The Workers Cache API refuses anything with Set-Cookie
I was putting an upstream response into caches.default inside a Worker and
put() kept throwing instead of caching. The response was fine. It just had a
Set-Cookie header on it.
That is deliberate. Caching a response with a cookie in it means handing one
visitor's cookie to the next visitor, so the runtime refuses rather than
letting you do it by accident. put() also rejects a 206, a request that is
not a GET, and a response with Vary: *.
Two ways out. Clone the response and drop the header before caching:
const toCache = new Response(response.body, response);
toCache.headers.delete("Set-Cookie");
ctx.waitUntil(cache.put(request, toCache.clone()));
Or, if the cookie genuinely needs to reach the browser and the rest of the body is shared, tell the cache to keep everything except that header:
Cache-Control: private=Set-Cookie
The ctx.waitUntil in there is the other half of the lesson. Once you return
the response, the runtime is free to tear the request context down, and a
cache.put() promise you neither awaited nor handed to waitUntil can just
disappear. You get no error. You get a cache that is mysteriously always cold,
which is a much worse afternoon than a thrown exception.
Also worth knowing: the cache key is the full URL including the query string. A tracking parameter on the end is a different cache entry.