Guide · AWS Cognito · Lambda Triggers
AWS Cognito Lambda Triggers in MCP Servers — Pre-Signup, Post-Confirmation, Pre-Token-Generation
Cognito Lambda triggers let you inject custom logic at every key point in the authentication lifecycle without maintaining a separate auth service. The pre-signup trigger runs synchronously before a user record is created — ideal for blocking disposable email domains, enforcing invite-only access, or auto-verifying email addresses for known corporate domains. The post-confirmation trigger fires after email or phone verification completes — the right place to provision a DynamoDB user record, grant default permissions, or send a welcome email. The pre-token-generation trigger runs before every token issuance — use it to inject custom attributes as JWT claims so MCP tool handlers can read plan tier, org ID, or feature flags directly from the bearer token without a database round-trip. The custom auth challenge trigger chain enables passwordless authentication flows (magic link, TOTP, WebAuthn). This guide covers the event/response contract for each trigger and production patterns for wiring them into an MCP server backend.
TL;DR
Attach a Lambda to a Cognito trigger by updating the user pool's LambdaConfig via UpdateUserPoolCommand. Each trigger receives a structured event object and must return it (modified). Pre-signup: set event.response.autoVerifyEmail = true to skip email confirmation for whitelisted domains; throw an error to block sign-up. Post-confirmation: provision the user record in your data layer — this fires exactly once per user. Pre-token-generation (V2_0 trigger): modify event.response.claimsAndScopeOverrideDetails to inject custom claims into the access token. All trigger Lambdas must respond within 5 seconds or Cognito fails the authentication attempt.
Wiring Lambda triggers to a user pool
import {
CognitoIdentityProviderClient,
UpdateUserPoolCommand,
} from '@aws-sdk/client-cognito-identity-provider';
const cognito = new CognitoIdentityProviderClient({ region: 'us-east-1' });
await cognito.send(new UpdateUserPoolCommand({
UserPoolId: 'us-east-1_XXXXXXXXX',
LambdaConfig: {
PreSignUp: 'arn:aws:lambda:us-east-1:123456789012:function:cognito-pre-signup',
PostConfirmation: 'arn:aws:lambda:us-east-1:123456789012:function:cognito-post-confirmation',
PreTokenGenerationConfig: {
LambdaArn: 'arn:aws:lambda:us-east-1:123456789012:function:cognito-pre-token',
LambdaVersion: 'V2_0', // V2_0 supports access token claim injection (V1_0 only affects ID token)
},
// Custom auth challenge chain (three functions, all required together):
DefineAuthChallenge: 'arn:aws:lambda:us-east-1:123456789012:function:cognito-define-challenge',
CreateAuthChallenge: 'arn:aws:lambda:us-east-1:123456789012:function:cognito-create-challenge',
VerifyAuthChallengeResponse: 'arn:aws:lambda:us-east-1:123456789012:function:cognito-verify-challenge',
},
}));
Cognito invokes trigger Lambdas synchronously with the cognito-idp.amazonaws.com principal. Add a resource-based policy to each Lambda granting this invocation:
# CLI — grant Cognito permission to invoke the Lambda
aws lambda add-permission \
--function-name cognito-pre-signup \
--statement-id cognito-invoke \
--principal cognito-idp.amazonaws.com \
--action lambda:InvokeFunction \
--source-arn arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_XXXXXXXXX
The source-arn condition scopes the permission to your specific user pool, preventing confused-deputy attacks where another Cognito pool invokes your trigger Lambda.
Pre-signup trigger: domain gating and invite-only access
import type { PreSignUpTriggerEvent } from 'aws-lambda';
import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb';
const db = new DynamoDBClient({ region: 'us-east-1' });
// Disposable email domains to block
const BLOCKED_DOMAINS = new Set([
'mailinator.com', 'guerrillamail.com', 'throwaway.email',
'temp-mail.org', 'yopmail.com', '10minutemail.com',
]);
export const handler = async (event: PreSignUpTriggerEvent): Promise<PreSignUpTriggerEvent> => {
const email = event.request.userAttributes.email ?? '';
const domain = email.split('@')[1]?.toLowerCase();
if (!domain) throw new Error('Email address is required');
// Block disposable email domains
if (BLOCKED_DOMAINS.has(domain)) {
throw new Error(`Sign-ups from ${domain} are not allowed`);
}
// Invite-only mode: check DynamoDB allowlist
if (process.env.INVITE_ONLY === 'true') {
const { Item } = await db.send(new GetItemCommand({
TableName: process.env.INVITES_TABLE!,
Key: { email: { S: email.toLowerCase() } },
}));
if (!Item) {
throw new Error('This email address has not been invited. Join the waitlist at alivemcp.com.');
}
}
// Auto-verify email for known corporate domains (skip confirmation email)
const TRUSTED_DOMAINS = new Set((process.env.TRUSTED_DOMAINS ?? '').split(',').filter(Boolean));
if (TRUSTED_DOMAINS.has(domain)) {
event.response.autoVerifyEmail = true;
event.response.autoConfirmUser = true;
}
return event;
};
Throwing any error from the pre-signup trigger causes Cognito to return an error response to the client with the error message as the description. Keep error messages user-friendly — they are shown in the Hosted UI and returned by the API. Do not include internal details like table names or ARNs.
Setting autoConfirmUser: true skips the email verification step entirely and immediately activates the user. Set this only for domains you control (SSO federations, internal tooling) — never set it based on user-supplied data.
Post-confirmation trigger: provisioning the user record
import type { PostConfirmationTriggerEvent } from 'aws-lambda';
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb';
const db = new DynamoDBClient({ region: 'us-east-1' });
export const handler = async (
event: PostConfirmationTriggerEvent,
): Promise<PostConfirmationTriggerEvent> => {
// Only provision on email confirmation, not on admin-create-user confirmation
if (event.triggerSource !== 'PostConfirmation_ConfirmSignUp') {
return event;
}
const userId = event.userName; // Cognito sub UUID
const email = event.request.userAttributes.email;
const now = new Date().toISOString();
await db.send(new PutItemCommand({
TableName: process.env.USERS_TABLE!,
Item: {
pk: { S: `USER#${userId}` },
sk: { S: 'PROFILE' },
userId: { S: userId },
email: { S: email },
plan: { S: 'free' }, // default tier
createdAt: { S: now },
updatedAt: { S: now },
// Pre-allocate API quota row
apiCallsThisMonth: { N: '0' },
apiQuotaLimit: { N: '1000' },
},
ConditionExpression: 'attribute_not_exists(pk)', // idempotent — ignore if already exists
}));
return event;
};
The post-confirmation trigger fires exactly once when the user confirms their email. However, Lambda can be invoked more than once due to retries — the ConditionExpression: 'attribute_not_exists(pk)' makes the write idempotent. If DynamoDB throws ConditionalCheckFailedException, the user record already exists; swallow that error and return the event normally.
The triggerSource field distinguishes between confirmation flows: PostConfirmation_ConfirmSignUp fires after a user confirms their own registration; PostConfirmation_ConfirmForgotPassword fires after a password reset confirmation. Do not re-provision users on password reset — check triggerSource before creating records.
Pre-token-generation trigger V2_0: injecting custom claims
import type { PreTokenGenerationV2TriggerEvent } from 'aws-lambda';
import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb';
const db = new DynamoDBClient({ region: 'us-east-1' });
export const handler = async (
event: PreTokenGenerationV2TriggerEvent,
): Promise<PreTokenGenerationV2TriggerEvent> => {
const userId = event.userName;
// Fetch current plan and org from DynamoDB
const { Item } = await db.send(new GetItemCommand({
TableName: process.env.USERS_TABLE!,
Key: { pk: { S: `USER#${userId}` }, sk: { S: 'PROFILE' } },
}));
const plan = Item?.plan?.S ?? 'free';
const orgId = Item?.orgId?.S ?? '';
const features = Item?.features?.SS ?? [];
// V2_0: inject into both ID token and access token claims
event.response.claimsAndScopeOverrideDetails = {
idTokenGeneration: {
claimsToAddOrOverride: {
'custom:plan': plan,
'custom:org_id': orgId,
'custom:features': features.join(','),
},
claimsToSuppress: [],
groupOverrideDetails: {},
},
accessTokenGeneration: {
claimsToAddOrOverride: {
'custom:plan': plan, // access token claims — available in MCP bearer token
'custom:org_id': orgId,
},
claimsToSuppress: [],
scopesToAdd: [],
scopesToSuppress: [],
},
};
return event;
};
The V2_0 trigger version (set via LambdaVersion: 'V2_0' in PreTokenGenerationConfig) can inject claims into the access token as well as the ID token. The older V1_0 only modified the ID token. MCP servers that validate bearer tokens (access tokens) need V2_0 to read custom plan/org claims without a separate database lookup per request.
Custom claim names must be prefixed with custom: for user-defined claims in Cognito. The total compressed JWT payload must remain under 4 KB — avoid injecting large arrays or nested objects. Serialize feature flags as a comma-separated string rather than a JSON array if you have more than a few flags.