Caching with Workers


I’m using the following JS to perform some HTML manipulation and caching per device type:

async function handleRequest(e) {
  let request = e.request
  let url = new URL(request.url);

  let params = url.searchParams;
  let userAgent = request.headers.get('User-Agent') || '';
  let deviceType = 'd';

  if(isMobileAgent(userAgent)) {
    deviceType = 'm';
  } else if(isTabletAgent(userAgent)) {
    deviceType = 't';
  if(!params.has('xmbdt')) {
    params.append('xmbdt', deviceType);
  } = params;

  let cache = caches.default;
  let rewriter = new HTMLRewriter().on('div.entry-utility', { element:  e => e.remove() });
  let response = await cache.match(url.toString());

  if(response) {
    return response;
  response = await fetch(url, new Request(request, {cf: {cacheTtl: 604800}}));
  response = rewriter.transform(new Response(response.body, response));
  response.headers.set('x-mb-devicetype', deviceType);

  e.waitUntil(cache.put(url.toString(), response.clone()))

  return response

The expected behaviour, and that which I’ve observed, is that pages are cached for 1 week per device type - before they are added to the cache, ‘div.entry-utility’ is removed if present.

I have 2 questions that I would appreciate some help with:

  1. Cloudflare runs at “the edge.” So Workers, Caching, etc, are local to the user. Edge locations are pretty much independent, so the cache is local; not network-wide.
  2. Purge Cache does happen network-wide across all locations.
1 Like

Thanks for the prompt response!

Do you know if there are plans to offer a network-wide caching option?

No. I’m pretty sure that even Enterprise plans don’t get this. That would be a Push CDN, and Cloudflare doesn’t do that. There are CDNs out there that do, though.

1 Like