Caching requests with Workers

Is there a way to cache responses directly with Workers? I know they have access the Cache API, but I’m not sure how to use them. Or would it be better to just store the responses in global JavaScript variables?

I’m wondering if I can return a cached response for all requests that don’t contain certain cookies such as comment_author or wordpress_logged_in.

Basically the “Bypass Cache Cookie” page rule which is only available on Business plans.

1 Like

Hi @till,

We recently released a feature (independent of Workers) that does exactly this: https://support.cloudflare.com/hc/en-us/articles/236166048

Unfortunately, Cloudflare Workers does not yet have access to the Cache API – we’re working on it.

Your worker runs before checking cache. More precisely, when you make a subrequest (that is, when you call fetch()), the subrequest is potentially served from cache. So, ideally, all you’d need to do is mark the subrequest to be non-cacheable. However, at this time, there isn’t a way to do that. We are planning to add one, similar to the other flags described here, but it’s not there yet. Sorry!

1 Like

Thanks @KentonVarda! What’s the best way of staying up to date with changes such as the one you’re working on?

Purhaps related. I would like to be able to cache the output of a worker. I have a very simple worker that converts all urls to lowercase - do to a legacy system that was case insensitive we have several hundred thousand URLs that are used in all various forms of casing. I have a worker that basically just does request.url.toLowerCase() and redirects with a 301. I would like the results of these to be catchable so that the worker only runs once per url.

Obviously this would cut my costs down significantly which maybe isn’t what you want, but it would be super helpful to me. :slight_smile:

That sounds cool because, from what I understand, that would make workers which make requests even more quicker. Is there an update on when (and if) we can expect this feature?


Edit: Wait, that’s not right what I say. :slight_smile: There’s no speed difference with the Worker if the requested asset is already cached at the Cloudflare POP. Do I understand that correctly?

I seem to be getting success with: Cloudflare Workers: Edge caching anonymous requests - @mmaton

Gist: https://gist.github.com/mmaton/8e1a6b0cf4033dc96a17bb40e1d19b93/raw/82a5c1a5238d0264b1f7e3b6930d68f8c4f87698/Wordpress%2520CF%2520Edge%2520Cache%2520Busting

It would be interesting to consult cache, before consulting a worker.

if we use fetch in a worker, and we know that the data fetched is only updated every 30 minutes, there is no sense in running the worker every requests.

Serving the response from cache instead, without running the worker, would:

  1. make response time much faster
  2. would not consume our worker resources.

Looking forward to a way to include this.

2 Likes

You can already do this: