Purging fetch cache using a custom cache key

I’m having a Worker serving requests to https://example.com/foo.json by doing a fetch under the hood, to proxy the request to my origin server and respond back to the client, while also caching the response.

The code is this:

export default {
  async fetch(request) {
    const url = new URL(request.url);
    const cacheKey = `https://${url.hostname}${url.pathname}`;

    // prepare request to proxy to origin
    const headers = new Headers(request.headers);
    headers.set("foo", url.host);
    url.host = "originserver.com"

    let response = await fetch(url.toString(), {
      cf: {
        cacheKey: cacheKey,
        cacheTtl: 3600,
        cacheEverything: true,
        cacheTtlByStatus: {
          '100-199': 0,
          '200-299': 3600,
          '300-599': 0,
        }
      },
      headers: headers,
    });

    response = new Response(response.body, response);
 
    return response;
  },
};

Now, this works properly AFAICT: I see CF-Cache-Status: HIT and Last-Modified: <a date in the past> in my requests to https://example.com/foo.

However, I now want to purge that fetch cache by URL/single-file, via the API. So in my understanding, I should execute the following:

$ curl -s -X POST "https://api.cloudflare.com/client/v4/zones/xxx/purge_cache" -H "Authorization: Bearer xxx"  -H "Content-Type: application/json" -d '{"files":["https://originserver.com/foo.json"]}'

# or maybe
$ curl -s -X POST "https://api.cloudflare.com/client/v4/zones/xxx/purge_cache" -H "Authorization: Bearer xxx"  -H "Content-Type: application/json" -d '{"files":[{"url":"https://originserver.com/foo.json", "headers": {"foo": "example.com"}}]}'

Both of these requests seem successful:

{
  "success": true,
  "errors": [],
  "messages": [],
  "result": {
    "id": "xxxxxx"
  }
}

However, when I re-request the original URL from my terminal, I still see a CF-Cache-Status: HIT and Last-Modified being unchanged from the initial requests.

I think I’m misunderstanding something on how cache purging should work in my case (i.e. Workers fetch cache, using a custom cache key). Is what I’m doing supposed to work?

Thanks in advance

Purge cache key resources · Cloudflare Cache (CDN) docs.

Hey @cscharff, were you referring specifically to this part?

Currently, it is not possible to purge a URL stored through Cache API that uses a custom cache key set by a Worker. Instead, use a custom key created by Page Rules. Alternatively, purge your assets using purge everything, purge by tag, purge by host or purge by prefix.

If so, that part talks about the Cache API (https://developers.cloudflare.com/workers/runtime-apis/cache/), which is not what I’m using here in my example. Instead, I use the fetch cache.