Cache from worker not working properly
We did a cache middleware which must store the previous response.
The key is based on the url and we add country, device, displayMode etc on a query parameter.
It is not working properly, I mean it work only if le worker is being called by the same client(without hard refresh). I know the cached is not shared globally but what can we do to make it work when request hit the same datacenter from another clients?
const key = country + '#' + displayMode.mode + '#' + device;
const cache = caches.default;
const reqUrl = new URL(context.req.url);
reqUrl.searchParams.set('cache', key);
let response = await cache.match(reqUrl.toString());
if (!response) {
await next();
response = context.res.clone();
const newResponse = new Response(response.body, response);
newResponse.headers.append('Cache-Control', context.env.CACHE_CONTROL);
console.log("Caching:::", reqUrl.toString());
context.executionCtx.waitUntil(cache.put(reqUrl.toString(), newResponse))
} else {
console.log("Response from cache:::", reqUrl.toString())
return response;
}
0 Replies