Skip to content
GitHubXDiscordRSS

Cache

Learn how to enable Workers Cache in Alchemy to serve cached responses from Cloudflare's edge without invoking your Worker.

Workers Cache is a Worker-owned edge cache that sits in front of your Worker. When enabled, Cloudflare checks the cache before invoking your Worker and serves matching responses directly from the edge — reducing latency and CPU time. It applies to all fetch() invocations: eyeball requests, service binding calls, and loopback fetches.

Enable the cache with the cache property on a Worker.

import { Worker } from "alchemy/cloudflare";
const worker = await Worker("my-worker", {
entrypoint: "./src/worker.ts",
cache: true,
});

The Worker’s code is the configuration surface — standard HTTP response headers decide what gets cached and for how long.

src/worker.ts
export default {
async fetch(request: Request): Promise<Response> {
return Response.json(
{ hello: "world" },
{
headers: {
"Cache-Control": "public, max-age=300, stale-while-revalidate=3600",
"Cache-Tag": "products",
},
},
);
},
};

Responses with a cacheable Cache-Control header are stored at the edge; subsequent requests for the same URL are served from cache without invoking the Worker.

Purge cached responses programmatically with ctx.cache.purge() — by Cache-Tag, path prefix, or entirely.

src/worker.ts
export default {
async fetch(request: Request, env: unknown, ctx: ExecutionContext): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/invalidate") {
await ctx.cache.purge({ tags: ["products"] });
return new Response("purged");
}
// ...
},
};

By default the cache is scoped to a single Worker version, so every deployment starts cold. Opt into sharing cached responses across versions when they are version-agnostic:

import { Worker } from "alchemy/cloudflare";
const worker = await Worker("my-worker", {
entrypoint: "./src/worker.ts",
cache: {
enabled: true,
crossVersionCache: true,
},
});
  • enabled — toggles the read-through cache (cache: true is shorthand for { enabled: true })
  • crossVersionCache — shares cached responses across Worker versions