你的 Worker 可随时使用 purge() 删除自身缓存的响应,或使用 invalidate() 将其标记为过期,以便下次请求时缓存向 Worker 重新验证。当数据发生变化且提供新值比继续提供缓存响应带来的性能收益更重要时,两者都很有用——例如,在内容更新、用户操作或来自上游系统的 webhook 之后。
由于 Workers Caching 是你的 Worker 的缓存,清除和失效操作的作用域限于拥有该缓存的 Worker。在 Worker 内部,两者都进一步限定为调用 purge() 或 invalidate() 的入口点(entrypoint)。一个 Worker 无法访问另一个 Worker 的缓存,一个入口点无法访问另一个入口点的缓存,任何 zone 级别的清除(通过仪表板、API 或 Terraform)都不会影响 Workers Caching 的内容。
在 Worker 内部有两种等效方式触发清除:
ctx.cache.purge(...)— 在每个处理程序传入的执行上下文上可用。当你已在作用域内持有ctx时使用。cache.purge(...)— 从cloudflare:workers导入。当你希望在不接收ctx的代码中调用 purge 时使用——例如,在多个处理程序间共享的工具模块,或未将执行上下文贯穿其内部的框架适配器。
两种形式调用同一 API,行为完全一致。选择在你的代码中更易读的一种即可。
import { cache } from "cloudflare:workers";
export default {
async fetch(request, env, ctx) {
// Using the module import — no need to thread ctx through helper functions.
await cache.purge({ tags: ["blog-posts"] });
// Equivalent, using ctx directly:
// await ctx.cache.purge({ tags: ["blog-posts"] });
return new Response("Purged", { status: 200 });
},
};import { cache } from "cloudflare:workers";
export default {
async fetch(request, env, ctx): Promise<Response> {
// Using the module import — no need to thread ctx through helper functions.
await cache.purge({ tags: ["blog-posts"] });
// Equivalent, using ctx directly:
// await ctx.cache.purge({ tags: ["blog-posts"] });
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;本页其余示例大多使用 ctx.cache.purge(...),因为这些示例已在作用域内持有 ctx。如果你偏好导入形式,可替换为 cache.purge(...)——其余无需改动。
purge() 可单独接受 purgeEverything: true,或接受 tags 和 pathPrefixes 中的一个或两个:
| 字段 | 清除内容 | 作用域 |
|---|---|---|
tags |
通过 Cache-Tag 标有给定值之一的每个缓存响应。 |
按入口点 |
pathPrefixes |
请求路径以给定前缀之一开头的每个缓存响应。 | 按入口点 |
purgeEverything |
调用 purge() 的入口点的每个缓存响应。 |
按入口点 |
purgeEverything 是互斥的——如需组合,可在单次调用中同时使用 tags 和 pathPrefixes,但不要与 purgeEverything 一起传递其中任一参数。
三种模式均限定为调用 purge() 的入口点。来自 PublicAPI 的清除不会影响 AdminAPI 存储的缓存响应,即使它们共享标签名或路径前缀。若要在 Worker 的每个入口点上清除,需从每个入口点调用 purge()。
返回的 promise 会解析为结果对象,你可检查以确认成功或处理失败——参见返回值。
在任意会修改数据的处理程序末尾调用 ctx.cache.purge(),在写入后执行清除:
export default {
async fetch(request, env, ctx) {
if (request.method === "POST") {
const body = await request.json();
// Mutate your data source (D1, KV, an origin, and so on), then purge
// every cached response tagged for this post.
await ctx.cache.purge({
tags: [`post-${body.postId}`, "post-list"],
});
return new Response("Updated", { status: 200 });
}
// Handle cacheable reads here.
return new Response("Hello", {
headers: { "Cache-Control": "public, max-age=3600" },
});
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
if (request.method === "POST") {
const body = await request.json<{ postId: string }>();
// Mutate your data source (D1, KV, an origin, and so on), then purge
// every cached response tagged for this post.
await ctx.cache.purge({
tags: [`post-${body.postId}`, "post-list"],
});
return new Response("Updated", { status: 200 });
}
// Handle cacheable reads here.
return new Response("Hello", {
headers: { "Cache-Control": "public, max-age=3600" },
});
},
} satisfies ExportedHandler;可在单次调用中组合多个字段。例如,purge({ tags: ["blog-posts"], pathPrefixes: ["/blog/"] }) 会清除任一 标签或路径前缀匹配的所有内容——字段取并集,而非交集。当一次逻辑更改会影响按多种方案标记的响应时使用。
export default {
async fetch(request, env, ctx) {
// Combined call: purges everything tagged "blog-posts" AND
// everything under /blog/ in a single round-trip.
await ctx.cache.purge({
tags: ["blog-posts"],
pathPrefixes: ["/blog/"],
});
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
// Combined call: purges everything tagged "blog-posts" AND
// everything under /blog/ in a single round-trip.
await ctx.cache.purge({
tags: ["blog-posts"],
pathPrefixes: ["/blog/"],
});
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;标签通过 Cache-Tag 响应头附加到响应上,之后按名称清除。这是最灵活、最常用的清除方式。
export default {
async fetch(request) {
const url = new URL(request.url);
const postId = url.pathname.split("/").pop() ?? "unknown";
const body = { id: postId, title: `Post ${postId}` };
return new Response(JSON.stringify(body), {
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=3600",
"Cache-Tag": `post,post-${postId},blog`,
},
});
},
};export default {
async fetch(request): Promise<Response> {
const url = new URL(request.url);
const postId = url.pathname.split("/").pop() ?? "unknown";
const body = { id: postId, title: `Post ${postId}` };
return new Response(JSON.stringify(body), {
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=3600",
"Cache-Tag": `post,post-${postId},blog`,
},
});
},
} satisfies ExportedHandler;Cache-Tag 头值为逗号分隔的标签列表。Cloudflare 在将响应返回给客户端之前会移除此头。
标签值必须是可打印 ASCII(无空格、无 Unicode),每个标签最长 1024 个字符,单个响应最多可携带 1000 个标签。清除时的标签匹配不区分大小写,因此 Foo 与 foo 会清除同一组响应。无效标签在存储时会被静默丢弃——响应仍会缓存,并保留其余有效标签。完整列表请参阅缓存标签限制。
export default {
async fetch(request, env, ctx) {
const postId = new URL(request.url).searchParams.get("id");
if (!postId) return new Response("Missing id", { status: 400 });
await ctx.cache.purge({ tags: [`post-${postId}`] });
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
const postId = new URL(request.url).searchParams.get("id");
if (!postId) return new Response("Missing id", { status: 400 });
await ctx.cache.purge({ tags: [`post-${postId}`] });
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;标签限定为调用 purge() 的入口点。应用于两个不同入口点响应的名为 user-42 的标签不会 被单次 purge({ tags: ["user-42"] }) 调用清除——仅影响发起调用的入口点。若需在多个入口点清除同一标签,需从每个入口点调用 purge(),或将清除调用集中到一个共享入口点,由该入口点缓存你之后需要清除的所有响应。
若要在一次调用中清除一组相关响应,为每个响应附加表示其所属各层级层次结构的多个标签——有时称为「软标签(soft tags)」:
export default {
async fetch(request) {
const path = new URL(request.url).pathname;
// Build a list of hierarchical tags for the current path.
// A response at /blog/2025/02/hello gets tags for:
// _path:/blog/, _path:/blog/2025/, _path:/blog/2025/02/, _path:/blog/2025/02/hello
const segments = path.split("/").filter(Boolean);
const tags = segments.map(
(_, i) => `_path:/${segments.slice(0, i + 1).join("/")}/`,
);
const body = `<!doctype html><title>${path}</title>`;
return new Response(body, {
headers: {
"Content-Type": "text/html",
"Cache-Control": "public, max-age=3600",
"Cache-Tag": tags.join(","),
},
});
},
};export default {
async fetch(request): Promise<Response> {
const path = new URL(request.url).pathname;
// Build a list of hierarchical tags for the current path.
// A response at /blog/2025/02/hello gets tags for:
// _path:/blog/, _path:/blog/2025/, _path:/blog/2025/02/, _path:/blog/2025/02/hello
const segments = path.split("/").filter(Boolean);
const tags = segments.map(
(_, i) => `_path:/${segments.slice(0, i + 1).join("/")}/`,
);
const body = `<!doctype html><title>${path}</title>`;
return new Response(body, {
headers: {
"Content-Type": "text/html",
"Cache-Control": "public, max-age=3600",
"Cache-Tag": tags.join(","),
},
});
},
} satisfies ExportedHandler;清除标签 _path:/blog/2025/ 后,会删除 URL 以 /blog/2025/ 开头的每个缓存响应。
有关标签数量、长度和字符集的限制,请参阅缓存标签限制。
默认情况下,Workers Caching 按 Worker 版本划分缓存,因此每次部署都会从冷缓存开始,无需按版本清除。本节仅在你启用了 cache.cross_version_cache 以在版本间共享缓存响应时适用。此时,版本 A 写入的响应在部署版本 B 后仍可能被提供,你可能希望清除特定版本写入的条目——例如,回滚之后。为此,为每个响应附加产生它的版本标签,之后清除该标签。
在 Wrangler 配置中添加版本元数据绑定(binding):
{
"name": "my-worker",
"main": "src/index.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-11-20",
"cache": { "enabled": true, "cross_version_cache": true },
"version_metadata": { "binding": "CF_VERSION_METADATA" },
}name = "my-worker"
main = "src/index.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-20"
[cache]
enabled = true
cross_version_cache = true
[version_metadata]
binding = "CF_VERSION_METADATA"然后将版本 ID 前置到标签中:
export default {
async fetch(request, env, ctx) {
const { id: versionId } = env.CF_VERSION_METADATA;
const postId = new URL(request.url).pathname.split("/").pop() ?? "unknown";
return new Response(JSON.stringify({ id: postId }), {
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=3600",
// Include the version ID as a tag so you can purge by version later.
"Cache-Tag": `post,post-${postId},v:${versionId}`,
},
});
},
};interface Env {
CF_VERSION_METADATA: WorkerVersionMetadata;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
const { id: versionId } = env.CF_VERSION_METADATA;
const postId = new URL(request.url).pathname.split("/").pop() ?? "unknown";
return new Response(JSON.stringify({ id: postId }), {
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=3600",
// Include the version ID as a tag so you can purge by version later.
"Cache-Tag": `post,post-${postId},v:${versionId}`,
},
});
},
} satisfies ExportedHandler<Env>;当你希望清除特定版本写入的所有内容——例如,回滚之后——清除该版本标签:
export default {
async fetch(request, env, ctx) {
const versionId = new URL(request.url).searchParams.get("version");
if (!versionId) return new Response("Missing version", { status: 400 });
await ctx.cache.purge({ tags: [`v:${versionId}`] });
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
const versionId = new URL(request.url).searchParams.get("version");
if (!versionId) return new Response("Missing version", { status: 400 });
await ctx.cache.purge({ tags: [`v:${versionId}`] });
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;pathPrefixes 会清除请求路径 以给定前缀之一开头的每个缓存响应:
export default {
async fetch(request, env, ctx) {
// Purge everything under /blog/2025/ for the current entrypoint.
await ctx.cache.purge({
pathPrefixes: ["/blog/2025/"],
});
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
// Purge everything under /blog/2025/ for the current entrypoint.
await ctx.cache.purge({
pathPrefixes: ["/blog/2025/"],
});
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;pathPrefixes 中的条目是路径,而非完整 URL。前缀不得包含 scheme、主机、查询字符串或 fragment——传入类似 https://example.com/blog/ 的内容是无效输入,而非仅匹配失败的前缀。前导斜杠可选(/images 与 images 处理方式相同),但为清晰起见建议使用。
pathPrefixes 限定为发起清除调用的入口点。来自 PublicAPI 的 purge({ pathPrefixes: ["/blog/"] }) 不会影响 AdminAPI 存储的缓存响应,即使其路径也以 /blog/ 开头。
没有专门的「按 URL 清除」模式。若要清除单个缓存 URL,将其路径作为单元素 pathPrefixes 数组传入:
export default {
async fetch(request, env, ctx) {
// Purge the cached response for exactly /blog/2026/hello-world.
await ctx.cache.purge({
pathPrefixes: ["/blog/2026/hello-world"],
});
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
// Purge the cached response for exactly /blog/2026/hello-world.
await ctx.cache.purge({
pathPrefixes: ["/blog/2026/hello-world"],
});
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;由于 pathPrefixes 按请求路径开头匹配,传入完整路径仅匹配该路径——以及恰好扩展它的路径(例如 /blog/2026/hello-world-2)。若需要精确匹配语义且无过度清除风险,请改用标签。
删除调用入口点存储的每个缓存响应:
export default {
async fetch(request, env, ctx) {
await ctx.cache.purge({ purgeEverything: true });
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
await ctx.cache.purge({ purgeEverything: true });
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;请谨慎使用。清除全部会导致后续所有请求缓存未命中,直到重新填充,这会暂时增加 Worker 及其调用的上游服务的负载。
invalidate() 是 purge() 的软对应方法。它接受相同选项(tags、pathPrefixes 或 purgeEverything),以相同方式选择缓存响应,遵循相同的按入口点作用域,并解析为相同的结果对象。你可以将其作为 ctx.cache.invalidate(...) 调用,或作为从 cloudflare:workers 导入的 cache.invalidate(...) 调用——与 purge() 的两种形式相同。
两种方法对匹配的缓存响应的处理不同:
| 方法 | 匹配的缓存响应 | 下一次匹配请求 |
|---|---|---|
purge() |
删除 | 缓存未命中。Worker 运行并生成新响应。 |
invalidate() |
保留,但标记为过期 | 重新验证。缓存向 Worker 发送条件请求。 |
要重新验证已失效的响应,缓存会使用与该响应一起存储的验证器构建条件请求标头并调用 Worker——例如,携带缓存 ETag 的 If-None-Match,或携带缓存 Last-Modified 的 If-Modified-Since。如果 Worker 返回 304 Not Modified,缓存会保留已存储的正文并以 Cf-Cache-Status: REVALIDATED 提供,之后的请求再次成为 HIT。如果 Worker 改为返回完整的 200 响应,该响应会替换缓存中的响应。
因此,仅当 Worker 发出验证器(ETag 或 Last-Modified)并以 304 响应匹配的条件请求时,invalidate() 才会节省工作。当一次调用覆盖许多响应但其中只有部分发生变化时,这最有帮助。每个未更改的响应只需一次验证器检查,而不是完整重新生成。如果 Worker 不发出验证器,或总是返回完整响应,则每次重新验证都会重新生成响应,invalidate() 相比 purge() 不会节省工作。
在此示例中,目录同步会写入每个产品,然后使所有产品页面失效。每个产品带有仅在其数据变化时才变化的修订号,Worker 将该修订号用作 ETag。未更改产品的页面以 304 重新验证,因此 Worker 仅渲染发生变化的页面:
function renderProductPage(product) {
// Stands in for the expensive rendering work that a 304 response skips.
return `<!doctype html><title>${product.name}</title>`;
}
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/sync") {
// Write every product from the upstream catalog. Many are unchanged.
const products = await request.json();
await Promise.all(
products.map((product) =>
env.PRODUCTS.put(product.id, JSON.stringify(product)),
),
);
// Mark every cached product page stale instead of deleting it.
await ctx.cache.invalidate({ tags: ["products"] });
return new Response("Synced", { status: 200 });
}
const id = url.pathname.split("/").pop() ?? "";
const product = await env.PRODUCTS.get(id, "json");
if (!product) return new Response("Not found", { status: 404 });
const etag = `"${product.revision}"`;
const headers = {
"Cache-Control": "public, max-age=86400",
"Cache-Tag": `products,product-${id}`,
ETag: etag,
};
// To revalidate an invalidated response, the cache sends the stored ETag
// in If-None-Match. If the product has not changed, answer 304 and skip
// rendering. The cache keeps the body it already has.
if (request.headers.get("If-None-Match") === etag) {
return new Response(null, { status: 304, headers });
}
return new Response(renderProductPage(product), {
headers: { ...headers, "Content-Type": "text/html" },
});
},
};interface Env {
PRODUCTS: KVNamespace;
}
interface Product {
id: string;
name: string;
// Changes only when the product data changes.
revision: string;
}
function renderProductPage(product: Product): string {
// Stands in for the expensive rendering work that a 304 response skips.
return `<!doctype html><title>${product.name}</title>`;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/sync") {
// Write every product from the upstream catalog. Many are unchanged.
const products = await request.json<Product[]>();
await Promise.all(
products.map((product) =>
env.PRODUCTS.put(product.id, JSON.stringify(product)),
),
);
// Mark every cached product page stale instead of deleting it.
await ctx.cache.invalidate({ tags: ["products"] });
return new Response("Synced", { status: 200 });
}
const id = url.pathname.split("/").pop() ?? "";
const product = await env.PRODUCTS.get<Product>(id, "json");
if (!product) return new Response("Not found", { status: 404 });
const etag = `"${product.revision}"`;
const headers = {
"Cache-Control": "public, max-age=86400",
"Cache-Tag": `products,product-${id}`,
ETag: etag,
};
// To revalidate an invalidated response, the cache sends the stored ETag
// in If-None-Match. If the product has not changed, answer 304 and skip
// rendering. The cache keeps the body it already has.
if (request.headers.get("If-None-Match") === etag) {
return new Response(null, { status: 304, headers });
}
return new Response(renderProductPage(product), {
headers: { ...headers, "Content-Type": "text/html" },
});
},
} satisfies ExportedHandler<Env>;由 ctx.cache.purge() 触发的清除使用 Cloudflare 的 Instant Purge 基础设施,并以与 zone 级别清除相同的保证在全球范围内传播。
purge() 和 invalidate() 解析为相同的结果对象。检查 success 以确认请求已被接受;若未成功,检查 errors:
export default {
async fetch(request, env, ctx) {
const result = await ctx.cache.purge({ tags: ["blog-posts"] });
if (!result.success) {
console.error("Cache purge failed", result.errors);
return new Response("Purge failed", { status: 500 });
}
return new Response("Purged", { status: 200 });
},
};export default {
async fetch(request, env, ctx): Promise<Response> {
const result = await ctx.cache.purge({ tags: ["blog-posts"] });
if (!result.success) {
console.error("Cache purge failed", result.errors);
return new Response("Purge failed", { status: 500 });
}
return new Response("Purged", { status: 200 });
},
} satisfies ExportedHandler;失败时,errors 中的每个错误包含数字 code 和可读 message,你可记录或返回给调用方。
purge() 使用与 Cloudflare zone 清除 API 相同的速率限制系统。但是,由于 Workers Caching 与 Worker 而非 zone 关联,Workers Cache 始终使用可用性与限制中描述的 Free 套餐限制,无论你的账户或 zone 套餐如何。当清除被限流时,success 为 false,errors 包含描述拒绝原因的错误条目。