Caching requests with Workers


#1

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.


#2

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!


#3

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


#4

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:


#5

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?


#6

I seem to be getting success with: https://www.mmaton.com/2018/07/02/cloudflare-cache-anonymous-requests/

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