Does the fetch() method return a cached object ONLY if it's locally cached at the edge node?

Here’s a line that fetches a URL in some worker code:

return fetch("" + u.pathname, request);

Let’s assume the asset above is cached via a page rule (which runs before a Worker runs) OR is set to be cached in some other way e.g. via the Worker Cache API.

If the cached version of the above URL does not exist at the edge node, what happens? Does the CF worker running at the edge go back to the origin to fetch the asset?

I know Cloudflare has 160 or so “edge nodes” - but I presume there’s a very slim chance that a cached asset will be at ALL edge nodes, so just wondering - when a worker does a fetch() - what happens in a situation where there the local node has no cached version but another, nearby node does?

Hi Amit,

There are two distinct concepts at play here: cached versus cacheable.

  • cached: a response is resident in a Cloudflare datacenter’s cache
  • cacheable: the cache will be checked before a request is forwarded to the origin, and the origin’s response will be stored in the cache (subject to the response’s Cache-Control header and other rules)

Cacheability is determined by file extension, but can be overridden by page rules (as in your example above) and fetch() options like fetch(url, { cf: { cacheTtl: 600 } }).

The Cache API can change whether a resource is cached, but cannot change its cacheability.

This means that you could caches.default.put() an uncacheable resource, but a subsequent fetch() to the same URL will ignore the cache for that resource and go straight to the origin. You could, however, retrieve it with caches.default.match().

A subrequest from fetch() will go to the origin, unless you have Tiered Caching, in which case it will check the next tier, and so on, until it hits the origin.