Caching Cloudflare Worker responses fetching from an external source

#1

Hi there,

We’re using Cloudflare workers to act as a reverse proxy to a downstream Wordpress server.

Works great.

I raised a ticket with Cloudflare about this, but they have been unable to answer - so hoping somehwere here can.

Question: how do i cache these requests in Cloudflare?

Ideally, i’d like to set the cache expiry based on the Wordpress headers. But, if that’s not possible - i’m happy to ‘force’ an arbitraty TTL, as long as i can check for a successful response first.

My worker code is pretty simple, the pertinent part is this:

return fetch(fetchUrl)

The best documentation i’ve found is this:

The docs indicate this:

fetch(event.request, { cf: { cacheEverything: true } })

But this seems to always result in a CF-Cache-Status: MISS:

We can force a cacheTtl:

fetch(event.request, { cf: { cacheTtl: 300 } })

But like i said this is risky because if there’s an error in Wordpress, it’ll be cached (i’m not on enterprise plan, so can’t cache by status code)

So, it feels like i need to:

  • Fetch the response from Wordpress
  • Check the status code
  • If status code is non-200, just return it through
  • If status code is 200, manually add to the cache (e.g cache.put)

Can someone provide suggestions, and ideally - some examples?

Thanks

0 Likes

#2

@pmeenan did something similar:

This comes from his blog post back in December:

0 Likes

#3

this may sound silly, but is there a simpler way? Workers KV isn’t really rolled out publicly yet, and i don’t really want to install a Cloudflare plugin into Wordpress if i don’t have to.

I thought it’d be much simpler… like, just return the response from the worker and add to cache somehow

0 Likes

#4

There’s the Cache API, that lets you programatically control the cache https://developers.cloudflare.com/workers/reference/cache-api

0 Likes