Can I make a worker only run if Cloudflare hasn't cached the page?


My use case is: I have an asset at /foo.png that is often cached by Cloudflare. When it’s not cached, it goes to my origin server.

I would like to add a worker that handles the /foo.png route ONLY if Cloudflare doesn’t have the asset cached, and would otherwise be going to the origin server.

So far as I know, if I put a worker on the /foo.png route, it will ALWAYS handle the route, regardless of whether Cloudflare is caching it via page rules or not.

Is there any way (even something complicated involving forwarding) to make it so the worker will only run if the asset is not cached, and it would otherwise have to go to the origin server?

As far as I know there is no way to do that. You can prevent the code to run within the Worker by using the Cache API.


Just note that the worker will still bill - it would be a nice feature to be able to cache in front of the worker.

Yeah, it could be useful, but it’s extremely hard since the stack runs first through Workers and then Cache…

well I can think of some way to hack it like:

make the worker response to:

make the foo.png directly to your origin
when your origin is hit, your origin will make a fetch to /test.png

that way when foo.png is cached your worker will not work
when its not cache it will get called from your origin

For one POP, maybe, but it would need to be done for 180+ POPs, otherwise it doesn’t make sense.

maybe I missed your point but it should work just like he asked…
the cache is anyway local to each pop, so even if cf would give a way to run worker only on uncached routes its also will need to be cached on 180 pops

Oh I see, but I presume he would like to reduce the load of the origin, this way he would increase it. Simply use the function on the Worker in Node.js, it would be simpler.

Just gonna bump this^

Being able to specify a response to be cached in front of Workers (such as via a property in would be great for reducing costs :slight_smile:

1 Like

+1 this!

I think Workers are amazing, but the main reason that I am not using them currently is because Cloudflare Workers always run before the cache.

Generally, I use Cloudflare to sit in front of my pay-per-request cloud servers. And Cloudflare is great for caching responses to common routes so that the requests don’t need to hit my servers as much.

I feel that a Worker is also essentially a “pay-per-request cloud server”, except it doesn’t benefit from Cloudflare’s cache in the same way.