Typical Browser Console Error (Static SPA (Pages/Vite) → Cloudflare Workers API)
When cross-origin headers are missing, mismatched, or blocked during preflight between Static SPA (Pages/Vite) and Cloudflare Workers API, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'https://api.opscheck.dev/v1/validate' from origin 'https://app.opscheck.dev' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Why CORS Blocks Requests Between Static SPA (Pages/Vite) and Cloudflare Workers API
Deploying a static React, Astro, Vue, or Svelte SPA to Cloudflare Pages alongside an edge API running on Cloudflare Workers delivers single-digit millisecond latency worldwide; but because Workers typically run on a distinct API subdomain or workers.dev hostname, browsers enforce strict CORS verification on every cross-origin fetch call. Unlike monolithic web frameworks with built-in CORS middleware, a bare Cloudflare Worker fetch() handler emits zero CORS headers unless you explicitly attach them to both OPTIONS preflights and actual responses.
A classic Cloudflare Workers pitfall occurs when proxying an upstream API inside a Worker: Response objects returned by fetch() inside Workers have immutable headers by design. Attempting to mutate response.headers.set("Access-Control-Allow-Origin", ..) directly throws a runtime TypeError ("Can't modify immutable headers") unless you first clone the response into a new Response(upstream.body, upstream) before adding or overwriting CORS headers.
Even more subtly, Cloudflare's global edge cache, Transform Rules, and Cloudflare Access Zero Trust policies interact directly with OPTIONS preflights. Caching API responses at the edge without Vary: Origin can hand one origin's Access-Control-Allow-Origin header to another frontend domain; and if Cloudflare Access protects your Worker hostname, unauthenticated OPTIONS preflights get intercepted with a 302 redirect to the Access login screen unless OPTIONS bypass is configured.
Because Cloudflare Workers execute globally across hundreds of edge locations, small CORS oversights; such as forgetting to clone immutable fetch() responses, omitting Vary: Origin on cached endpoints, or leaving Cloudflare Access enabled without OPTIONS bypass; can break SPA requests immediately across every region. Centralize your origin allowlist and 204 preflight handler in a dedicated TypeScript module (or Hono middleware), ensure every catch block wraps 500 error responses with withCors(), and validate both OPTIONS and POST responses against wrangler dev and staging before cutting over production DNS.
Step-by-Step Cloudflare Workers API + Static SPA (Pages/Vite) CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for Cloudflare Workers API.
1Build a Reusable CORS Helper With Strict Origin Validation in Workers
src/cors.tsCreate a zero-dependency helper that validates the incoming Origin header against a strict Set of allowed frontend origins, returns clean 204 preflight responses, and clones Responses safely so immutable upstream headers never throw runtime TypeErrors.
src/cors.tstypescriptconst ALLOWED_ORIGINS = new Set([ 'https://app.opscheck.dev', 'http://localhost:5173', ]); export function getCorsHeaders(request: Request): Record<string, string> { const origin = request.headers.get('Origin'); const headers: Record<string, string> = { 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Max-Age': '86400', Vary: 'Origin', }; if (origin && ALLOWED_ORIGINS.has(origin)) { headers['Access-Control-Allow-Origin'] = origin; } return headers; } export function handleOptions(request: Request): Response { return new Response(null, { status: 204, headers: getCorsHeaders(request), }); } export function withCors(request: Request, response: Response): Response { const mutable = new Response(response.body, response); const corsHeaders = getCorsHeaders(request); for (const [key, value] of Object.entries(corsHeaders)) { mutable.headers.set(key, value); } return mutable; }2Intercept OPTIONS Early in the Worker Fetch Entrypoint
src/index.tsShort-circuit OPTIONS requests at the very top of your Worker fetch() handler before verifying JWTs or parsing request.json(). Wrap all success and error responses with withCors() so 404 and 500 JSON payloads remain readable by your SPA instead of turning into opaque CORS blocks.
src/index.tstypescriptimport { handleOptions, withCors } from './cors'; export default { async fetch(request: Request): Promise<Response> { if (request.method === 'OPTIONS') { return handleOptions(request); } try { const url = new URL(request.url); if (url.pathname === '/v1/validate' && request.method === 'POST') { const body = await request.json(); return withCors(request, Response.json({ valid: true, body })); } return withCors(request, Response.json({ error: 'Not found' }, { status: 404 })); } catch (error) { return withCors( request, Response.json({ error: 'Worker execution failed' }, { status: 500 }) ); } }, };3Use Hono CORS Middleware for Multi-Route Cloudflare Workers APIs
src/app.tsIf your Worker uses the lightweight Hono router, register hono/cors ahead of all routes and pass a callback function for origin so multiple production and local Vite origins are validated cleanly without wildcards.
src/app.tstypescriptimport { Hono } from 'hono'; import { cors } from 'hono/cors'; const app = new Hono(); const allowed = new Set(['https://app.opscheck.dev', 'http://localhost:5173']); app.use( '/v1/*', cors({ origin: (origin) => (allowed.has(origin) ? origin : ''), allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization'], maxAge: 86400, credentials: false, }) ); export default app;4Verify Preflight and Edge Caching Behavior With Wrangler and curl
terminalRun wrangler dev locally and verify both the 204 preflight headers and the presence of Vary: Origin on actual responses before deploying to Cloudflare's edge network.
terminalbashnpx wrangler dev --port 8787 curl -i -X OPTIONS http://localhost:8787/v1/validate \ -H "Origin: http://localhost:5173" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: content-type, authorization"
Common Cloudflare Workers API + Static SPA (Pages/Vite) CORS Pitfalls
Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.
Mutating Immutable Response Headers Returned by fetch() in Workers
When a Worker proxies an upstream service via const res = await fetch(url), calling res.headers.set("Access-Control-Allow-Origin", ..) throws TypeError: Can't modify immutable headers. Always clone with new Response(res.body, res) before setting CORS headers.
Cloudflare Transform Rules or Origin Returning Duplicate CORS Headers
If you configure Cloudflare Transform Rules to inject Access-Control-Allow-Origin at the zone level AND your Worker (or upstream origin) also sets Access-Control-Allow-Origin, browsers reject the duplicate header values. Always use headers.set() inside the Worker or manage CORS in one layer only.
Cloudflare Access Blocking Anonymous OPTIONS Preflights
Browsers never send CF_Authorization cookies on non-credentialed OPTIONS requests. If a Worker API sits behind Cloudflare Access, enable "Bypass OPTIONS requests to origin" in the Access application's CORS settings so preflights reach your Worker instead of receiving a 302 redirect.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your Proxy
Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Multi-Service Subpath Routing Config (/api/, /auth/ & /ws/).
Frequently Asked Questions
- Can I avoid CORS completely by using Cloudflare Pages Functions on the same domain?
- Yes. If your SPA is hosted on Cloudflare Pages (e.g., https://app.opscheck.dev) and your API runs as Pages Functions under /api/* on the exact same origin, browser requests are same-origin and require zero CORS preflights. Use standalone Workers CORS when serving multiple frontends or external API consumers.
- Why does Cloudflare Workers CORS break intermittently across two frontend domains?
- When an API response is cached by Cloudflare CDN without Vary: Origin (or without incorporating Origin into the custom Cache API key), the first requesting domain's Access-Control-Allow-Origin header gets cached and served to the second domain, causing immediate browser rejections.
- Do Cloudflare Workers support Access-Control-Max-Age caching for preflights?
- Yes. Returning Access-Control-Max-Age: 86400 on your 204 OPTIONS response allows browsers to cache preflight approvals (up to 2 hours in Chromium and 24 hours in Firefox), reducing billable Worker invocations on chatty SPAs.
- How should I handle CORS when returning WebSocket upgrades from a Cloudflare Worker?
- WebSocket handshakes do not use CORS Access-Control-Allow-Origin headers, but browsers DO send an Origin header on the upgrade request. Validate request.headers.get("Origin") manually inside your Worker before accepting the WebSocket upgrade to prevent Cross-Site WebSocket Hijacking (CSWSH).
Related CORS Stack Simulators
Browse all 12 stacks →Nginx Reverse Proxy + Docker API CORS Simulator & Fix Guide
Fix Nginx reverse proxy CORS bugs for Docker APIs. Prevent duplicate Access-Control-Allow-Origin headers, add always on 4xx/5xx errors, and handle OPTIONS 204.
Next.js Route Handlers + External Frontend CORS Simulator & Fix Guide
Configure CORS for Next.js App Router Route Handlers serving external SPAs or widgets. Fix 405 OPTIONS preflights, next.config.ts headers, and Vary: Origin.
Node.js Express + React (Vite) CORS Config Simulator & Fix Guide
Resolve CORS preflight errors between Node.js Express APIs and React Vite on port 5173. Generate cors() configs, fix PATCH/DELETE methods, and debug headers.
Laravel + React (Vite) CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between Laravel 11/12 APIs and React Vite on port 5173. Generate config/cors.php with credentials and header rules.