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

hasanga lakdinu
4 min readOct 20, 2019

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

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

provider:
name: aws
runtime: nodejs8.10

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

resources:
Resources:
CustomUserOnboardingRole:
Type: AWS::IAM::Role
Properties:
RoleName: CustomUserOnboardingRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: CustomCloudWatchLogsPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- 'Fn::Join':
- ':'
-
- 'arn:aws:logs'
- Ref: 'AWS::Region'
- Ref: 'AWS::AccountId'
- 'log-group:/aws/lambda/*:*:*'
- PolicyName: CustomUserOnboardingPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:PutItem
Resource:
- '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) => {
console.log(event);
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: event.request.userAttributes.email},
'createdDate': {S: date.toISOString()},
'firstLogin': {BOOL: true}
}
};
// Call DynamoDB
try {
ddbResult = await ddb.putItem(ddbParams).promise();
console.log("Success");
} 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.

Conclusion

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!.

--

--