React SPA loses session cookie intermittently when routed through Cloudflare Worker edge scripts
Environment
Single-page React app (production build, served from an S3 bucket behind Cloudflare CDN). Authentication is cookie-based (HTTP only, SameSite=Lax, Domain=example.com). Cloudflare account uses Workers to rewrite URLs and inject headers at the edge. Origin runs Node.js Express for API at api.example.com. Incidents seen in Chrome 120 and Firefox 119 on desktop and mobile browsers.
Symptoms
Users intermittently appear logged out while the browser still shows session cookie present in DevTools; subsequent API calls receive 401 from origin. Issue is transient and resolves after page refresh or after 10–30 seconds. Affected requests are often the first POST after page load or after navigation handled by the Worker.
Observations
Cloudflare Worker logs show that some incoming requests lack the Cookie header when forwarded to origin; Worker sometimes sets Set-Cookie in response but the browser does not persist it. When tracing with curl against Cloudflare edge, responses to the browser include Set-Cookie but the header is dropped on subsequent requests. Reproduces more frequently when the Worker rewrites hostnames (proxying api.example.com to origin-internal.example) or when Worker returns an early 302 redirect. No issues when bypassing Cloudflare (direct DNS to origin) and requests include expected cookies. Browser console shows no JS errors; cookies are marked Secure and HttpOnly.
Already attempted
Disabled Worker and confirmed cookie behavior restored (no more intermittent loss). Reduced Worker script to a simple header passthrough — issue absent. Reintroduced URL rewrite logic gradually; issue reappeared when rewriting to an internal host and setting a custom Host header in fetch(). Tried using fetch(event.request) vs. fetch(modifiedRequest) in Worker; same pattern. Verified cookie domain and path settings; tested with SameSite=None; issue persists only when Worker alters request host header or emits a redirect.
Question
Why are session cookies intermittently missing when requests are forwarded by a Cloudflare Worker that rewrites host/redirects, and what changes to Worker logic or cookie configuration will reliably preserve cookies without weakening security?
Verified community troubleshooting
No answers yet..
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags