INTEGRITY Cloudflare Docs

Customize cache behavior with Workers

You can use Workers to customize cache behavior on Cloudflare's network. Workers run as middleware in the request lifecycle — a single Worker handles both the request and response phases. When a request arrives, it hits the Worker before the cache is checked. The Worker can modify the incoming request (for example, rewrite the URL or add headers), then call fetch() to continue the request through the cache. When the response comes back — whether from cache or from the origin server — the Worker can also modify the response before it is sent to the visitor.

The diagram below illustrates a common interaction flow between Workers and Cache.

Workers and cache flow example flow diagram.
  1. A visitor (a) requests a URL, and this request is directed to a Worker. The Worker can then interact with the request, either requesting the content from the origin server using (b) fetch() or sending a (f) response back to the visitor.
  2. If the content is cached, the cache sends a (e) response back to the Worker, which can modify the response before sending a (f) response back to the visitor.
  3. When using cache rules with Workers, the cache rule must match the properties of the URL in the fetch() (b) request — such as headers, hostname, or URL path — not the original visitor URL/host (a). Otherwise, the rule will not be applied.

Here are a few examples of how Workers can be used to customize cache behavior:

You can also use Snippets for lightweight modifications like header changes, redirects, and JWT validation without deploying a full Worker script. Snippets are included at no additional cost on all paid plans but have stricter resource limits (5 ms execution time, 32 KB package size).

Cache features in Workers

Workers offer two ways to interact with the cache. Use fetch() when your Worker makes subrequests to an origin. Use the Cache API when your Worker generates responses without a backend origin.

To understand more about how Cache and Workers interact, refer to Cache in Workers.