Nginx CORS Preflight Config: map $http_origin & add_header always Pitfalls
Configure Nginx reverse-proxy CORS safely using map $http_origin, the always directive on 204/4xx/5xx responses, and Vary: Origin without breaking header inheritance.
Handle HTTP OPTIONS preflights cleanly on Cloudflare Workers with explicit origin allowlists, Vary: Origin cache isolation, Access-Control-Max-Age 7200s, and safe credential handling.
Pass: 3 · Warnings: 0 · Errors: 0
# Simulated Browser Preflight: OPTIONS /api/v1/resource # Request Origin: https://app.example.com | Method: POST | Headers: Authorization, Content-Type # Browser Verdict: ALLOWED (HTTP 204 No Content) HTTP/1.1 204 No Content Access-Control-Allow-Origin: https://app.example.com Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, Idempotency-Key Access-Control-Expose-Headers: X-Request-Id, X-RateLimit-Remaining Access-Control-Allow-Credentials: true Access-Control-Max-Age: 7200 Vary: Origin
const ALLOWED_ORIGINS = new Set(["https://app.example.com","https://studio.example.com"]);
function buildCorsHeaders(request: Request): Record<string, string> {
const origin = request.headers.get("Origin") || "";
const allowOrigin = ALLOWED_ORIGINS.has(origin) ? origin : "";
const headers: Record<string, string> = {
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Authorization, Content-Type, X-Requested-With, Idempotency-Key",
"Access-Control-Expose-Headers": "X-Request-Id, X-RateLimit-Remaining",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Max-Age": "7200"
};
if (allowOrigin) headers["Access-Control-Allow-Origin"] = allowOrigin;
headers["Vary"] = "Origin";
return headers;
}
export default {
async fetch(request: Request): Promise<Response> {
const cors = buildCorsHeaders(request);
if (request.method === "OPTIONS") {
return new Response(null, { status: 204, headers: cors });
}
return new Response(JSON.stringify({ ok: true }), {
headers: { "Content-Type": "application/json", ...cors }
});
}
};
Test your deployed domain's security headers, HSTS, CSP & DMARC live on ReadyCheck, diff OpenAPI contracts & OWASP API Top 10 risks in SpecDiff, or deploy all 9 production configs in minutes with the $49 ReadyCheck Fix Pack.
| Rule / Header | Production Value | Behavior & Gotchas |
|---|---|---|
Preflight Status |
204 No Content (OPTIONS) |
Return early before invoking upstream origin or KV/D1 reads |
Vary: Origin |
Required on dynamic origin allowlists |
Prevents Cloudflare Edge CDN cache from poisoning CORS headers across origins |
Access-Control-Max-Age |
7200 (Chromium cap) |
Avoids repeated preflight latency on Chrome/Edge without pointless >86400 values |
Credentials + Wildcard |
Forbidden (* + true fails Fetch) |
Echo only matched origins from an explicit Set<string> |
const ALLOWED_ORIGINS = new Set([
"https://app.example.com",
"https://studio.example.com",
]);
function corsHeaders(request: Request): Record<string, string> {
const origin = request.headers.get("Origin") || "";
const headers: Record<string, string> = {
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Authorization, Content-Type, Idempotency-Key",
"Access-Control-Max-Age": "7200",
"Vary": "Origin",
};
if (ALLOWED_ORIGINS.has(origin)) {
headers["Access-Control-Allow-Origin"] = origin;
headers["Access-Control-Allow-Credentials"] = "true";
}
return headers;
}
export default {
async fetch(request: Request): Promise<Response> {
const cors = corsHeaders(request);
if (request.method === "OPTIONS") {
return new Response(null, { status: 204, headers: cors });
}
return Response.json({ status: "ok" }, { headers: cors });
},
};
curl -i -X OPTIONS "https://api.example.com/v1/resource" \ -H "Origin: https://app.example.com" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: Authorization, Content-Type" # Expect HTTP/2 204, Access-Control-Allow-Origin: https://app.example.com, Vary: Origin
Configure Nginx reverse-proxy CORS safely using map $http_origin, the always directive on 204/4xx/5xx responses, and Vary: Origin without breaking header inheritance.
Fix FastAPI/Starlette CORS failures when allow_credentials=True: why allow_origins=['*'] breaks cookies/Auth headers, middleware ordering, and preflight 500 error masking.
Implement dynamic multi-origin CORS with Vary: Origin in Next.js App Router route handlers and middleware.ts without the single-origin limitation of static next.config.mjs headers().
Verify GitHub X-Hub-Signature-256 and Slack v0= webhook signatures using constant-time crypto.timingSafeEqual, raw request bytes, and timestamp replay protection.
Implement production-grade billing webhook HMAC-SHA256 verification for Stripe (`t=<ts>,v1=<hex>`) and Creem (`creem-signature: <hex>`) with raw-body preservation and replay checks.
← Back to CORS & Webhook HMAC Debugger Hub · OpenAPI OWASP API Top 10 & MCP Scorer → · SBOM & Sigstore Validator → · HTTP Security Headers & CSP →
Use Cloudflare Pages _headers for static JSON files like /.well-known/agent-card.json (with static Access-Control-Allow-Origin: *), and use a Worker or Pages Function for credentialed multi-origin APIs that require dynamic Origin allowlisting and Vary: Origin.
Chromium caps preflight cache duration at 7200 seconds (2 hours), while Firefox honors up to 86400 seconds (24 hours). Setting 7200 keeps behavior consistent.
If your Worker throws before wrapping error responses with Access-Control-Allow-Origin, the browser hides the HTTP status body and reports a generic CORS failure.