2

I set the following lambda function as the post-confirmation trigger in Cognito. Anyone know why I'm receiving "Invalid lambda function output : Invalid JSON"?

I'm getting log from "console.log("params", params)" in CloudWatch but not from "console.log("inside adminAddUserToGroup", params)".

const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
const lambda = new AWS.Lambda();

type TriggerEvent = {
  version: string,
  region: string,
  userPoolId: string,
  userName: string,
  callerContext: {
    awsSdkVersion: string,
    clientId: string
  },
  triggerSource: string,
  request: {
    userAttributes: {
        sub: string,
        'cognito:email_alias': string,
        'cognito:user_status': string,
        birthdate: string,
        email_verified: string,
        gender: string,
        preferred_username: string,
        email: string
    }
  },
  response: {}
}

exports.handler = async (event:TriggerEvent, context: any, callback: any) => {
    var cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({ apiVersion: '2016-04-18' });

    console.log("event", event);
    var params = {
        GroupName: 'customers',
        UserPoolId: event.userPoolId,  
        Username: event.userName
    };
    console.log("params", params)
    try {
        cognitoIdentityServiceProvider.adminAddUserToGroup(params, function(err: any, data: any) {
            console.log("inside adminAddUserToGroup", params)
            if (err) {
                console.log(err, err.Stack);
                context.done(err);
            }
            context.done();
        });
    } catch (err) {
        console.log("Add user to group catch err", err);
        context.fail("Add user to group catch err");
    }

}

Thanks.

codehell
  • 21
  • 1

1 Answers1

0

There are two different problems in the code:

Fixing the missing output of console.log("inside adminAddUserToGroup", params):

You should await on the adminAddUserToGroup(..).promise(), otherwise the lambda will proceed and complete before the adminAddUserToGroup fully executes. You can check this by adding a console.log("Lambda completed") after the try/catch block and see that it does show.

Fix it with:

await cognitoIdentityServiceProvider.adminAddUserToGroup(params, function(err: any, data: any) {
    console.log("inside adminAddUserToGroup", params)
    if (err) {
        console.log(err, err.Stack);
        context.done(err);
    }
    context.done();
}).promise();

Fixing the "Invalid lambda function output : Invalid JSON" response:

You need to return the event, usage of context.done() is deprecated and, since you are using an async handler, you should use return or throw, for success and failure respectively, as per the AWS documentation on Async handler for Typescript.

Fix it by replacing context.done(); with return event;.

ammendonca
  • 541
  • 4
  • 7