I have a Cloudflare Pages project that uses _worker.js with a domain of pages.sevfurneaux.co.uk.
The _worker.js has the following Cache API test code:
export default {
async fetch(request, env, ctx) {
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
let response = await cache.match(cacheKey);
if (!response) {
console.log(
`Response for request url: ${request.url} not present in cache. Fetching and caching request.`
);
// If not in cache, get it from origin
response = new Response(new Date(Date.now()).toUTCString(), {
headers: { "Content-Type": "text/plain" },
});
// Must use Response constructor to inherit all of response's fields
response = new Response(response.body, response);
// 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=3600");
ctx.waitUntil(cache.put(cacheKey, response.clone()));
} else {
console.log(`Cache hit for: ${request.url}.`);
}
return response;
},
};
However, when purging the cache using Purge Everything, the cache isn’t cleared.
In contrast, the cache for my Cloudflare Workers project at https://test.sevfurneaux.co.uk is cleared. This worker has identical code to the code used in the above Pages _worker.js file:
export default {
async fetch(request, env, ctx) {
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
let response = await cache.match(cacheKey);
if (!response) {
console.log(`Response for request url: ${request.url} not present in cache. Fetching and caching request.`);
// If not in cache, get it from origin
response = new Response(new Date(Date.now()).toUTCString(), {
headers: { 'Content-Type': 'text/plain' },
});
// Must use Response constructor to inherit all of response's fields
response = new Response(response.body, response);
// 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=3600');
ctx.waitUntil(cache.put(cacheKey, response.clone()));
} else {
console.log(`Cache hit for: ${request.url}.`);
}
return response;
},
};
So to conclude, do Cloudflare Pages workers that use the Cache API act differently to a Workers project that uses the Cache API?