async function handleRequest(event)
{
let request = event.request;
let ttl = undefined;
let cache = caches.default;
let url = new URL(event.request.url);
let shouldCache = false;
// cache JSON files with custom max age
if (url.pathname.endsWith(’.json’))
{
shouldCache = true;
ttl = 60;
}
// look in cache for existing item
let response = await cache.match(request);
if (!response)
{
// fetch URL
response = await fetch(request);
// if the resource should be cached then put it in cache using the cache key
if (shouldCache)
{
// clone response to be able to edit headers
response = new Response(response.body, response);
if (ttl)
{
// https://developers.cloudflare.com/workers/recipes/vcl-conversion/controlling-the-cache/
response.headers.append('Cache-Control', 'max-age=' + ttl);
}
// put into cache (need to clone again)
event.waitUntil(cache.put(request, response.clone()));
}
return response;
Are you simply taking all .json files and then forcing a cache for all of them for 60 seconds? You are doing that because you can’t add that header on the origin?
I would optimize it in this direction but in this example, all .json will answer with 200.
const cache = caches.default;
const handleRequest = async (event) => {
const request = event.request;
let ttl = undefined;
let url = new URL(event.request.url);
// cache JSON files with custom max age
if (url.pathname.endsWith(".json")) {
//shouldCache = true;
ttl = 60;
}
/* look in cache for existing item */
let response = await cache.match(request);
if (!response) {
// fetch URL
response = await fetch(request);
// if the resource should be cached then put it in cache using the cache key
if (ttl != undefined) {
// clone response to be able to edit headers
response = new Response(response.body, {
status: 200,
statusText: "OK",
headers: {
"Cache-Control": `max-age=${ttl}`,
"Content-Type": "application/json;charset=UTF-8",
},
});
// put into cache (need to clone again)
event.waitUntil(cache.put(request, response.clone()));
}
return response;
}
return response;
};
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
Adding simply the .json extention to cloudflare static caching, is not want you want with JSON - unless it really rarely changed - or is versioned by filename. You probably want something like 60 seconds or 5 minutes so that if you update a file it’ll update within that time but your server won’t get bombarded with individual requests from every end user!
You can set a TTL to the normal static caching, it wouldn’t be really an issue. Add a cache everything rule for example.com/*.json and add the header on the origin. You don’t need Workers. Alternatively @adaptive optimized as much as possible, I believe.