How to get Cognito User Pool ID and the App client Id in Lambda

I am trying to create a cognito user pool ID and the app client using Serverless.yml file

I am referring this link -

I want to use this Cognito user pool id in my code.

Is there any way I can get this User Pool ID and app client ID in my lambda code?

Is there any way serverless can create some envieonment variables, which can hold the values for user pool ID and the App client ID?

3 Likes

Hi, you can do it in this way

resources:
....
  Outputs:
    UserPoolId:
      Value:
        Ref: CognitoUserPool
      Export:
        Name: ${self:provider.stage}-UserPoolId

    UserPoolClientId:
      Value:
        Ref: CognitoUserPoolClient
      Export:
        Name: ${self:provider.stage}-UserPoolClientId
functions:
   your-function:
     ....
     environment:
       USER_POOL_ID: !ImportValue ${self:provider.stage}-UserPoolId
       USER_POOL_CLIENT_ID: !ImportValue ${self:provider.stage}-UserPoolClientId

your-function.js

   const { USER_POOL_ID, USER_POOL_CLIENT_ID } = process.env;
   ...

p.s.
If your functions + resources are in the same stack - you can just use USER_POOL_ID: !Ref CognitoUserPool and USER_POOL_CLIENT_ID: !Ref CognitoUserPoolClient

2 Likes

Thanks for solution ! it works

@moro - Hey I can access these two. However, I am unable to access the Client secret in lambda. How do I access that? I checked on the web but could not find any solution to this.
Thanks in advance :slight_smile:

Hi, could you pls try this https://stackoverflow.com/a/53968945/1268283 ? I hope I understood your question correctly.

Hi, moro.
Could you teach me how to get Cognito userPoolId in AWS amplify react app?
I want to delete a user in the AWS Cognito user pool.

const params = { Username: selectedRows[i], UserPoolId: process.env.REACT_APP_COGNITO_USER_POOL_ID };

    const result = await new Promise((resolve, reject) => {

      cognito.adminDeleteUser(params, (err, data) => {

        console.log(err)

        if (err) {

          reject(err);

          return;

        }

        resolve(data);

      });

    });

Thanks for the solution