How to sync data or trigger a Lambda when Cognito user attributes change

amazon-lambdaamazon-web-services

I'm trying to sync user data (name + some custom attributes) from an AWS Cognito user pool to a DynamoDB table. Cognito has a lot of triggers related to sign in / sign up but I haven't found any trigger that is fired when user attributes are updated.

How can I trigger a Lambda or otherwise sync data when user attributes change?

Best Answer

I had the same problem. I store email, family_name and given_name in cognito as part of sign up process. Then users can change any of these fields at any time.

I couldn't find a way to track these changes as the documentation doesn't state any such lambda trigger for sync events. However, since the idToken contains the user attributes in my case, it has to update itself after user makes a change. So I tested this and found that the Pre-Token trigger is invoked any time there is a change in the user attributes so that it can regenerate a new token. That lambda contains the following payload

{
  version: '1',
  triggerSource: 'TokenGeneration_RefreshTokens',
  region: 'XXX',
  userPoolId: '',
  userName: 'XXX',
  callerContext: {
    awsSdkVersion: 'aws-sdk-unknown-unknown',
    clientId: 'XXX'
  },
  request: {
    userAttributes: {
      sub: 'XXX',
      email_verified: 'false',
      'cognito:user_status': 'CONFIRMED',
      'cognito:email_alias': 'user1@mailinator.com',
      given_name: 'Name',
      family_name: 'New',
      email: 'user1@mailinator.com'
    },
    groupConfiguration: {
      groupsToOverride: [],
      iamRolesToOverride: [],
      preferredRole: null
    }
  },
  response: { claimsOverrideDetails: null }
}

So I update the records in dynamodb in this lambda itself. I am not 100% sure though because the documentation doesn't say anything about this use case and pre token trigger. Give it a try and see.

Related Topic