CORS Preflight Failures: Fixing Missing Allow-Origin Headers
CORS missing Access-Control-Allow-Origin? Fix 5xx gateway proxy stripping, credentials wildcard errors, preflight OPTIONS 204 caching, and middleware order.
You open your browser console after deploying an updated API endpoint, and your frontend network tab lights up in red. A critical request failed, but the status code says canceled and the console logs a generic browser security error.
Browsers block cross-origin requests with No 'Access-Control-Allow-Origin' header is present on the requested resource whenever the response lacks authorization headers for the requesting origin. While frontend developers assume this is a client misconfiguration, the root cause almost always lives in upstream reverse proxies dropping headers on 5xx errors, middleware order execution flaws, or invalid credentials wildcard syntax.
Here is the immediate triage checklist to diagnose and resolve CORS preflight failures:
- Check the Actual HTTP Status Code in Network Headers: If the underlying status code is
500 Internal Server Error,502 Bad Gateway, or504 Gateway Timeout, fix the unhandled backend exception or timeout first. Upstream error pages bypass application CORS middleware entirely. - Verify Middleware Execution Order: Ensure your CORS middleware executes at the very top of your application pipeline, before authentication, rate limiting, and route parsing handlers.
- Eliminate the Wildcard Credentials Trap: Never combine
Access-Control-Allow-Origin: *withAccess-Control-Allow-Credentials: true. Echo the incomingOriginrequest header dynamically after validating it against an approved domain whitelist. - Return HTTP 204 No Content for OPTIONS Calls: Explicitly handle preflight
OPTIONSrequests before any session verification, returning status 204 or 200 alongside allowed methods, headers, andAccess-Control-Max-Age.
Illustrative browser console capture during a failed cross-origin preflight check:
Access to fetch at 'api.example.internal/v1/workspaces' from origin 'app.example.internal'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Anatomy of CORS: Simple Requests vs Preflight Handshakes
Cross-Origin Resource Sharing (CORS) is not an authorization framework; it is a browser-enforced mechanism that prevents unauthorized web pages from reading sensitive data across origins.
An origin is defined strictly as the combination of Scheme + Hostname + Port (e.g., app.example.internal:443). If any of these three components differ between the web application and the API server, the request is cross-origin.
The browser classifies cross-origin calls into two distinct categories:
+-------------------------------------------------------------------------+
| CORS Request Decision Tree |
| |
| [Cross-Origin HTTP Request] |
| | |
| +---------------------------+---------------------------+ |
| | | |
| Method in (GET, POST, HEAD) AND Method in (PUT, DELETE, PATCH) |
| Content-Type in (text/plain, OR Content-Type: application/json |
| multipart/form-data, OR Custom Headers (Authorization) |
| application/x-www-form-urlencoded) | |
| | | |
| v v |
| [Simple Request] [Preflighted Request] |
| Browser sends actual request immediately. Browser sends HTTP OPTIONS. |
| Inspects Access-Control-Allow-Origin Waits for 204/200 OK with |
| on response before releasing payload to JS. CORS headers before firing actual. |
+-------------------------------------------------------------------------+
Simple Requests
If a request uses GET, POST, or HEAD, contains only basic headers (Accept, Accept-Language, Content-Language), and uses simple media types (text/plain, multipart/form-data, application/x-www-form-urlencoded), the browser sends the actual request directly. It includes an Origin header in the request:
GET /public-feed HTTP/1.1
Host: api.example.internal
Origin: app.example.internal
The browser inspects the returned headers. If Access-Control-Allow-Origin matches app.example.internal or *, JavaScript code receives the response. If the header is missing, the browser discards the payload and throws a console security error.
Preflighted Requests
Almost all modern single-page applications (SPAs) send preflighted requests because they use Content-Type: application/json or include authentication tokens via Authorization: Bearer <token>.
Before sending the actual HTTP request, the browser transparently issues an HTTP OPTIONS probe:
OPTIONS /v1/workspaces HTTP/1.1
Host: api.example.internal
Origin: app.example.internal
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization,content-type
The server must reply with specific access control headers:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: app.example.internal
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Only if this preflight check succeeds will the browser execute the primary POST request. If the preflight fails, the actual request is never transmitted over the wire.
The Four Most Common CORS Breakdown Modes
CORS errors rarely stem from basic spelling mistakes. They occur when networking layers, reverse proxies, and application middleware interact in unexpected ways.
1. The 5xx Upstream Error Header Stripping Trap
This is the number one cause of intermittent CORS errors in production. Your code works flawlessly during staging. Suddenly, a customer triggers a bug or a database query times out. The browser does not display the 500 or 502 error; it displays a CORS missing header error.
Here is what happens:
- The client sends a valid cross-origin request.
- The application backend throws an uncaught exception, or a reverse proxy (Nginx, AWS ALB, Cloudflare, Traefik) suffers a gateway timeout (504).
- The reverse proxy catches the upstream failure and returns its own default error template (
<html><body>502 Bad Gateway</body></html>). - Because this static error page was generated by the proxy rather than your application code, no CORS headers were attached.
- The browser evaluates the response, notes the absence of
Access-Control-Allow-Origin, and blocks the response with a CORS violation.
Frontend developers spend hours debugging cross-origin settings when the real issue is an unhandled database connection leak or out-of-memory crash.
2. The Credentials Wildcard Syntax Violation
When your application authenticates via cookies (credentials: 'include') or HTTP Authorization headers, the browser enforces strict security standards defined in the Fetch specification.
If the server responds with:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
The browser will explicitly reject the response with the following error:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
when the request's credentials mode is 'include'.
The specification explicitly forbids wildcard origins when credentials are transmitted, preventing untrusted third-party sites from executing credentialed ambient requests against private APIs.
3. Middleware Ordering: Auth Intercepting OPTIONS Calls
In many microservices frameworks, developers register authentication middleware globally across all incoming routes:
// ❌ Bug: Authentication middleware executes before CORS handler
app.use(verifyJwtToken);
app.use(corsMiddleware);
When the browser sends an initial preflight OPTIONS request, the browser does not include authentication headers or cookies. The verifyJwtToken middleware inspects the request, finds no Authorization header, and immediately rejects the request with 401 Unauthorized.
Because the request was halted before reaching corsMiddleware, the 401 response returns without Access-Control-Allow-Origin. The browser interprets this as a preflight rejection, completely blinding the client to the underlying auth requirement.
4. Reverse Proxy Stripping Preflight OPTIONS
In environments leveraging AWS API Gateway, Nginx, or Kubernetes Ingress, administrators often configure routing rules that only proxy GET and POST methods to the backend service.
When the browser dispatches an OPTIONS call, the gateway itself responds with 403 Forbidden or 405 Method Not Allowed without passing the probe down to the application container.
Hardening CORS at the Reverse Proxy (Nginx Architecture)
The most resilient way to prevent 5xx header stripping is handling CORS directly at the reverse proxy boundary, ensuring error responses inherit required headers.
Here is an enterprise-grade Nginx configuration that dynamically validates origins, handles OPTIONS with instant 204 responses, and preserves CORS headers across upstream errors:
# /etc/nginx/conf.d/api.conf
# Map incoming Origin to an allowed whitelist
map $http_origin $cors_origin {
default "";
"~*(app|admin)\.example\.internal" "$http_origin";
"~*preview-[a-z0-9]+\.example\.internal" "$http_origin";
"~*localhost:[0-9]+" "$http_origin";
}
server {
listen 443 ssl http2;
server_name api.example.internal;
# SSL certificates and security ciphers...
location / {
# Preflight OPTIONS handling
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $cors_origin always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, X-Request-ID, Stripe-Signature' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Max-Age' 86400 always;
add_header 'Content-Type' 'text/plain; charset=utf-8' always;
add_header 'Content-Length' 0 always;
return 204;
}
proxy_pass $upstream_cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Inject CORS headers on ALL responses, including upstream 502/504 errors
add_header 'Access-Control-Allow-Origin' $cors_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Expose-Headers' 'X-Request-ID, Content-Length' always;
}
}
Important: Notice the use of the
alwaysdirective in Nginx’sadd_header. Withoutalways, Nginx suppresses custom headers on response status codes400,401,403,500,502,503, and504. Addingalwaysguarantees that even if your application crashes and emits a 502, the browser still receivesAccess-Control-Allow-Origin, exposing the true backend error in the console.
Backend Application Hardening: Node.js & Express
If your infrastructure relies on application-level CORS handlers, implement a dynamic whitelist validator that handles preflight short-circuiting:
// Production CORS configuration in Express / Node.js
import express, { Request, Response, NextFunction } from "express";
const app = express();
const ALLOWED_ORIGIN_HOSTS = new Set([
"app.example.internal",
"admin.example.internal",
"localhost:3000",
]);
// 1. Register CORS as the absolute first middleware
app.use((req: Request, res: Response, next: NextFunction) => {
const origin = req.headers.origin;
// Validate incoming origin against explicit whitelist
if (origin) {
try {
const url = new URL(origin);
if (ALLOWED_ORIGIN_HOSTS.has(url.host)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
} catch {
// Invalid origin header
}
}
// Handle Preflight OPTIONS
if (req.method === "OPTIONS") {
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Authorization, Content-Type, X-Client-Version"
);
// Cache preflight verdict for 24 hours (86,400 seconds)
res.setHeader("Access-Control-Max-Age", "86400");
return res.status(204).end();
}
next();
});
// 2. Authentication middleware executes only AFTER preflight has exited
app.use(authenticateUserSession);
AWS API Gateway Preflight Resolution
When using AWS API Gateway (REST API or HTTP API), preflight requests must be intercepted directly by the gateway to prevent Lambda execution overhead on simple OPTIONS checks.
HTTP APIs (v2)
For HTTP APIs, configure CORS directly in the gateway spec or Terraform:
# Terraform configuration for AWS API Gateway v2 CORS
resource "aws_apigatewayv2_api" "http_api" {
name = "core-api"
protocol_type = "HTTP"
cors_configuration {
allow_credentials = true
allow_headers = ["Authorization", "Content-Type", "X-Requested-With"]
allow_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allow_origins = ["app.example.internal", "localhost:3000"]
max_age = 86400
}
}
Gateway Responses for 5xx / 4xx
AWS API Gateway generates custom error responses for quota exhaustion (429), authorization failure (403), or Lambda timeouts (504). If these Gateway Responses lack CORS headers, the browser hides the AWS error behind a generic CORS failure.
Navigate to API Gateway -> Gateway Responses and ensure DEFAULT_4XX and DEFAULT_5XX have response headers configured:
Access-Control-Allow-Origin = 'app.example.internal'
Access-Control-Allow-Headers = 'Content-Type,Authorization'
Access-Control-Allow-Methods = 'GET,POST,OPTIONS'
Access-Control-Allow-Credentials = 'true'
Testing Preflight Responses with cURL
Do not rely exclusively on browser console logs to diagnose CORS bugs. Browsers sanitize security headers, obscuring the exact response status.
Use curl to simulate an exact preflight check from the command line:
# Simulate a browser preflight OPTIONS request
curl -i -X OPTIONS api.example.internal/v1/workspaces \
-H "Origin: app.example.internal" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: Authorization, Content-Type"
Verify that the terminal output matches these four expectations:
- Status Code: Returns
HTTP/1.1 204 No Contentor200 OK. - Origin Reflection:
Access-Control-Allow-Originmatchesapp.example.internal(not*if credentials are true). - Methods List:
Access-Control-Allow-MethodsincludesPOST. - Headers List:
Access-Control-Allow-HeadersincludesAuthorizationandContent-Type.
If curl returns a 401 Unauthorized or 502 Bad Gateway, your preflight is either getting intercepted by auth middleware or hitting a failing upstream service before the CORS header can attach.
Comparison: CORS Response Headers Reference
The following table summarizes the primary CORS response headers and their configuration rules:
| Header Name | Required on Preflight? | Accepted Values | Architectural Pitfall |
|---|---|---|---|
Access-Control-Allow-Origin | Yes | Specific Origin (app.example.internal) or * | Setting * breaks if credentials mode is true |
Access-Control-Allow-Methods | Yes | Comma-separated list (GET, POST, OPTIONS...) | Omitting requested HTTP method causes 405 error |
Access-Control-Allow-Headers | Yes | Comma-separated list of allowed request headers | Omitting custom headers like Authorization halts request |
Access-Control-Allow-Credentials | If using cookies/auth | true (literal boolean string) | Setting to true while origin is * triggers browser rejection |
Access-Control-Max-Age | Recommended | Seconds (e.g., 86400) | Omitting causes browser to fire OPTIONS on every call |
Access-Control-Expose-Headers | On actual response | Comma-separated list of custom headers | Omitting prevents frontend JS from reading custom response headers |
Frequently Asked Questions
Can I fix CORS by modifying frontend code?
No. CORS is enforced by the browser against the response returned by the server. Unless you control the server or route traffic through a same-origin proxy (like Next.js rewrites or a BFF layer), frontend code cannot bypass CORS security constraints.
Why does my request succeed in Postman or cURL but fail in Chrome?
Postman, cURL, and backend services are not browsers; they ignore browser cross-origin security specifications entirely and do not enforce origin isolation. Only web browser runtimes enforce CORS rules.
What is the maximum value for Access-Control-Max-Age?
While the HTTP specification allows arbitrary values, browsers cap the maximum duration. Chromium engines (Chrome, Edge) cap Access-Control-Max-Age at 7,200 seconds (2 hours), while Firefox allows up to 86,400 seconds (24 hours). Setting 86400 ensures maximum caching across all engines.
Is setting Access-Control-Allow-Origin: * safe for public APIs?
Yes, for genuinely public APIs that deliver identical, non-sensitive data to all clients without authentication cookies or bearer tokens. If your API serves tenant-specific data or requires user sessions, always use an explicit origin whitelist.
Related Engineering Guides
- 5 Critical Security Boundaries Overlooked in Rapid MVPs: Protecting customer data, securing service keys, and enforcing zero-trust API perimeters.
- Next.js Server Actions: Hardening Multi-Tenant Security: Closing public RPC attack surfaces and preventing session boundary leaks in modern full-stack frameworks.
- OAuth 2.0 PKCE & State Flaws: Closing SPA Interceptions: Hardening frontend authentication flows against login CSRF and token leakage.
Marcus Vance
Principal Systems ArchitectSystems engineer focusing on distributed backends, database concurrency, and application security. Specializes in high-throughput PostgreSQL concurrency, serverless connection pooling, and infrastructure hardening.
Why does the browser report missing Access-Control-Allow-Origin on 500 or 502 server errors?
Why does Access-Control-Allow-Origin: * fail when sending cookies or authorization headers?
What is an HTTP preflight request and what triggers it?
How does Access-Control-Max-Age improve API performance?
Have our team inspect your AI-generated codebase.
48-hour turnaround with direct pull requests fixing security and scale bottlenecks.