skip to content

In a Cloudflare Worker, how do you reuse an expensive JSON response with caches.default, cache.match() and cache.put()?

level: juniorimportance: must knowfreq 45%

answer

  1. a key-value store you drive
  2. a GET Request is the key
  3. undefined means a miss
  4. store a clone, return the original
  5. Cache-Control sets the lifetime

basics

~10 s

Build a GET Request as the key and return caches.default.match(key) when it hits; on a miss, build the response with a Cache-Control lifetime, store response.clone() with cache.put() inside ctx.waitUntil, and return the original.

solid answer

~40 s

The Cache API is a key-value store I drive from code: the key is a `GET` `Request` (really its URL) and the value is a `Response`. I call `await caches.default.match(cacheKey)` first; it resolves to the stored response or `undefined`, and it never goes to the origin by itself. On a miss I make the upstream calls, build one `Response` whose `Cache-Control` (say `s-maxage=300`) sets the edge lifetime, and pass `cache.put(cacheKey, response.clone())` to `ctx.waitUntil()` so the write finishes after the reply. The clone matters because a body can be read only once. I strip tracking parameters before building the key so they do not split the cache, and I remember the entry exists only in the data center that ran the Worker.

code

javascript · 25 lines
javascript
export default {
  async fetch(request, env, ctx) {
    if (request.method !== "GET") {
      return new Response("Method not allowed", { status: 405 });
    }
    const url = new URL(request.url);
    url.searchParams.delete("utm_source");
    const cacheKey = new Request(url.toString());
    const cache = caches.default;

    const cached = await cache.match(cacheKey);
    if (cached) return cached;

    const [prices, stock] = await Promise.all([
      fetch("https://prices.example.com/v1/list").then((r) => r.json()),
      fetch("https://stock.example.com/v1/levels").then((r) => r.json()),
    ]);
    const response = Response.json(
      { prices, stock, builtAt: new Date().toISOString() },
      { headers: { "Cache-Control": "public, max-age=60, s-maxage=300" } },
    );
    ctx.waitUntil(cache.put(cacheKey, response.clone()));
    return response;
  },
};

go deeper

for a junior

Recall the four moves: build a GET key, match, on a miss build and store a clone, return the original. Know that match() returns undefined on a miss and never calls the origin.

for a middle

Explain what sets an entry's lifetime (Cache-Control, Expires on the stored response), why the clone is needed, and how query strings and tracking parameters shape the key.

for a senior

Show you know the entry is local to one data center, that put() reports nothing, and that per-user data must never share a key; describe how you would confirm a write actually landed.

for a principal

Frame the Cache API as the low-level option: the Worker runs on every request and owns keys, lifetimes and purges, which a team must standardise if several services use it.

