Cloudflare Worker Cache API not saving results

const cache = (caches as any).default;
await cache.put(request, response.clone());
const stored = await cache.match(request);
console.log('finished storing cache key');
console.log('stored', stored);

I’m trying to save some data using the Cloudflare Cache API on my Cloudflare Worker. However, when executing the code above, it doesn’t seem like I’m able to retrieve the Response that’s stored. (console.log('stored', stored); returns null for stored).

Does anyone have any insight into what went wrong?

Note that cache doesn’t work on the dashboard editor.
const cache = caches.default;

Also, you need to return a Response.

This example might help:

1 Like

Thanks adaptive. I think the cf settings in fetch are different from what I’m trying to do.

I ended up fixing this by throwing away everything in the response except the body and creating a new Response object to be saved in cache.

  const clone = response.clone();
  const saveResponse = new Response(clone.body, {status: 200, headers: new Headers({'Cache-Control': `max-age=${CACHE_EXPIRATION}`})});

  const cache = (caches as any).default;
  await cache.put(request, saveResponse.clone());

There’s a little note in the documentation saying that Response objects with Set-Cookie headers are never cached, which might have been where I went wrong. I was expecting cache.put to throw some sort of error, but it seems like it just doesn’t save the response and moves on.

1 Like