I’ve seen a weird pattern with CORS on AWS projects: the infrastructure is “fully automated,” but CORS is still handled like a last-minute checkbox. Somebody adds '*', the browser still fails, and the team burns half a day staring at DevTools.

This case study is from a setup that’s very common:

  • React frontend hosted on S3 + CloudFront
  • API on API Gateway + Lambda
  • Infrastructure managed with AWS CDK in TypeScript
  • Cookies used for auth in production
  • Separate frontend domains for local, staging, and prod

The team thought they had CORS configured. They did not.

The setup

The app looked roughly like this:

  • https://app.example.com → frontend
  • https://api.example.com → API Gateway custom domain
  • http://localhost:3000 → local frontend

The frontend called endpoints like:

  • GET /me
  • POST /sessions
  • PATCH /profile

Authenticated requests included cookies, so fetch used credentials: 'include'.

That last detail matters a lot. If you use credentials, sloppy CORS config stops working fast.

The symptoms

The team reported:

  • GET requests sometimes worked in Postman but failed in the browser
  • POST and PATCH requests triggered preflight failures
  • Cookies weren’t being sent reliably
  • Error responses from Lambda appeared in the Network tab but were blocked by CORS in the app

Classic AWS CORS mess.

Before: the broken CDK

Here’s the sort of CDK code I usually find in these situations.

API Gateway with naive CORS

import * as cdk from 'aws-cdk-lib';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

export class ApiStack extends cdk.Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    const fn = new lambda.Function(this, 'ApiFn', {
      runtime: lambda.Runtime.NODEJS_20_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('lambda'),
    });

    const api = new apigateway.RestApi(this, 'Api', {
      defaultCorsPreflightOptions: {
        allowOrigins: apigateway.Cors.ALL_ORIGINS,
        allowMethods: apigateway.Cors.ALL_METHODS,
        allowHeaders: ['Content-Type', 'Authorization'],
      },
    });

    const me = api.root.addResource('me');
    me.addMethod('GET', new apigateway.LambdaIntegration(fn));

    const sessions = api.root.addResource('sessions');
    sessions.addMethod('POST', new apigateway.LambdaIntegration(fn));
  }
}

At first glance, this looks fine. API Gateway has CORS enabled. Problem solved, right?

Nope.

Lambda responses without CORS headers

export const handler = async (event: any) => {
  if (event.path === '/me') {
    return {
      statusCode: 200,
      body: JSON.stringify({ id: '123', email: '[email protected]' }),
    };
  }

  return {
    statusCode: 401,
    body: JSON.stringify({ error: 'Unauthorized' }),
  };
};

This is where people get tripped up. For REST APIs on API Gateway, preflight may be configured correctly, but your actual Lambda responses still need the right headers depending on your integration setup.

And if you’re using cookies, Access-Control-Allow-Origin: * is dead on arrival.

Why it failed

There were three separate problems.

1. Wildcard origin with credentials

The frontend used:

fetch('https://api.example.com/me', {
  credentials: 'include',
});

Browsers reject credentialed cross-origin requests if the server responds with:

Access-Control-Allow-Origin: *

You must return the exact requesting origin, and also:

Access-Control-Allow-Credentials: true

2. Preflight was incomplete for real requests

The app sent:

  • Content-Type: application/json
  • cookies
  • custom auth-related headers in some flows

That means browsers send an OPTIONS preflight request. If the preflight response is missing an allowed method, header, or credentials flag, the real request never happens.

3. Error responses were missing CORS headers

A lot of teams only test happy-path 200 responses. Then a 401 or 500 happens, and the browser blocks the response from JavaScript because the headers are missing. The API “works,” but the frontend gets a useless generic CORS error.

After: explicit, environment-aware CORS

The fix was to stop pretending one wildcard setting would cover every environment.

Step 1: define allowed origins in CDK

const allowedOrigins = [
  'http://localhost:3000',
  'https://staging.example.com',
  'https://app.example.com',
];

Step 2: configure API Gateway preflight properly

const api = new apigateway.RestApi(this, 'Api', {
  defaultCorsPreflightOptions: {
    allowOrigins: allowedOrigins,
    allowMethods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
    allowHeaders: [
      'Content-Type',
      'Authorization',
      'X-Requested-With',
    ],
    allowCredentials: true,
  },
});

That handles the browser’s OPTIONS requests correctly.

Step 3: return CORS headers from Lambda responses

I prefer a small helper so every code path stays consistent.

const allowedOrigins = new Set([
  'http://localhost:3000',
  'https://staging.example.com',
  'https://app.example.com',
]);