## What the Cache API is Inside a Cloudflare Worker, the **Cache API** is a programmatic handle on Cloudflare's edge cache. It behaves like a small **key-value store**: the key is a `Request` (in practice its URL, and it must be a `GET`), and the value is a `Response`. Nothing enters the cache through this API unless the Worker writes it, and nothing comes out unless the Worker asks. That makes it the tool for caching a response the Worker *built itself*, such as a JSON document assembled from several upstream calls, which no origin cache would ever see as one object. Two handles exist: | Handle | How you get it | Shared with `fetch()` subrequests? | |---|---|---| | `caches.default` | a property, no `await` | yes, it is the zone cache that `fetch()` reads and fills | | a named cache | `await caches.open("api:v1")` | no, a separate namespace | ## The read-through pattern, step by step 1. **Build the key.** Create a `GET` `Request` for the URL that identifies the result. A string URL also works as a key. 2. **Look it up.** `await cache.match(cacheKey)` resolves to the stored `Response` or to `undefined`. It **never** sends a request to the origin on a miss. 3. **On a hit, return it.** The work is skipped. 4. **On a miss, do the work** (here, two upstream calls in parallel) and build one `Response`. 5. **Give it a lifetime.** Put a `Cache-Control` header on that response; `s-maxage` sets the edge lifetime and `max-age` what the browser keeps. 6. **Store a clone.** `cache.put(cacheKey, response.clone())` streams the body into the cache. Wrapping it in `ctx.waitUntil()` lets the write finish after the reply has gone out. 7. **Return the original** to the visitor. ## Choosing the key - The **full URL, query string included**, identifies the entry, so `?utm_source=a` and `?utm_source=b` are two entries unless you delete the parameter before building the key. - Keep **per-user data out of a shared key**. Two visitors who map to the same key get the same stored body; put a user or tenant id in the key, or do not cache. - `cache.put()` **throws** for a key whose method is not `GET`. To cache the result of a `POST`, hash its body into a synthetic `GET` URL. - `cache.match(request, { ignoreMethod: true })` treats any method as `GET` for the lookup. ## What decides how long an entry lives The Cache API reads the headers on the response passed to `put()`: - **`Cache-Control`** sets freshness, following Cloudflare's cache directives; `no-store` or `private` means the entry is not kept. - **`Expires`** is honoured as an expiry time. - **`ETag`** and **`Last-Modified`** let `match()` answer a conditional request (`If-None-Match`, `If-Modified-Since`) with `304 Not Modified`. - **`Cache-Tag`** labels the entry so a later purge by tag can remove it. - `stale-while-revalidate` and `stale-if-error` are **not supported** by `put()` and `match()`: an expired entry is simply a miss. ## Things that surprise newcomers - Unless it throws for an invalid input (a non-`GET` key, a `206`, `Vary: *`), `put()` resolves to `undefined` **whether or not** anything was stored, so success has to be checked with a later `match()`. - A response body can be read **once**. Passing the response you return to `put()` leaves nothing for the client; reading it afterwards throws "Body has already been used". - A response with **`Set-Cookie`** is never stored unless you remove that header or add `Cache-Control: private=Set-Cookie`. - The entry lives **only in the data center that ran the Worker**. Visitors elsewhere fill their own copies, so expect a lower hit ratio than a zone-wide cache would give. - Cache API calls count toward the per-request limit shared with subrequests: **50** per request on Workers Free, **1,000** on Workers Paid. The largest object is **512 MB**. - Calls made in the dashboard editor or the Playground preview have no effect, so test on a deployed route or locally with `wrangler dev`. ## When the Cache API is the wrong tool - **The Worker only proxies an origin.** A `fetch()` subrequest already reads through the zone cache, and through Tiered Cache where it is enabled, and its `cf` options set lifetimes without any `match()` or `put()` code. - **Every location must see the same value at once.** A per-location cache cannot promise that; a globally replicated store or a short lifetime has to. - **The response differs per visitor** and nothing in the key separates visitors. Caching it shares one person's data with the next. Used this way, an expensive aggregation runs once per data center per lifetime instead of once per request, and the Worker stays in control of what is stored, under which key and for how long.

  • What is the difference between caches.default and a cache returned by caches.open()?
    `caches.default` is the zone cache that `fetch()` subrequests also read and fill, so a `put()` there can replace what a fetch cached for the same URL. `await caches.open("api:v1")` returns a separate namespace that `fetch()` never touches, which keeps a Worker's own entries apart. `caches.default` is a property; `caches.open()` returns a promise. Both are local to one data center.
  • Why does the code store response.clone() rather than the response it returns?
    `cache.put()` consumes the body as it streams it into the cache. If you store the object you also return, the client is left with a used body, and reading it afterwards throws "Body has already been used". `response.clone()` tees the body, so one branch goes into the cache and the other to the visitor.
  • How does cache.match() answer a request that carries If-None-Match or Range?
    `match()` honours the request's conditional and range headers: `If-None-Match` against a stored `ETag` and `If-Modified-Since` against `Last-Modified` produce a `304 Not Modified`, and `Range` produces a `206` from a stored response with `Content-Length`. If you always want the full body, build the key as a fresh `Request` from the URL alone.

  • cache.match() fetches from the origin and stores the result when the key is missing
  • cache.put() returns false when the cache declines to store the response
  • The same Response object can be stored with cache.put() and also returned
  • An entry stored with cache.put() is available in every Cloudflare data center
  • stale-while-revalidate on the stored response makes match() serve stale copies