Changing CacheTtl based on Response HTML?

I was hoping to adjust the edge CacheTTL based on the contents of the Response. In my specific case, I wanted to pull a modified date on the page. If the modified date > XX days, I’d like to cache it longer.

Starting with this basic code:

self.addEventListener(‘fetch’, event => event.respondWith(handle(event)))

async function handle(event) {
const cache_time = 900
let cache = caches.default
let response = await cache.match(event.request)

if (!response) {
response = await fetch(event.request, {
cf: {
cacheTtl: cache_time
}
});
event.waitUntil(cache.put(event.request, response.clone()))
}

return response
};

The CacheTtl is set on the fetch event. So I tried to fetch again using a longer cache_time if my condition was met. But I couldn’t get it to work. It would never follow the new cache time. Here’s what I was trying to do:

self.addEventListener(‘fetch’, event => event.respondWith(handle(event)))

async function handle(event) {
const cache_time_long = 10000
const cache_time = 900
let cache = caches.default
let response = await cache.match(event.request)

if (!response) {
response = await fetch(event.request, {
cf: {
cacheTtl: cache_time
}
});
let html = await response.text()

if (some condition)
  {
    response = await fetch(event.request, {
        cf: {
          cacheTtl: cache_time_long
        }
     });
   }

event.waitUntil(cache.put(event.request, response.clone()))
}

return response
};

This didn’t work. Any suggestions if this is possible?

There two cacheable operations:

  • request (server to cloudflare)
  • response (cloudflare to client)

You need to set/override/manipulate cache headers on the response to benefit from cache.default.
Just an exemple below.

  const responseInit = {
    headers: {
      "Content-Type": "text/css",
      "Access-Control-Allow-Origin": `https://${parsedUrl.hostname}`,
      "Cache-Control": "max-age=604800"
    }
  };

  response = new Response(body, responseInit);
  event.waitUntil(cache.put(event.request.url, response.clone()));
1 Like

My understanding is that that will only affect browser cache settings. I want the Cloudflare edge server to cache the result for longer.