CORS & Preflight Simulator · Cloudflare Workers API + Static SPA (Pages/Vite)

Cloudflare Workers API + SPA Frontend CORS Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between Static SPA (Pages/Vite) and Cloudflare Workers API. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (Static SPA (Pages/Vite))

2. Server Response Policy (Cloudflare Workers API)

Access-Control-Allow-Methods
# nginx.conf — Reverse Proxy CORS Block
# IMPORTANT: Disable CORS headers in your upstream app (or proxy_hide_header)
# to avoid duplicate 'Access-Control-Allow-Origin' headers.

location /v1/validate/ {
    # Handle CORS Preflight (OPTIONS) directly at the gateway
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' 'https://app.opscheck.dev' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
        add_header 'Access-Control-Max-Age' 86400 always;
        add_header 'Vary' 'Origin' always;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    # Strip upstream CORS headers if the backend also emits them
    proxy_hide_header Access-Control-Allow-Origin;
    proxy_hide_header Access-Control-Allow-Credentials;
    proxy_hide_header Access-Control-Allow-Methods;
    proxy_hide_header Access-Control-Allow-Headers;

    # Apply CORS headers to actual responses (including 4xx/5xx via 'always')
    add_header 'Access-Control-Allow-Origin' 'https://app.opscheck.dev' always;
    add_header 'Vary' 'Origin' always;

    proxy_pass http://api_upstream;
    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;
}

Preflight (OPTIONS)

Triggered · Passed

Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, https://app.opscheck.dev', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.opscheck.dev
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.opscheck.dev
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

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:

DevTools Console Output

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.

  1. 1Build a Reusable CORS Helper With Strict Origin Validation in Workers

    src/cors.ts

    Create 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.tstypescript
    const 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;
    }
  2. 2Intercept OPTIONS Early in the Worker Fetch Entrypoint

    src/index.ts

    Short-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.tstypescript
    import { 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 })
          );
        }
      },
    };
  3. 3Use Hono CORS Middleware for Multi-Route Cloudflare Workers APIs

    src/app.ts

    If 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.tstypescript
    import { 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;
  4. 4Verify Preflight and Edge Caching Behavior With Wrangler and curl

    terminal

    Run 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.

    terminalbash
    npx 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tool · Same-Origin Reverse 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/).

Open Nginx Builder

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).
Browse all 12 stacks →