Debugging CORS Preflight Requests and Credential Headers
Diagnose failing browser OPTIONS preflights, disallow wildcard origins with credentials, configure Vary: Origin safely, and test CORS headers deterministically.
On this page
Why Browsers Block Cross-Origin Requests
Cross-Origin Resource Sharing (CORS) exists to relax the browser’s Same-Origin Policy under explicit server permission. Whenever JavaScript served from https://app.example.com calls fetch("https://api.example.com/v1/orders"), the scheme, host, or port differs, making the request cross-origin. Without CORS headers from the API server, the browser withholds the response body from frontend scripts even when the network trace shows HTTP 200 OK.
Two distinct failure paths confuse engineers during debugging. For “simple” requests (GET, HEAD, or POST with application/x-www-form-urlencoded, multipart/form-data, or text/plain and no non-safelisted headers), the browser fires the request directly and inspects the CORS headers on the response. The moment your frontend adds Authorization: Bearer ..., X-Request-Id, Content-Type: application/json, or uses PUT/PATCH/DELETE, the browser freezes the real request and dispatches a preflight OPTIONS probe first.
Anatomy of an OPTIONS Preflight Handshake
During preflight, the browser sends three request headers: Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. Your server must respond with 204 No Content (or 200 OK) before the browser ever dispatches the actual POST or PATCH. If the preflight returns a 301/302 redirect, a 401 auth challenge, or omits any header requested in Access-Control-Request-Headers, the browser aborts the entire operation immediately.
Keep in mind that browsers also maintain a per-origin, per-method preflight cache controlled by Access-Control-Max-Age. While production deployments often cache preflight replies for 600 seconds (note that Chromium caps Access-Control-Max-Age at 7200 seconds and Firefox caps it at 86400 seconds), during local debugging a long cache duration hides server header fixes until you manually bypass the cache in DevTools or restart the browser profile. Before editing production reverse proxy rules, you can simulate origin matching, credential restrictions, and requested headers locally in the Interactive CORS Header Debugger to pinpoint which header rule fails.
Building an Allowlist Middleware in TypeScript
Never reflect the raw req.headers.origin header blindly back into Access-Control-Allow-Origin, because doing so with Access-Control-Allow-Credentials: true lets any malicious site read authenticated API responses on a victim user’s browser. Equally dangerous is naive substring matching such as origin.endsWith("example.com"), which admits attacker domains like evil-example.com. Parse origins against an exact Set<string> of scheme + hostname + optional port.
import type { IncomingMessage, ServerResponse } from "node:http";
const ALLOWED_ORIGINS = new Set<string>([
"https://app.example.com",
"https://staging.example.com",
"http://localhost:5173",
]);
const ALLOWED_METHODS = "GET, POST, PUT, PATCH, DELETE, OPTIONS";
const ALLOWED_HEADERS = "Authorization, Content-Type, X-Request-Id";
function appendVary(res: ServerResponse, headerName: string): void {
const existing = res.getHeader("Vary");
if (!existing) {
res.setHeader("Vary", headerName);
return;
}
const tokens = String(existing)
.split(",")
.map((v) => v.trim().toLowerCase());
if (!tokens.includes(headerName.toLowerCase())) {
res.setHeader("Vary", `${existing}, ${headerName}`);
}
}
export function applyCorsPolicy(req: IncomingMessage, res: ServerResponse): boolean {
const origin = req.headers.origin;
if (!origin) {
// Non-browser or same-origin request without Origin header
return false;
}
// Always inform intermediate caches that CORS headers depend on Origin
appendVary(res, "Origin");
if (!ALLOWED_ORIGINS.has(origin)) {
if (req.method === "OPTIONS") {
res.statusCode = 403;
res.end("Origin not allowed");
return true;
}
return false;
}
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Expose-Headers", "X-Request-Id, Retry-After");
if (req.method === "OPTIONS") {
appendVary(res, "Access-Control-Request-Method");
appendVary(res, "Access-Control-Request-Headers");
res.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS);
res.setHeader("Access-Control-Allow-Headers", ALLOWED_HEADERS);
res.setHeader("Access-Control-Max-Age", "600");
res.statusCode = 204;
res.end();
return true;
}
return false;
}
Notice how Access-Control-Expose-Headers is separate from Access-Control-Allow-Headers. By default, fetch() JavaScript code can only read CORS-safelisted response headers (Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, Pragma). If your client inspects Retry-After on a 429 rate-limit response or reads X-Request-Id for error reporting, you must explicitly list them in Access-Control-Expose-Headers.
Nginx Reverse Proxy and Gateway Edge Cases
Many CORS bugs occur because application middleware sets the headers while an upstream Nginx ingress, API gateway, or CDN strips, duplicates, or caches them incorrectly. In Nginx, remember that add_header inside a nested location block or if block suppresses parent add_header directives, and Nginx drops add_header on 4xx/5xx error responses unless you append the always keyword. If an unhandled 502 Bad Gateway or 401 Unauthorized lacks Access-Control-Allow-Origin and always, your frontend receives an opaque TypeError: Failed to fetch instead of the real status code.
map $http_origin $cors_origin {
default "";
"https://app.example.com" "https://app.example.com";
"https://staging.example.com" "https://staging.example.com";
}
server {
listen 443 ssl;
server_name api.example.com;
location /v1/ {
add_header Vary "Origin" always;
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Authorization, Content-Type, X-Request-Id" always;
add_header Access-Control-Max-Age "600" always;
add_header Vary "Origin, Access-Control-Request-Method, Access-Control-Request-Headers" always;
return 204;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials "true" always;
proxy_pass http://api_upstream;
}
}
Notice why add_header Access-Control-Allow-Origin appears inside both the if ($request_method = OPTIONS) block and the main location block: Nginx stops evaluating outer add_header rules whenever add_header is declared inside an if block. Also avoid adding CORS headers in both Nginx and Express simultaneously—emitting two Access-Control-Allow-Origin headers causes browsers to reject the response immediately with "contains multiple values, but only one is allowed".
Subtle Failures: Credentials, Redirects, and Caching
Keep an eye on five recurring edge cases when auditing cross-origin flows:
- Wildcard mismatch with cookies or auth flags: Sending
fetch(url, { credentials: "include" })while the server repliesAccess-Control-Allow-Origin: *orAccess-Control-Allow-Headers: *fails in Chromium, Firefox, and Safari. Credentialed requests demand explicit non-wildcard values for origin, headers, and methods. - Auth middleware blocking OPTIONS: Because browsers never attach
Authorizationheaders or cookies to preflightOPTIONSprobes, any JWT/session middleware mounted ahead of your CORS middleware returns401 UnauthorizedonOPTIONSand breaks every cross-origin write call. Mount CORS before authentication. - Redirects on preflight: Returning a
301trailing-slash normalization redirect (POST /v1/items->/v1/items/) on a preflightOPTIONSrequest violates the Fetch preflight spec and aborts immediately. - Missing
Vary: Originbehind CDNs: WithoutVary: Origin, Cloudflare or CloudFront caches the first caller’sAccess-Control-Allow-Origin: https://app.example.comresponse and serves it tohttps://staging.example.com, breaking staging clients unpredictably. - Private Network Access prompts: Modern Chromium browsers reject public HTTPS origins calling
http://localhostor192.168.x.xunless the local target also responds withAccess-Control-Allow-Private-Network: trueduring preflight.
Probing and Verifying CORS From the Terminal
Always verify both the preflight OPTIONS response and the actual GET/POST response headers using curl -i and your browser DevTools network log, or paste your candidate policy headers into the Interactive CORS Header Debugger to test edge cases before deployment.
# 1. Probe preflight OPTIONS as if from allowed origin
curl -i -X OPTIONS "https://api.example.com/v1/orders" \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: PATCH" \
-H "Access-Control-Request-Headers: Authorization, Content-Type"
# 2. Probe disallowed origin to confirm fail-closed behavior
curl -i -X OPTIONS "https://api.example.com/v1/orders" \
-H "Origin: https://evil-example.com" \
-H "Access-Control-Request-Method: GET"
Confirm four assertions in CI against your API test server: allowed OPTIONS returns 204 with exact single-value Access-Control-Allow-Origin, Vary: Origin is present even on 403/500 error responses, unauthenticated OPTIONS bypasses JWT guards cleanly, and an untrusted origin never receives Access-Control-Allow-Origin in any response header.
FAQ
- Why does curl succeed while fetch fails with a CORS error in the browser?
- Cross-Origin Resource Sharing is enforced exclusively by the browser's Fetch security model, never by curl, Postman, or server-to-server HTTP clients. Your API server may return 200 OK to curl while still omitting the Access-Control-Allow-* headers browsers demand.
- Can Access-Control-Allow-Origin contain multiple space-separated or comma-separated domains?
- No. According to the Fetch specification, Access-Control-Allow-Origin accepts only *, null, or a single exact origin such as https://app.example.com. Multi-origin policies must match the request Origin dynamically against a server allowlist.
- Why do I still get blocked when using Access-Control-Allow-Origin: * with cookies?
- The browser blocks any credentialed request (credentials: 'include' or withCredentials = true) if Access-Control-Allow-Origin is *. Credentialed endpoints must return the exact matched Origin plus Access-Control-Allow-Credentials: true.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.