Skip to content

Programmable cache

Use the Cache API when a Worker can safely reuse a generated or fetched response for later requests. The platform provides the standard caches.default and caches.open() interfaces; there is no resource to create before deployment.

export default {
  async fetch(request, env, ctx) {
    const cache = caches.default;
    const cached = await cache.match(request);
    if (cached) return cached;

    const response = await fetch("https://example.com/data");
    const cacheable = new Response(response.body, response);
    cacheable.headers.set("Cache-Control", "public, max-age=300");
    ctx.waitUntil(cache.put(request, cacheable.clone()));
    return cacheable;
  },
};

Deploy the Worker normally with Wrangler. Cache activity, retained response data, and per-version purge controls appear under Data → Cache in the organization console.

Safety and isolation

Every entry is scoped to the organization, Worker, immutable deployment version, cache namespace, URL, and any declared Vary request headers. A new deployment starts with a cold cache even when its code uses the same cache key. Named caches are isolated from caches.default and from one another.

The service bypasses requests with Authorization, Cookie, or request no-cache/no-store directives. It also refuses to store responses with Set-Cookie, private, no-cache, no-store, Vary: *, or an already-expired TTL. These conservative defaults reduce accidental disclosure; application code should still choose cache keys and response policy deliberately.

Entries are limited to 8 MiB and TTLs are capped at 24 hours. Use object storage for retained files or larger values. The platform meters cache operations and enforces tier limits for response count and retained bytes.

What this does not do

This is programmable caching inside Worker code, not automatic CDN or ingress caching. Access, request protection, routing, and the Worker invocation still run for every request. A cache hit can avoid application or origin work, but it does not bypass the platform security boundary or eliminate the invocation.

cache.put() is asynchronous in most applications. Pass its promise to ctx.waitUntil() so the write may finish after the response is returned. Use cache.delete() for a precise key and the console purge control when an entire Worker version must be invalidated.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close