I'm working on a Cloudflare Worker to manage cached responses for an API. Here's the workflow I've implemented:
- Created a cache instance using
caches.open()
in a Cloudflare Worker. - Added response headers to the cache before doing
caches.put()
- Response Headers:
Cache-Control: public, max-age=86400
, A customCache-Tags
header with specific tags. - Ensured I called
event.waitUntil(caches.put(...))
to handle asynchronous operations properly.
Example Code:
async function setCacheWithTags(event, key, response) {
response.headers.set('Cache-Control', 'public, max-age=3600');
response.headers.set('Cache-Tags', 'cache-tag-A');
const cacheInstance = caches.default;
await event.waitUntil(caches.put(key, response.clone()))
return response;
}
Everything works fine for caching responses. However, I’m facing issues when trying to purge the cache by tags. I’m using the Cache Purge API with the zone ID of my domain to purge by cache tags.
Here is the cURL for the Cache Purge API:
curl /$ZONE_ID/purge_cache \
-H 'Content-Type: application/json' \
-H "X-Auth-Email: $CLOUDFLARE_EMAIL" \
-H "X-Auth-Key: $CLOUDFLARE_API_KEY" \
-d '{
"tags": [
"a-cache-tag",
"another-cache-tag"
]
}'
The above API call returns a success response saying the cache was purged. But when I make a GET call to my deployed API, the new changes on server are not reflected.
It seems like the purge operation does not affect the cache created via caches.open() and caches.put().
Questions:
- Does the Cache Purge API support purging cache created using caches.open() or caches.put() in Cloudflare Workers?
- Is there a specific limitation when using cache tags with these methods?
- What is the recommended approach to manage and purge cache in Cloudflare Workers when using the Cache API?