Edge / Workers · Zero-Cold-Start OPTIONS

Cloudflare Workers CORS Preflight Middleware & Origin Allowlist Guide

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.

Zero Telemetry · Strict CSP (connect-src 'none')

CORS Policy & Preflight Controls

Access-Control-Allow-Methods
Simulate Browser Preflight Request (OPTIONS)
CORS Security & Fetch Spec Linter
100 / 100
PASS

Pass: 3 · Warnings: 0 · Errors: 0

CORS-002: Strict origin allowlist (2 origins) PASS
https://app.example.com, https://studio.example.com
CORS-004: Vary: Origin cache safety enabled PASS
Prevents CDN/proxy cache poisoning across distinct allowed origins.
CORS-005: Access-Control-Max-Age (7200s) within Chromium 7200s cap PASS
Avoids unnecessary OPTIONS preflight round-trips while honoring cross-browser cache ceilings.
Simulated Preflight Response
# 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

Copy-Paste Runtime Configs (6 Stacks)

Cloudflare Workers (worker-cors.ts)
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 }
    });
  }
};
Live API & Edge Audit Zero-Upload SpecDiff

Harden your live domain headers, OpenAPI schemas & AEO discovery

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.

Protocol Rules & Header Reference

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>

Cloudflare Workers — Strict Allowlist + Vary: Origin Router

worker-cors.ts
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 });
  },
};

Verify Preflight & Vary Headers via curl

verify-workers-cors.sh
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

Key Engineering Takeaways

  • Checking ALLOWED_ORIGINS.has(origin) via an exact Set lookup stops subdomain/prefix regex bypasses (like https://app.example.com.evil.com).
  • Always attach Vary: Origin whenever Access-Control-Allow-Origin varies per request so Cloudflare Cache / browser disk caches do not serve Origin A's headers to Origin B.
  • Returning 204 No Content directly in the Worker edge isolate avoids cold-starting downstream origin APIs on every browser preflight.

Common Production Pitfalls to Avoid

  • Using origin.endsWith('example.com') without a leading dot or exact host parse allows evil-example.com to pass.
  • Using Access-Control-Allow-Origin: * alongside Access-Control-Allow-Credentials: true causes browsers to reject the response at runtime.
  • Attaching CORS headers only on 200 OK responses while omitting them on 401/403/500 error responses masks real HTTP status codes behind opaque browser CORS errors.

More CORS & Webhook Signature Guides

← Back to CORS & Webhook HMAC Debugger Hub · OpenAPI OWASP API Top 10 & MCP Scorer → · SBOM & Sigstore Validator → · HTTP Security Headers & CSP →

Frequently Asked Questions

Should Cloudflare Pages _headers or a Worker handle API CORS?

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.

Why does Chrome ignore Access-Control-Max-Age: 86400?

Chromium caps preflight cache duration at 7200 seconds (2 hours), while Firefox honors up to 86400 seconds (24 hours). Setting 7200 keeps behavior consistent.

Why do 4xx/5xx API errors look like CORS errors in browser DevTools?

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.