Edge Worker Request Routing, Cache Headers, and Cookies
How Cloudflare Workers and Snippets clone immutable HTTP messages, cache at the edge, route by geography, and run same-URL split tests.
This page summarises Cloudflare Workers and Rules Snippets documentation for changing HTTP requests and responses at the edge: custom headers, caching when the origin sends weak or missing Cache-Control, geography-based routing, CORS for browser clients, server-side A/B tests on one public URL, and related limits. The same patterns appear on Cloudflare Pages Functions (for example A/B testing middleware and CORS); deploy surface differs, but cloning requests and responses and using cookies for affinity work the same way.
Immutable Request and Response: how to add or change HTTP headers
Section titled “Immutable Request and Response: how to add or change HTTP headers”A Worker or Snippet cannot change headers on an existing Response or Request in place. After fetch returns from an origin or Cloudflare Pages, you must construct a new object and set headers on that copy.
When a Worker makes a request to a Cloudflare Pages application, it will receive a response. The response a Worker receives is immutable, meaning it cannot be changed. In order to add, delete, or alter headers, clone the response and modify the headers on a new Response instance.
— Cloudflare, Add custom HTTP headers
The same rule applies when altering responses in examples such as Alter headers, Modify response, and Define CORS headers. For requests, use new Request(request, { headers: new Headers(request.headers) }) or the pattern in Modify request property. To change status or body, build new Response(body, { status, statusText, headers }) as described in Modify response:
Response properties are immutable. To change them, construct a new Response and pass modified status or statusText in the ResponseInit object.
— Cloudflare, Modify response
Common mistake: appending Set-Cookie without cloning
Section titled “Common mistake: appending Set-Cookie without cloning”Same-URL A/B tests and cookie expiry examples fetch a response, then append Set-Cookie. That only works on a new Response cloned from the upstream body and headers. Skipping the clone is a frequent production bug (see A/B testing and Append dates to cookies).
request.cf geolocation: country, ASN, and when it is missing
Section titled “request.cf geolocation: country, ASN, and when it is missing”The cf property on the incoming request exposes geography and network data used in Geolocation: Hello World, Country code redirect, and Conditional response (country, city, colo, asn, timezone, and related fields). Country-based redirects use that object explicitly:
Use the cf object to obtain the country of the request
— Cloudflare, Country code redirect
Accessing the Cloudflare Object documents preview behaviour:
The
cfobject is not available inside the preview.— Cloudflare, Accessing the Cloudflare Object
For logic that depends on IP, ASN, or device type, conditional-response documentation expects a live deployed Worker, not only the playground. Return a clear error JSON when req.cf is undefined instead of silently defaulting.
Edge cache: fetch cf options, Cache API, and origins you do not control
Section titled “Edge cache: fetch cf options, Cache API, and origins you do not control”Cache at the edge when Cache-Control from the origin is weak or absent
Section titled “Cache at the edge when Cache-Control from the origin is weak or absent”Cache using fetch sets options such as cacheTtl, cacheEverything, and optionally cacheKey on fetch(request, { cf: { ... } }), then rebuilds the response so the browser sees your Cache-Control. Custom cacheKey in that example is tied to Enterprise plans; other plans often combine origin fetch options with the Cache API.
Workers Caching targets origins you do not control:
Workers Caching lets you put your own cache layer in front of that origin without changing anything on the origin side.
— Cloudflare, Workers Caching examples
Replace the origin’s Cache-Control with your own. This is the whole point of the pattern: you decide how long Workers Caching stores this response, regardless of what the origin says.
— Cloudflare, Workers Caching examples
caches.default pattern and TTL
Section titled “caches.default pattern and TTL”The Cache API example builds a cache key with new Request(cacheUrl.toString(), request), checks caches.default.match, and on miss fetches then stores:
Use the Cache API to store responses in Cloudflare’s cache.
— Cloudflare, Using the Cache API
Cache API respects Cache-Control headers. Setting s-maxage to 10 will limit the response to be in cache for 10 seconds max
— Cloudflare, Using the Cache API
Use ctx.waitUntil(cache.put(cacheKey, response.clone())) so the client response and the cached copy are separate instances. Cache POST request shows hashing the body for a synthetic GET key—unusual but documented. Cache tags passes cacheTags on the cf option of fetch.
Same-URL A/B testing and cookies without changing the public URL
Section titled “Same-URL A/B testing and cookies without changing the public URL”Split tests assign visitors to control or variant paths while the browser URL stays the same. A/B testing using Workers states the goal:
This architecture shows a same-URL A/B testing endpoint. The A/B testing logic and configuration is deployed on the server side, so that clients do not have to implement any changes to make use of A/B testing.
— Cloudflare, A/B testing using Workers
Implementations include Workers A/B testing, Snippets A/B testing on the same URL, and Pages Functions A/B testing. Typical flow: read a cookie (or assign a random bucket), rewrite internally to /control… or /test…, passthrough real asset paths, set Set-Cookie on a cloned response. Configuration can live in Workers KV. Extract cookie value notes cookies for A/B testing; parsing may use the cookie package or framework helpers.
CORS and third-party API proxy from a Worker
Section titled “CORS and third-party API proxy from a Worker”Browser clients need preflight and response headers. CORS headers on Pages Functions handles OPTIONS with Access-Control-Allow-*. CORS header proxy fetches a third-party API with Origin set to the API’s origin so the upstream is not cross-site, then adds Access-Control-Allow-Origin and Vary: Origin on a cloned response. Define CORS headers applies the same idea in Snippets.
Request routing: redirects, rewrites, and origin failover
Section titled “Request routing: redirects, rewrites, and origin failover”| Pattern | Where documented | Idea |
|---|---|---|
| Path redirect map | Bulk redirects, Bulk redirect map | Map pathname → Response.redirect(location, 301) or passthrough fetch |
| Hostname rewrite | Bulk origin proxy, Route and rewrite | Replace url.hostname, prepend or strip path segments |
| Country redirect | Country code redirect | request.cf.country → map → redirect |
| Origin redirect chains | Follow redirects | fetch(request, { redirect: "follow" }); each hop counts as a subrequest |
When to use Snippets vs Workers lists Snippet-only edge behaviours: maintenance 503, failover when the origin is not OK, stripping JSON fields, and HTMLRewriter link rewrites—often without a separate Worker deploy.
Snippet subrequest limit on redirect chains
Section titled “Snippet subrequest limit on redirect chains”Snippets have a maximum number of subrequests per invocation which depends on your plan. If the origin server issues multiple redirects, each redirect subrequest will count towards this limit. When the number of subrequests exceeds the limit for your Cloudflare plan, you will receive a 1202 error.
— Cloudflare, Follow redirects from the origin
Block or allow requests: IP, User-Agent, PSK header, and Basic Auth samples
Section titled “Block or allow requests: IP, User-Agent, PSK header, and Basic Auth samples”Conditional response branches on hostname, path, method, User-Agent, CF-Connecting-IP, request.cf.asn, and related signals. Auth with headers compares a pre-shared key in a header (not a replacement for Web Crypto). HTTP Basic Authentication is sample-only:
This code is provided as a sample, and is not suitable for production use. Basic Authentication sends credentials unencrypted, and must be used with an HTTPS connection to be considered secure.
— Cloudflare, HTTP Basic Authentication
Use crypto.subtle.timingSafeEqual for secret comparison; do not short-circuit when buffer lengths differ. Protect against timing attacks explains comparing the user input to itself when lengths mismatch so elapsed time does not leak secret length. For production admin surfaces, documentation points to Cloudflare Access rather than embedded Basic Auth credentials.
HTTP 103 Early Hints: faster loads before origin HTML
Section titled “HTTP 103 Early Hints: faster loads before origin HTML”103 Early Hints uses status 103 so clients can prefetch linked assets:
103 Early Hints is an HTTP status code designed to speed up content delivery. When enabled, Cloudflare can cache the Link headers marked with preload and/or preconnect from HTML pages and serve them in a 103 Early Hints response before reaching the origin server.
— Cloudflare, 103 Early Hints
Enable Early Hints under Speed → Content Optimization in the dashboard, or return HTML with Link headers such as </test.css>; rel=preload; as=style from a Worker.
Workers, Snippets, and Pages Functions: where the same code runs
Section titled “Workers, Snippets, and Pages Functions: where the same code runs”| Surface | Typical use in this cluster |
|---|---|
Module Worker export default { fetch } |
Full logic: cache, WebSockets (Using the WebSockets API), R2 multipart HTTP API |
| Rules Snippets | Header, redirect, CORS, maintenance on existing zone routes; stricter subrequest limits |
| Pages Functions | A/B and CORS on static assets via ASSETS and middleware |
Migrate to Module Workers notes Service Workers are deprecated in favour of module Workers. Snippets can set a request header (for example Hex timestamp) that a Worker reads when both are composed (When to use Snippets vs Workers).
WebSockets and response digests (optional Worker APIs)
Section titled “WebSockets and response digests (optional Worker APIs)”WebSocket servers require Upgrade: websocket, a WebSocketPair, response 101 with the client socket, and server.accept() before messaging (Using the WebSockets API). Web Crypto documents streaming crypto.DigestStream on a fetch response body via tee() for headers such as x-content-digest.
Common mistakes at the edge
Section titled “Common mistakes at the edge”- Mutating
ResponseorRequestwithoutnew Response/new Request. - Assuming
request.cfin local preview or playground for ASN, IP, or device tests. - Shipping sample PSK or Basic Auth values from examples unchanged.
- Long origin redirect chains in Snippets → error 1202.
- Relying on Enterprise-only
cacheKeyonfetchwithout a Cache API fallback. - A/B flows that append cookies without cloning the upstream response.
- Data loss prevention regex false positives on
text/*only. - Background logging without
ctx.waitUntil(Debugging logs).
How to check this on your site
Section titled “How to check this on your site”- Deploy the Worker or Snippet with
npx wrangler deploy(as in R2 multipart from Workers) and hit the route withcurl -Ito confirm new or removed headers match Alter headers behaviour. - For geography or ASN logic, test on a live Worker URL—not preview—and compare with Return incoming request properties or your conditional branch.
- For caching, repeat the same URL twice and inspect shared-cache TTL via
Cache-Control/s-maxagefrom Using the Cache API. - For same-URL A/B tests, use a private window, confirm
Set-Cookie, and verify internal rewrites still load assets under/controlor/testpaths per A/B testing. - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about.