CORS on CloudFront looks simple until caching gets involved.
That’s the part that bites people. You add Access-Control-Allow-Origin, test once, it works, then a different origin starts failing or getting the wrong response from cache. If you’ve ever had a “works in curl, fails in browser” day with CloudFront, this is usually why.
I’m going to show the setups that actually work in production:
- static assets behind CloudFront
- APIs behind CloudFront
- S3 origins
- custom origins like ALB, EC2, or API backends
- dynamic origin allowlists
- preflight caching without poisoning your edge cache
What CloudFront does in a CORS flow
CloudFront is a cache and proxy sitting between the browser and your origin.
For CORS, that means CloudFront can affect three things:
- Whether the
Originheader reaches your origin - Whether
OPTIONSrequests are forwarded - Whether responses with different CORS headers are cached separately
That third one is the big deal.
If your origin returns:
Access-Control-Allow-Origin: https://app.example.com
for one request, and CloudFront caches it without varying by Origin, then the next request from:
Origin: https://admin.example.com
might get the cached headers for app.example.com. Browser rejects it. You waste an afternoon.
The two main ways to do CORS on CloudFront
You generally have two choices:
1. Set CORS at the origin
Best when:
- your API already handles CORS
- allowed origins are dynamic
- you need per-route or per-tenant logic
2. Set CORS with a CloudFront Response Headers Policy
Best when:
- you serve static content
- your rules are simple
- you want CloudFront to inject headers consistently
For most APIs, I prefer keeping CORS logic at the origin unless the policy is dead simple.
Option 1: Configure CORS with a CloudFront Response Headers Policy
CloudFront has a built-in feature for adding CORS headers to responses.
In the AWS Console:
- Open CloudFront
- Select your distribution
- Open Behaviors
- Edit the behavior
- Attach a Response headers policy
You can use a managed policy or create a custom one.
A custom policy might look like this conceptually:
- Allow origin:
https://app.example.com - Allow methods:
GET, POST, OPTIONS - Allow headers:
Content-Type, Authorization - Expose headers:
ETag - Max age:
86400
If you use Terraform, it looks like this:
resource "aws_cloudfront_response_headers_policy" "cors_api" {
name = "cors-api-policy"
cors_config {
access_control_allow_credentials = false
access_control_allow_headers {
items = ["Content-Type", "Authorization"]
}
access_control_allow_methods {
items = ["GET", "POST", "OPTIONS"]
}
access_control_allow_origins {
items = ["https://app.example.com"]
}
access_control_expose_headers {
items = ["ETag"]
}
access_control_max_age_sec = 86400
origin_override = true
}
}
Then attach it to the behavior:
default_cache_behavior {
target_origin_id = "api-origin"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
cached_methods = ["GET", "HEAD", "OPTIONS"]
response_headers_policy_id = aws_cloudfront_response_headers_policy.cors_api.id
}
When this works well
This is great for static assets and simple public APIs. If your CORS rule is basically “allow this one frontend,” CloudFront can do it cleanly.
When this breaks down
If you need:
- multiple allowed origins based on request
- tenant-specific rules
- credentials with origin reflection
- route-specific CORS behavior
then pushing it to the origin is usually less painful.
Option 2: Handle CORS at the origin and make CloudFront cache-safe
This is the more common API setup.
Your origin returns CORS headers, and CloudFront forwards the right request headers and caches correctly.
The minimum rule
If your origin sends different Access-Control-Allow-Origin values depending on Origin, then CloudFront must include Origin in the cache key.
If you handle preflight, you should also think about:
Access-Control-Request-MethodAccess-Control-Request-Headers
CloudFront cache policy and origin request policy
Use:
- a Cache Policy to include
Originin the cache key - an Origin Request Policy to forward the CORS request headers to origin
Terraform example:
resource "aws_cloudfront_cache_policy" "cors_cache" {
name = "cors-cache-policy"
default_ttl = 300
max_ttl = 3600
min_ttl = 0
parameters_in_cache_key_and_forwarded_to_origin {
headers_config {
header_behavior = "whitelist"
headers {
items = ["Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
}
}
cookies_config {
cookie_behavior = "none"
}
query_strings_config {
query_string_behavior = "all"
}
enable_accept_encoding_gzip = true
enable_accept_encoding_brotli = true
}
}
resource "aws_cloudfront_origin_request_policy" "cors_origin" {
name = "cors-origin-policy"
headers_config {
header_behavior = "whitelist"
headers {
items = ["Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
}
}
cookies_config {
cookie_behavior = "none"
}
query_strings_config {
query_string_behavior = "all"
}
}
Attach both to the behavior:
default_cache_behavior {
target_origin_id = "app-api"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
cached_methods = ["GET", "HEAD", "OPTIONS"]
cache_policy_id = aws_cloudfront_cache_policy.cors_cache.id
origin_request_policy_id = aws_cloudfront_origin_request_policy.cors_origin.id
}
Example origin code: Node/Express behind CloudFront
Here’s a practical Express setup with an allowlist:
import express from "express";
const app = express();
const allowedOrigins = new Set([
"https://app.example.com",
"https://admin.example.com",
]);
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && allowedOrigins.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Expose-Headers", "ETag, Link");
}
next();
});
app.options("*", (req, res) => {
const origin = req.headers.origin;
if (origin && allowedOrigins.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Vary", "Origin");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
res.setHeader(
"Access-Control-Allow-Headers",
req.headers["access-control-request-headers"] || "Content-Type, Authorization"
);
res.setHeader("Access-Control-Max-Age", "86400");
return res.status(204).end();
}
return res.status(403).end();
});
app.get("/data", (req, res) => {
res.json({ ok: true });
});
app.listen(3000);
The Vary: Origin header is not optional here. Without it, shared caches can serve the wrong CORS response.
S3 + CloudFront CORS
If your origin is S3, you usually configure CORS on the bucket and let CloudFront forward Origin.
S3 CORS config example:
[
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET", "HEAD"],
"AllowedOrigins": ["https://app.example.com"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 86400
}
]
If you serve public static files and only need one origin, this is usually enough.
If you need CloudFront to add headers instead, use a Response Headers Policy and keep the S3 config simple.
Preflight requests on CloudFront
Browsers send preflight OPTIONS requests when the real request is non-simple.
CloudFront must allow and usually cache OPTIONS if you want decent performance.
Checklist:
OPTIONSincluded in allowed methodsOPTIONSincluded in cached methods if you want edge cachingOrigin,Access-Control-Request-Method, andAccess-Control-Request-Headersforwarded when origin handles preflight- cache key varies on those headers when responses differ by them
If not, one preflight response can get incorrectly reused for another request shape.
Public APIs and exposed headers
A good real-world reference is GitHub’s API. api.github.com sends:
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 Access-Control-Expose-Headers list is a good reminder that CORS isn’t just about allowing requests. It also controls what frontend JavaScript can read from the response.
If your frontend needs ETag, pagination Link, rate limit headers, or deprecation metadata, expose them explicitly.
Testing CloudFront CORS correctly
Don’t just test with curl once and call it done.
You want to test:
- simple request
- preflight request
- allowed origin
- blocked origin
- cache behavior with different origins
Example preflight test:
curl -i -X OPTIONS "https://d111111abcdef8.cloudfront.net/data" \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: authorization,content-type"
And a second one with a different origin:
curl -i -X OPTIONS "https://d111111abcdef8.cloudfront.net/data" \
-H "Origin: https://evil.example.com" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: authorization,content-type"
If you want a quick way to inspect headers and validate what’s actually coming back through CloudFront, HeaderTest is handy.
Common CloudFront CORS mistakes
1. Using * with credentials
This is invalid for browser CORS.
If you send:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
the browser will reject it.
2. Forgetting Origin in the cache key
This causes wrong cached CORS headers across origins.
3. Forwarding Origin but not varying cache
This is the sneaky version of the same bug. Your origin does the right thing, CloudFront cache does not.
4. Not handling OPTIONS
The actual GET or POST route works, but browser never sends it because preflight fails first.
5. Missing Access-Control-Expose-Headers
Your frontend can make the request but can’t read the headers it needs.
6. Mixing CORS logic in both CloudFront and origin
You can do this, but I try not to unless the split is deliberate. Conflicting headers create weird results fast.
Security boundaries that CORS does not solve
CORS is not auth. It does not stop server-to-server requests. It does not protect a public endpoint from abuse. It just tells browsers which cross-origin frontend code can read responses.
If you’re hardening CloudFront responses more broadly, you’ll probably also want CSP, HSTS, and the rest of your security headers. If you’re working through that side too, https://csp-guide.com is a solid reference.
My recommended patterns
For static assets on CloudFront
Use a Response Headers Policy.
For APIs with one fixed frontend
You can use either:
- CloudFront Response Headers Policy, or
- origin-handled CORS
I still lean origin-side if the API may evolve.
For APIs with multiple allowed origins or credentials
Handle CORS at the origin, forward the CORS request headers, and include Origin in the cache key.
That setup is boring, predictable, and production-safe. Which is exactly what you want from CORS.