CloudFlare worker cache does not work

The CloudFlare worker cache API does not ever work.

Using the sample code here:
https://developers.cloudflare.com/workers/examples/cache-api

We can modify it to ALWAYS cache, and to respond with the current timestamp in milliseconds:

async function handleRequest(event) {
  const request = event.request
  const cacheUrl = new URL(request.url)

  // Construct the cache key from the cache URL
  const cacheKey = new Request(cacheUrl.toString(), request)
  const cache = caches.default

  // Check whether the value is already available in the cache
  // if not, you will need to fetch it from origin, and store it in the cache
  // for future access
  let response = await cache.match(cacheKey)

  if (!response) {
    response = new Response(Date.now())

    // Cache API respects Cache-Control headers. Setting s-max-age to 10
    // will limit the response to be in cache for 10 seconds max

    // Any changes made to the response here will be reflected in the cached value
    response.headers.append("Cache-Control", "s-maxage=100")

    // Store the fetched response as cacheKey
    // Use waitUntil so you can return the response without blocking on
    // writing to cache
    event.waitUntil(cache.put(cacheKey, response.clone()))
  }
  return response
}

addEventListener("fetch", event => {
  try {
    const request = event.request
    return event.respondWith(handleRequest(event))
  } catch (e) {
    return event.respondWith(new Response("Error thrown " + e.message))
  }
})

We have deployed the above code here, and as you can see:
https://jacob-test.nichehacks.workers.dev/

Every time you refresh the page, the timestamp updates, so the cache is NEVER used.

How can we enable the cache to actually work like the docs say it should?

Here is a very helpful video how to Deploy to a Custom Domain with Cloudflare Wrangler Environments.
I haven’t used the wrangler deploy, but I’ve set up DNS and Worker Route as suggested the author and it helped.

I’ve created the following DNS:
Type: CNAME
Name: cache-worker
Target: @
Proxy status: Proxied

And the following Route (Worker - Route):
Route: https://cache-worker.mydomain.com
Worker: cache-worker

Where the ‘cache-worker’ is the name of my worker, which I’ve created using the Cloudflare Worker UI.

Cache API is not enabled on workers.dev - this is due to the cache being at the zone level (meaning it’d be shared between everyone on workers.dev)

You will need to deploy this over a custom domain to see it work.

2 Likes