Home > Software engineering >  Cognito - Error: Invalid UserPoolId format
Cognito - Error: Invalid UserPoolId format

Time:04-12

I am using AWS CDK to create a userpool and userpool client. I would like to be able to access the userpool id and userpool client id from a lambda once they have been created. I pass these two values to the lambda via environmental variables. Here is my code:

import { Construct } from 'constructs';
import {
  IResource,
  LambdaIntegration,
  MockIntegration,
  PassthroughBehavior,
  RestApi,
} from 'aws-cdk-lib/aws-apigateway';
import {
  NodejsFunction,
  NodejsFunctionProps,
} from 'aws-cdk-lib/aws-lambda-nodejs';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
import * as amplify from 'aws-cdk-lib/aws-amplify';

import {
  aws_s3,
  aws_ec2,
  aws_rds,
  aws_cognito,
  aws_amplify,
  Duration,
  CfnOutput,
} from 'aws-cdk-lib';

export class FrontendService extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    const userPool = new aws_cognito.UserPool(this, 'userpool', {
      userPoolName: 'frontend-userpool',
      selfSignUpEnabled: true,
      signInAliases: {
        email: true,
      },
      autoVerify: { email: true },
    });

    const userPoolClient = new aws_cognito.UserPoolClient(
      this,
      'frontend-app-client',
      {
        userPool,
        generateSecret: false,
      }
    );

    const bucket = new aws_s3.Bucket(this, 'FrontendStore');

    const nodeJsFunctionProps: NodejsFunctionProps = {
      environment: {
        BUCKET: bucket.bucketName,
        DB_NAME: 'hospoFEDB',
        AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
        USER_POOL_ID: userPool.userPoolId,
        USER_POOL_CLIENT_ID: userPoolClient.userPoolClientId,
      },
      runtime: Runtime.NODEJS_14_X,
    };

    const registerLambda = new NodejsFunction(this, 'registerFunction', {
      entry: 'dist/lambda/register.js',
      memorySize: 1024,
      ...nodeJsFunctionProps,
    });

    const registerIntegration = new LambdaIntegration(registerLambda);

    const api = new RestApi(this, 'frontend-api', {
      restApiName: 'Frontend Service',
      description: 'This service serves the frontend.',
    });

    const registerResource = api.root.addResource('register');
    registerResource.addMethod('POST', registerIntegration);
  }
}

Here is my lambda function and how I intend to use the USER_POOL_ID and USER_POOL_CLIENT_ID env variables:

import {
  CognitoUserPool,
} from 'amazon-cognito-identity-js';

export const handler = async (event: any, context: any) => {
  try {
    console.log(process.env.USER_POOL_ID);
    console.log(process.env.USER_POOL_CLIENT_ID);

    const userPool = new CognitoUserPool({
      UserPoolId: process.env.USER_POOL_ID as string,
      ClientId: process.env.USER_POOL_CLIENT_ID as string,
    });

    return {
      statusCode: 200,
    };
  } catch (error) {
    if (error instanceof Error) {
      const body = error.stack || (JSON.stringify(error, null, 2) as any);
      return {
        statusCode: 400,
        headers: {},
        body: JSON.stringify(body),
      };
    }
    return {
      statusCode: 400,
    };
  }
};

The idea with this setup is that I would create a cognito user pool and client then be able to pass those id's directly down. Currently if I run this locally via sam local start-api it generates the following USER_POOL_ID : Frontenduserpool87772999. If I try and use this id in the new CognitoUserPool({... part of my lambda function I get the following error:

Error: Invalid UserPoolId format.

If I deploy the app however and execute the lambda function from the deployed environment with the exact same code I get a USER_POOL_ID that looks more like: us-east-1_HAjkUj9hP. This works fine and I do not get the error above.

Should I assume that I can not create a user pool locally and will always have to point to the deployed user pool?

CodePudding user response:

Should I assume that I can not create a user pool locally and will always have to point to the deployed user pool

Yes. See the docs: start-api creates an emulated local API endpoint and Lambda for local testing. It does not deploy or emulate other resources.

You can reference previously deployed AWS resources by passing a JSON file with the deployed physical values using the --env-vars flag.

  • Related