Functions
To use Functions with the preview version of Amplify (Gen 2), you must use the AWS CDK. In the following sections, we walk through installing the CDK library package and building an example backend function using the CDK.
To get started, install the CDK library package:
1npm add --save-dev aws-cdk-lib
Example - Create a Function trigger for Auth
You can use the NodejsFunction
construct in the AWS CDK to create the Function definition, and apply it to the Amplify-generated Amazon Cognito resource as a Cognito trigger. This is made possible through the L2 UserPool
construct and its provided .addTrigger()
method.
First, create the trigger's shell of a Function handler by creating a file at amplify/custom/post-confirmation.ts
with the following contents:
1// amplify/custom/post-confirmation.ts2import type { PostConfirmationTriggerHandler } from 'aws-lambda';3
4export const handler: PostConfirmationTriggerHandler = async (event) => {5 console.log('event: ', JSON.stringify(event));6};
Next, create the instance of NodejsFunction
using the scaffolding below, and use the .addTrigger()
method to set the Function on your Amazon Cognito resource.
1// amplify/backend.ts2import * as url from 'node:url';3import * as cognito from 'aws-cdk-lib/aws-cognito';4import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs';5import { defineBackend } from '@aws-amplify/backend';6import { auth } from './auth/resource.js';7import { data } from './data/resource.js';8
9const backend = defineBackend({10 auth,11 data12});13
14// create function stack for the auth triggers15const authTriggerStack = backend.createStack('AuthTriggerStack');16
17// create the PostConfirmation trigger18const postConfirmationTrigger = new lambda.NodejsFunction(19 authTriggerStack,20 'PostConfirmation',21 {22 entry: url.fileURLToPath(23 new URL('./custom/post-confirmation.ts', import.meta.url)24 )25 }26);27
28// add the newly created trigger to the auth resource29const userPool = backend.resources.auth.resources.userPool as cognito.UserPool;30userPool.addTrigger(31 cognito.UserPoolOperation.POST_CONFIRMATION,32 postConfirmationTrigger33);