Cache html using workers

We have a worker in place to cache html using cache api, basically we have cloned it from here:
From the code

async function cacheResponse(cacheVer, request, originalResponse, event) {
// some code here
response.headers.set('Cache-Control', 'public; max-age=315360000');
event.waitUntil(cache.put(cacheKeyRequest, response));
// more code here

We understand the page will be cached for one year, but we have noticed that sometimes, the pages that are not frequently visited are not cached anymore after a few days or inactivity.
How can we force them to be actually cached for one year? Would be adding more headers like Expires or Cloudflare-CDN-Cache-Control do the trick?
I have tried already, when logging the response retrieved from cache, can see the Expires header, but Cloudflare-CDN-Cache-Control is missing. Is it expected?

Thanks in advance

You can’t force something to be cached for an amount of time with Cloudflare cache. Items will automatically be evicted from cache based on how frequently something has been accessed, plus plan. Some PoPs are smaller and thus have less cache amount available, so higher eviction are likely. There are items like Tiered Cache and Cache Reserve that can help increase cache rates.

Hi, many thanks for your response.
So then if I understood well, headers like cache-control or Cloudflare-CDN-Cache-Control only determine how long cached content should be served before a new copy will be fetched from an origin server, but doesn’t mean these resources will be present on CDN cache for that amount of time.

So next question is, can we somehow handle what is on cache reserve using workers? Cause I believe even enabling Tiered Cache and Cache reserve, since what we want to cache is HTML code, it would be ignored?

Correct. The headers tell Cloudflare, “Please cache this for 6 hours at most” which Cloudflare respects but will evict sooner from their cache if necessary.

The workers cache follows the same as the normal cache, but you might be able to do some caching with KV. I personally do it with some JSON data that I get from APIs but it would work for HTML as well.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.