Cache using fetch
Determine how to cache a resource by setting TTLs, custom cache keys, and cache headers in a fetch request.
Setting the cache level to Cache Everything will override the default cacheability of the asset. For time-to-live (TTL), Cloudflare will still rely on headers set by the origin.
A request’s cache key is what determines if two requests are the same for caching purposes. If a request has the same cache key as some previous request, then Cloudflare can serve the same cached response for both. For more about cache keys, refer to the Create custom cache keys documentation.
Normally, Cloudflare computes the cache key for a request based on the request’s URL. Sometimes, though, you may like different URLs to be treated as if they were the same for caching purposes. For example, if your website content is hosted from both Amazon S3 and Google Cloud Storage - you have the same content in both places, and you can use a Worker to randomly balance between the two. However, you do not want to end up caching two copies of your content. You could utilize custom cache keys to cache based on the original request URL rather than the subrequest URL:
Workers operating on behalf of different zones cannot affect each other’s cache. You can only override cache keys when making requests within your own zone (in the above example event.request.url
was the key stored), or requests to hosts that are not on Cloudflare. When making a request to another Cloudflare zone (for example, belonging to a different Cloudflare customer), that zone fully controls how its own content is cached within Cloudflare; you cannot override it.
This option is a version of the cacheTtl
feature which chooses a TTL based on the response’s status code and does not automatically set cacheEverything: true
. If the response to this request has a status code that matches, Cloudflare will cache for the instructed time, and override cache directives sent by the origin. You can review details on the cacheTtl
feature on the Request page.
Using custom cache keys and overrides based on response code, you can write a Worker that sets the TTL based on the response status code from origin, and request file type.
The following example demonstrates how you might use this to cache requests for streaming media assets:
The cache
mode can be set in fetch
options.
Currently Workers only support the no-store
mode for controlling the cache.
When no-store
is supplied the cache is bypassed on the way to the origin and the request is not cacheable.