Creating a Cognito Trigger using CDK and TypeScript
Tags: awslambda, typescript, aws
Published: 2024-03-04 21:54:48

---
title: Creating a Cognito Trigger using CDK and TypeScript
published: true
date: 2024-03-04 21:49:44 UTC
tags: awslambda,typescript,aws
# canonical_url: https://medium.com/@luisvaldeszero/creating-a-cognito-trigger-using-cdk-and-typescript-eacce6312575
canonical_url: https://valdes.com.br/creating-a-cognito-trigger-using-cdk-and-typescript-eacce6312575
---

In the current scenario we want our users to be able to sign up for an account, and when the user confirms its account, in the post confirmation event from Cognito, we want to run a lambda function to add the record from the user to a DynamoDB table

![](https://cdn-images-1.medium.com/max/1024/1*0_SRYGgjN_NqbvCBUEnemw.jpeg)

#### Requirements

- git
- NodeJS 14 or later, my version is v18.18.0
- An AWS account and configured credentials
- Install [cdk command](https://docs.aws.amazon.com/cdk/v2/guide/cli.html/)
- docker

#### TL;DR;

Clone [the repo](https://github.com/kavichu/aws-appsync-typescript) and follow the instructions to deploy the project, you can use the gitpod configuration which comes with nodejs, aws cli v2, docker and cdk installed

#### Create the Users Table

In this snippet we are creating a table with a partition key with the name of id and type string, then we are granting read and write data permission to a role called lambdaRole

```typescript
const usersTable = new dynamodb.Table(this, 'UsersTable', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
});
usersTable.grantReadWriteData(lambdaRole)
```

#### Create post confirmation lambda function

We fill the parameters with their respective values, notice that we are passing the DynamoDB table name of usersTable as an environment variable, we are going to use this environment variable in the lambda code, in the last part of the snippet we se that we call the addTrigger method of the userPool, we pass as parameter the type of operation and a lambda function construct

```typescript
const postConfirmation = new lambda_nodejs.NodejsFunction(this, "PostConfirmationLambdaFunction", { 
  entry: path.join(__dirname, '../functions/postConfirmation/index.ts'),
  handler: 'postConfirmation',
  runtime: lambda.Runtime.NODEJS_20_X,
  environment: {
    'USERS_TABLE': usersTable.tableName
  },
  role: lambdaRole,
  timeout: cdk.Duration.seconds(30)
})

userPool.addTrigger(cognito.UserPoolOperation.POST_CONFIRMATION, 
  postConfirmation
);
```

Lets take a look at the code that runs inside the lambda function, we import the type of event from the aws-lambda module, and then we create a PutCommand using the enviroment variable USERS\_TABLE

```typescript
import { PostConfirmationTriggerEvent } from "aws-lambda";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const documentClient = DynamoDBDocumentClient.from(client);

export const postConfirmation = async (event: PostConfirmationTriggerEvent ) => {

  const createdAt = new Date().toJSON()
  const { userAttributes } = event.request

  const data = {
    id: userAttributes['sub'],
    email: userAttributes['email'],
    createdAt
  }

  const command = new PutCommand({
    TableName: process.env.USERS_TABLE,
    Item: data
  });

  await documentClient.send(command);

  return event
}
```

#### Conclusion

We created a DynamoDB table, granted permission to an iam role, then created a lambda function and added a trigger to the user pool, in future posts we are going to use our users table