Adding AWS Cognito Users to a Group on Sign Up

avatar

Borislav Hadzhiev

Thu Apr 22 20212 min read

Updated on Thu Apr 22 2021

Automatically Adding Cognito Users to a Group on Sign up #

In order to add a Cognito user to a group when they sign up, we have to use the Post Confirmation lambda trigger.

This trigger is a Lambda function that gets invoked automatically after a user has confirmed their account.

post confirmation trigger

Implementing the Post Confirmation Trigger #

The Post Confirmation lambda trigger needs to have the IAM permission to execute the cognito-idp:AdminAddUserToGroup action on the User Pool.

Let's define the lambda function that is going to add the Cognito users to a group after they register:

src/post-confirmation-trigger/index.ts
import {Callback, Context, PostConfirmationTriggerEvent} from 'aws-lambda'; import AWS from 'aws-sdk'; export async function main( event: PostConfirmationTriggerEvent, _context: Context, callback: Callback, ): Promise<void> { const {userPoolId, userName} = event; try { await adminAddUserToGroup({ userPoolId, username: userName, groupName: 'Users', }); return callback(null, event); } catch (error) { return callback(error, event); } } export function adminAddUserToGroup({ userPoolId, username, groupName, }: { userPoolId: string; username: string; groupName: string; }): Promise<{ $response: AWS.Response<Record<string, string>, AWS.AWSError>; }> { const params = { GroupName: groupName, UserPoolId: userPoolId, Username: username, }; const cognitoIdp = new AWS.CognitoIdentityServiceProvider(); return cognitoIdp.adminAddUserToGroup(params).promise(); }

In the code snippet every user who successfully confirms their account gets added to the Users group.

The lambda receives the user pool id and the username in the event object, so all we have to specify is the name of the group we want to add the user to.

After you create the Lambda function you have to set it as a Post Confirmation trigger in the User Pool.

Discussion #

In order to automatically add a Cognito user to a group we have to set a Post confirmation trigger in our User pool. The lambda function will automatically get invoked after a user confirms their account.

The function is passed the User Pool id and the username in the event object, so all we have to add is the name of the Group we want to add the user to.

Note that the function has to have permission to execute the cognito-idp:AdminAddUserToGroup action.

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee