CORS

CORS on AWS Lambda — API Gateway Configuration

AWS API Gateway handles CORS at the gateway level — separate from your Lambda function. You need to configure both. Missing either one and the browser error is the same: no CORS headers.

Step 1 — Enable CORS in API Gateway

In the API Gateway console: select your resource → Actions → Enable CORS. This adds an OPTIONS method that returns CORS headers. Set the values to match your frontend domain.

# Using AWS SAM template
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      Cors:
        AllowOrigin: "'https://yourapp.com'"
        AllowHeaders: "'Content-Type,Authorization'"
        AllowMethods: "'GET,POST,PUT,DELETE,OPTIONS'"
        AllowCredentials: "'true'"

Step 2 — Lambda must also return CORS headers

API Gateway's CORS config handles the OPTIONS preflight. But your Lambda function response headers are what the browser sees on actual GET/POST calls. Your function must also include them:

// Node.js Lambda handler
exports.handler = async (event) => {
  const origin = event.headers?.origin || event.headers?.Origin;

  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': 'https://yourapp.com',
      'Access-Control-Allow-Credentials': 'true',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ data: 'ok' }),
  };
};

Using AWS CDK

const api = new apigateway.RestApi(this, 'MyApi', {
  defaultCorsPreflightOptions: {
    allowOrigins: ['https://yourapp.com'],
    allowMethods: apigateway.Cors.ALL_METHODS,
    allowHeaders: ['Content-Type', 'Authorization'],
    allowCredentials: true,
  },
});

Common mistake

Enabling CORS in API Gateway but not returning CORS headers from the Lambda function. The preflight passes (OPTIONS returns 204) but the actual request fails because the response from Lambda has no Access-Control-Allow-Origin header.

Test your Lambda CORS config →