Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 30, 2024

Add user to group

You can use defineAuth and defineFunction to create a Cognito post confirmation Lambda trigger that extends the behavior to perform some action when a user is confirmed.

A user is "confirmed" when they verify their account. Typically this happens when the user confirms their email via the verification email. The post confirmation handler will not be triggered for federated sign-ins (i.e. social sign-in).

To get started, install the AWS SDK v3 package, which will be used to perform actions against your auth resource, and the @types/aws-lambda package, which is used to define the handler type:

Terminal
npm add --save-dev @aws-sdk/client-cognito-identity-provider @types/aws-lambda

Next, create a new directory and a resource file, amplify/auth/post-confirmation/resource.ts. Then, define the Function with defineFunction:

amplify/auth/post-confirmation/resource.ts
import { defineFunction } from '@aws-amplify/backend';
export const postConfirmation = defineFunction({
name: 'post-confirmation',
// optionally define an environment variable for your group name
environment: {
GROUP_NAME: 'EVERYONE'
}
});

After creating the Function definition you will need to:

  1. create the EVERYONE group
  2. grant access to your auth resource to ensure it can perform the addUserToGroup action
  3. set the Function as the post confirmation trigger
amplify/auth/resource.ts
import { defineAuth } from "@aws-amplify/backend";
import { postConfirmation } from "./post-confirmation/resource"
export const auth = defineAuth({
loginWith: {
email: true,
},
groups: ["EVERYONE"],
triggers: {
postConfirmation,
},
access: (allow) => [
allow.resource(postConfirmation).to(["addUserToGroup"]),
],
})

Then create the Function's corresponding handler file, amplify/auth/post-confirmation/handler.ts, file with the following contents:

amplify/auth/post-confirmation/handler.ts
import type { PostConfirmationTriggerHandler } from 'aws-lambda';
import {
CognitoIdentityProviderClient,
AdminAddUserToGroupCommand
} from '@aws-sdk/client-cognito-identity-provider';
import { env } from '$amplify/env/post-confirmation';
const client = new CognitoIdentityProviderClient();
// add user to group
export const handler: PostConfirmationTriggerHandler = async (event) => {
const command = new AdminAddUserToGroupCommand({
GroupName: env.GROUP_NAME,
Username: event.userName,
UserPoolId: event.userPoolId
});
const response = await client.send(command);
console.log('processed', response.$metadata.requestId);
return event;
};

After deploying the changes, whenever a user signs up and verifies their account they are automatically added to the group named "EVERYONE".