function corsHeaders(origin?: string) {
  if (origin && allowedOrigins.has(origin)) {
    return {
      'Access-Control-Allow-Origin': origin,
      'Access-Control-Allow-Credentials': 'true',
      'Vary': 'Origin',
    };
  }

  return {};
}

export const handler = async (event: any) => {
  const origin = event.headers?.origin || event.headers?.Origin;
  const headers = {
    'Content-Type': 'application/json',
    ...corsHeaders(origin),
  };

  if (event.path === '/me') {
    return {
      statusCode: 200,
      headers,
      body: JSON.stringify({ id: '123', email: '[email protected]' }),
    };
  }

  return {
    statusCode: 401,
    headers,
    body: JSON.stringify({ error: 'Unauthorized' }),
  };
};

That Vary: Origin header is a good habit, especially when anything in front of your API caches responses.

The result

After deployment:

  • local dev worked against the deployed API
  • staging and prod worked with cookies
  • preflight errors disappeared
  • frontend code could finally read real 401 and 500 responses

That last point matters more than people realize. A lot of “CORS bugs” are actually “my error response path forgot CORS headers” bugs.

What about exposed headers?

Most teams only think about Access-Control-Allow-Origin, but Access-Control-Expose-Headers matters when frontend code needs to read non-simple response headers.

A good real-world example is GitHub’s API. api.github.com returns:

access-control-allow-origin: *
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning

That’s not accidental. If your frontend needs pagination headers like Link, rate limit info, or ETag, you must expose them.

In CDK-backed APIs, people often forget this and then wonder why response.headers.get('ETag') returns null.

If your Lambda needs to expose headers:

const headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': origin,
  'Access-Control-Allow-Credentials': 'true',
  'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After',
  'Vary': 'Origin',
};

Use the smallest list that actually matches your frontend needs.

The S3 and CloudFront trap

This project also had one more problem: the frontend team had started calling the S3 website endpoint directly for some uploaded assets during development.

That introduced a second CORS surface area.

If your browser hits S3 directly, S3 needs its own CORS config. CDK example:

import * as s3 from 'aws-cdk-lib/aws-s3';

const bucket = new s3.Bucket(this, 'UploadsBucket', {
  cors: [
    {
      allowedOrigins: [
        'http://localhost:3000',
        'https://staging.example.com',
        'https://app.example.com',
      ],
      allowedMethods: [
        s3.HttpMethods.GET,
        s3.HttpMethods.PUT,
        s3.HttpMethods.POST,
      ],
      allowedHeaders: ['*'],
      exposedHeaders: ['ETag'],
    },
  ],
});

If uploads use presigned URLs, test those flows separately. API Gateway CORS can be perfect while S3 upload CORS is still broken.

How we verified it

I like testing CORS outside the app before blaming frontend code. Browser DevTools are useful, but they’re noisy.

A simple header inspection tool like HeaderTest makes it easier to confirm what your API actually returns for preflight and real responses.

For manual checks, I also use curl a lot.

Simulate a preflight request

curl -i -X OPTIONS https://api.example.com/sessions \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type"

Expected response headers should include something like:

Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET,POST,PATCH,DELETE,OPTIONS
Access-Control-Allow-Headers: Content-Type,Authorization,X-Requested-With
Access-Control-Allow-Credentials: true

Simulate the real request

curl -i https://api.example.com/me \
  -H "Origin: https://app.example.com"

If the response is a 401, it still needs CORS headers.

What I’d do differently from day one

If I were setting this up fresh in AWS CDK, I’d stick to these rules:

  1. Never use * if cookies or auth credentials are involved.
  2. Keep an explicit origin allowlist per environment.
  3. Make sure error responses include the same CORS behavior as success responses.
  4. Expose only the response headers the frontend actually needs.
  5. Treat API Gateway, Lambda, S3, and CloudFront as separate CORS boundaries.
  6. Add Vary: Origin when origin-specific responses are possible.

And one more opinionated take: CORS config belongs in infrastructure and application code together. CDK alone won’t save you if your Lambda responses are inconsistent.

If you’re tuning security headers beyond CORS for the frontend, especially CSP, I’d also sanity check your setup against csp-guide.com. Teams that care enough to lock down CORS usually end up tightening CSP next.

CORS on AWS isn’t hard because the rules are mysterious. It’s hard because the rules are spread across too many layers, and AWS makes it easy to configure one layer and forget the others. That’s how you end up with “working infrastructure” and a broken browser app.