How to add confirmed user data from Cognito to DynamoDB table using serverless framework.

Hello guys, last week our project leader came up with a new requirement that is user registration for a certification portal but after registering them we want to use their user data for emailing and another purpose so I tried to search a way how to add this new user data to dynamodb table. and i found out how to do that using serverless framework.

so in this article, we are going to talk about adding confirmed Cognito user data to dynamodb table using serverless framework.

okay, let’s try out,

first of all, you should create a new dynamodb table. I named it as users you can name it as whatever name you want.

then you should create a new Cognito user pool. I named it as articleusers you can name it as you wish.

now comes the most important part. ( i assumed that you’ve already installed serverless and setup the CLI credentials).

now you have to bootstrap the project by typing

serverless create --template aws-nodejs

this will create a boilerplate for you. it will generate .gitignore folder, handler.js file and serverless.yml file. Okey let’s see how should be our serverless.yml file

service: syncService

myRegion: us-east-1
myDDB: users
myPool: articleusers

name: aws
runtime: nodejs8.10

handler: cognitoToDDB.handler
- cognitoUserPool:
pool: ${self:custom.myPool}
trigger: PostConfirmation
existing: true
role: CustomUserOnboardingRole
TABLE_NAME: ${self:custom.myDDB}
REGION: ${self:custom.myRegion}

Type: AWS::IAM::Role
RoleName: CustomUserOnboardingRole
Version: '2012-10-17'
- Effect: Allow
Action: sts:AssumeRole
- PolicyName: CustomCloudWatchLogsPolicy
Version: '2012-10-17'
- Effect: Allow
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- 'Fn::Join':
- ':'
- 'arn:aws:logs'
- Ref: 'AWS::Region'
- Ref: 'AWS::AccountId'
- 'log-group:/aws/lambda/*:*:*'
- PolicyName: CustomUserOnboardingPolicy
Version: '2012-10-17'
- Effect: Allow
- dynamodb:PutItem
- 'Fn::Join':
- ':'
- 'arn:aws:dynamodb'
- Ref: 'AWS::Region'
- Ref: 'AWS::AccountId'
- 'table/${self:custom.myDDB}'

under the hood, this serverless.yml tells to aws that create a lambda function(which will consider later) that enter Cognito user data to dynamodb, not only that it will generate IAM roles and policies also. as you can see it creates the lambda function that names ‘UserOnboardingLambda’ and create IAM role ‘CustomUserOnboardingRole’ and the policies.

let’s see the handler.js we will rename it as cognitoToDDB.js for naming convention you can name it as you wish. actually this file contains our lambda function that do our task,

const aws = require('aws-sdk');
const ddb = new aws.DynamoDB({apiVersion: '2012-10-08'});
exports.handler = async (event, context) => {
const date = new Date();
const tableName = process.env.TABLE_NAME;
const region = process.env.REGION;
console.log(`table=${tableName} -- region=${region}`)
aws.config.update({ region });
if (!event.request.userAttributes.sub) {
// Nothing to do, the user's email ID is unknown
console.log("Error: Nothing was written to DDB or SQS");
return context.done(null, event);
// -- Write data to DDB
// If the required parameters are present, proceed
const ddbParams = {
TableName: tableName,
Item: {
'userId': {S: event.request.userAttributes.sub},
'sortKey': {S: "user"},
'email': {S:},
'createdDate': {S: date.toISOString()},
'firstLogin': {BOOL: true}
// Call DynamoDB
try {
ddbResult = await ddb.putItem(ddbParams).promise();
} catch (err) {
console.log("Error", err);
console.log("Success: Everything executed correctly")
context.done(null, event);

okay now we have to deploy the code. save all the files and type

serverless deploy

yey!!! that’s it.. after deploying successfully our user pool has post-confirmation trigger (it’s going to fire our lambda function after confirming the user)

and here’s the lambda function.


Congratulations, you’ve created a Lambda function invoked by a Cognito post-confirmation trigger by using serverless framework. I hope this article is helpful for you. see you guys in the next time. until then Happy coding!.




Software Engineer at hSenid Mobile

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Digging Into a Solopreneur’s “Experimentation Stack”

Managing internal and external developer experience in platform DX development

Setting Up Continuous Delivery for a Node.js REST API — Part 1

Number of the Day

Salesforce bizarre practices: SOQL Query Builder

Rails g Makes It Easy

Algorithm Complexity Simplified

Keywords and Identifiers in Python

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
hasanga lakdinu

hasanga lakdinu

Software Engineer at hSenid Mobile

More from Medium

High Availability Architecture with AWS CLI

Let’s Create Video Closed Caption with AWS Transcribe


Steps for Successful Migration from GitLab to GitHub