question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

sam local start-api gives CORS error when CORS are enabled

See original GitHub issue

Description:

I am using AWS CDK (Typescript) and running SAM local start-api to spin up a RESTful API tied to lambda resolvers and am running into a CORS issue when trying to hit the API from a browser.

Steps to reproduce:

CDK config:

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 { join } from 'path';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as cdk from 'aws-cdk-lib';

export function addCorsOptions(apiResource: IResource) {
  apiResource.addMethod(
    'OPTIONS',
    new MockIntegration({
      integrationResponses: [
        {
          statusCode: '200',
          responseParameters: {
            'method.response.header.Access-Control-Allow-Headers':
              "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
            'method.response.header.Access-Control-Allow-Origin': "'*'",
            'method.response.header.Access-Control-Allow-Credentials':
              "'false'",
            'method.response.header.Access-Control-Allow-Methods':
              "'OPTIONS,GET,PUT,POST,DELETE'",
          },
        },
      ],
      passthroughBehavior: PassthroughBehavior.NEVER,
      requestTemplates: {
        'application/json': '{"statusCode": 200}',
      },
    }),
    {
      methodResponses: [
        {
          statusCode: '200',
          responseParameters: {
            'method.response.header.Access-Control-Allow-Headers': true,
            'method.response.header.Access-Control-Allow-Methods': true,
            'method.response.header.Access-Control-Allow-Credentials': true,
            'method.response.header.Access-Control-Allow-Origin': true,
          },
        },
      ],
    }
  );
}

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

    const vpc = new ec2.Vpc(this, 'HospoFEVPC');
    const cluster = new rds.ServerlessCluster(this, 'AuroraHospoFECluster', {
      engine: rds.DatabaseClusterEngine.AURORA_POSTGRESQL,
      parameterGroup: rds.ParameterGroup.fromParameterGroupName(
        this,
        'ParameterGroup',
        'default.aurora-postgresql10'
      ),
      defaultDatabaseName: 'hospoFEDB',
      vpc,
      scaling: {
        autoPause: cdk.Duration.seconds(0),
      },
    });

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

    const nodeJsFunctionProps: NodejsFunctionProps = {
      environment: {
        BUCKET: bucket.bucketName,
        CLUSTER_ARN: cluster.clusterArn,
        SECRET_ARN: cluster.secret?.secretArn || '',
        DB_NAME: 'hospoFEDB',
        AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
      },
      runtime: Runtime.NODEJS_14_X,
    };

    const loginLambda = new NodejsFunction(this, 'loginFunction', {
      entry: 'dist/lambda/login.js',
      memorySize: 1024,
      ...nodeJsFunctionProps,
    });

    const loginIntegration = new LambdaIntegration(loginLambda);

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

    const loginResource = api.root.addResource('login');
    loginResource.addMethod('POST', loginIntegration);
    addCorsOptions(loginResource);
  }
}

lambda resolver (login.js)

export async function handler(event: any, context: any) {
    return {
      statusCode: 200,
      headers: { 'Access-Control-Allow-Origin': '*' },
      body: JSON.stringify(body),
    };
}

Observed result:

When running locally using sam start local-api I get a CORS error mentioning it does not pass preflight. This error only occurs locally, when the lambda is eployed to AWS I do not get any CORS errors

Expected result:

With the Access-Control-Allow-Origin header set in the lambda response and mock integration for the options request I would expect it to not give me any CORS errors

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

I am on SAM version 1.46.0 on the latest Ubuntu distribution. I have also tried configuring CORS via the CDK RestApi config like so:

new apigateway.RestApi(this, 'api', {
  defaultCorsPreflightOptions: {
    allowOrigins: apigateway.Cors.ALL_ORIGINS,
    allowMethods: apigateway.Cors.ALL_METHODS // this is also the default
  }
})

But it just gives me the following error: lIIl3

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
thomas-yaacommented, May 11, 2022

@mildaniel I ran into this exact same problem. I upgraded to 1.49 and now it works without modification.

1reaction
mildanielcommented, May 10, 2022

Hi @redhouse877, can you try updating to the latest version of sam-cli. In version 1.47.0 we released a fix to read CORS configurations from AWS::ApiGateway::Method resources which we weren’t doing previously. I’m not certain that this resolves your issue too but let us know!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Enable CORS when running AWS SAM CLI locally
When I change it to POST this is when it fails. The command I am running: sam local start-api. And my template.yaml is:...
Read more >
Serverless-Fixed CORS with SAM on full stack local ... - AWS Tip
3 steps fixed CORS issue. 1. Configure CORS on API resource. Configure CORS on Api resource on template.yaml file. CORS configuration is depended...
Read more >
CorsConfiguration - AWS Serverless Application Model
Manage cross-origin resource sharing (CORS) for your API Gateway APIs. Specify the domain to allow as a string or specify a dictionary with...
Read more >
Problems with CORS when creating Creating API's from ...
I'd ideally like to be able to configure in the CF / SAM templates and just deploy it.. But i'm not sure what...
Read more >
Tutorial: Deploying a Hello World application - 亚马逊云科技
Amazon SAM CLI error: "Running Amazon SAM projects locally requires Docker. Have you got it installed?" When running the sam local start-api command,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found