
This has become very common to use AWS Cognito as an authentication system in modern days. Using Cognito, when a user signs up or gets an invitation from another user, he gets an email with password and verification codes. But the email is in simple plain text. But we can easily configure a lambda function that can customize and beautify this email according to our needs.
To configure the lambda, first, we have to understand the states when we can actually trigger a lambda from Cognito. These states are (source):
- CustomMessage_SignUp : Custom message — To send the confirmation code post-sign-up.
- CustomMessage_AdminCreateUser : Custom message — To send the temporary password to a new user.
- CustomMessage_ResendCode : Custom message — To resend the confirmation code to an existing user.
- CustomMessage_ForgotPassword : Custom message — To send the confirmation code for Forgot Password request.
- CustomMessage_UpdateUserAttribute : Custom message — When a user’s email or phone number is changed, this trigger sends a verification code automatically to the user. Cannot be used for other attributes.
- CustomMessage_VerifyUserAttribute : Custom message — This trigger sends a verification code to the user when they manually request it for a new email or phone number.
- CustomMessage_Authentication : Custom message — To send MFA code during authentication.
For convenience, we will only focus on the first two and hope that you can easily configure for the others. Now let’s configure the lambda.
Go to the Lambda console and click create a function and give it a name and node version then create it. Now for the code part, follow the below:
‘use strict’; exports.handler = async (event, context, callback) => { const email = event.request.userAttributes.email; const link = `https://example.com?userName=${email}&confirmation\_code=${event.request.codeParameter}\`; const name = event.request.userAttributes.name; const template = (name,link) => `
<img fetchpriority=“high” fetchpriority=“high” decoding=“async” style=“border: 0;display: block;height: auto; width: 100%;max-width: 373px;” alt=“Animage” height=“200” width=“300” src=“https://publish.example.com/main-logo.png” />
<h2 style=“font-size: 28px; margin-top: 20px; margin-bottom: 0;font-style: normal; font-weight: bold; color: #000;font-size: 24px;line-height: 32px;text-align: center;”>Hi ${name}
Your registration request was successfully approved. Click below to complete the registration
const templateInvite = (name,email,code)=> ` <body style=“ background-color: #333; font-family: PT Sans, Trebuchet MS, sans-serif; “ > <div style=“ margin: 0 auto; width: 600px; background-color: #fff; font-size: 1.2rem; font-style: normal; font-weight: normal; line-height: 19px; “ align=“center” >