workers-best-practices by cloudflare/skills
npx skills add https://github.com/cloudflare/skills --skill workers-best-practices您对 Cloudflare Workers API、类型和配置的了解可能已过时。对于任何 Workers 代码任务(编写或审查),优先使用检索而非预训练知识。
在编写或审查 Workers 代码之前,请获取最新版本。不要依赖已内置的知识来了解 API 签名、配置字段或绑定结构。
| 来源 | 如何检索 | 用途 |
|---|---|---|
| Workers 最佳实践 | 获取 https://developers.cloudflare.com/workers/best-practices/workers-best-practices/ | 规范规则、模式、反模式 |
| Workers 类型 | 查看 references/review.md 了解检索步骤 | API 签名、处理器类型、绑定类型 |
| Wrangler 配置模式 | node_modules/wrangler/config-schema.json | 配置字段、绑定结构、允许的值 |
| Cloudflare 文档 |
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
搜索工具或 https://developers.cloudflare.com/workers/ |
| API 参考、兼容性日期/标志 |
在审查或编写 Workers 代码之前,请检索当前的最佳实践页面和相关的类型定义。如果项目的 node_modules 中有旧版本,优先使用最新发布的版本。
# 获取最新的 workers 类型
mkdir -p /tmp/workers-types-latest && \
npm pack @cloudflare/workers-types --pack-destination /tmp/workers-types-latest && \
tar -xzf /tmp/workers-types-latest/cloudflare-workers-types-*.tgz -C /tmp/workers-types-latest
# 类型文件位于 /tmp/workers-types-latest/package/index.d.ts
references/rules.md — 包含代码示例和反模式的所有最佳实践规则references/review.md — 类型验证、配置验证、绑定访问模式、审查流程| 规则 | 摘要 |
|---|---|
| 兼容性日期 | 在新项目上将 compatibility_date 设置为今天;在现有项目上定期更新 |
| nodejs_compat | 启用 nodejs_compat 标志 — 许多库依赖 Node.js 内置模块 |
| wrangler 类型 | 运行 wrangler types 以生成 Env — 切勿手动编写绑定接口 |
| 密钥 | 使用 wrangler secret put,切勿在配置或源代码中硬编码密钥 |
| wrangler.jsonc | 对非机密设置使用 JSONC 配置 — 较新的功能仅支持 JSON |
| 规则 | 摘要 |
|---|---|
| 流式传输 | 流式传输大型/未知负载 — 切勿对无界数据使用 await response.text() |
| waitUntil | 使用 ctx.waitUntil() 处理响应后的工作;不要解构 ctx |
| 规则 | 摘要 |
|---|---|
| 绑定优于 REST | 使用进程内绑定(KV、R2、D1、Queues)— 而非 Cloudflare REST API |
| 队列与工作流 | 将异步/后台工作移出关键路径 |
| 服务绑定 | 使用服务绑定进行 Worker 到 Worker 的调用 — 而非公共 HTTP |
| Hyperdrive | 始终使用 Hyperdrive 进行外部 PostgreSQL/MySQL 连接 |
| 规则 | 摘要 |
|---|---|
| 日志与追踪 | 在配置中启用 observability 并设置 head_sampling_rate;使用结构化 JSON 日志记录 |
| 规则 | 摘要 |
|---|---|
| 无全局请求状态 | 切勿将请求范围的数据存储在模块级变量中 |
| 悬空 Promise | 每个 Promise 都必须被 await、return、void 或传递给 ctx.waitUntil() |
| 规则 | 摘要 |
|---|---|
| Web Crypto | 使用 crypto.randomUUID() / crypto.getRandomValues() — 切勿将 Math.random() 用于安全目的 |
| 不使用 passThroughOnException | 使用显式 try/catch 和结构化错误响应 |
| 反模式 | 为何重要 |
|---|---|
对无界数据使用 await response.text() | 内存耗尽 — 128 MB 限制 |
| 在源代码或配置中硬编码密钥 | 通过版本控制泄露凭据 |
将 Math.random() 用于令牌/ID | 可预测,非加密安全 |
裸 fetch() 没有 await 或 waitUntil | 悬空 Promise — 结果丢失,错误被吞没 |
| 为请求状态使用模块级可变变量 | 跨请求数据泄露、状态陈旧、I/O 错误 |
| 从 Worker 内部调用 Cloudflare REST API | 不必要的网络跳转、身份验证开销、增加延迟 |
使用 ctx.passThroughOnException() 作为错误处理 | 隐藏错误,使调试无法进行 |
手动编写 Env 接口 | 与实际 wrangler 配置绑定不同步 |
| 直接进行字符串比较以检查密钥值 | 时序侧信道攻击 — 使用 crypto.subtle.timingSafeEqual |
解构 ctx(const { waitUntil } = ctx) | 丢失 this 绑定 — 运行时抛出 "Illegal invocation" |
在 Env 或处理器参数上使用 any | 使所有绑定访问的类型安全性失效 |
使用 as unknown as T 双重转换 | 隐藏真实的类型不兼容性 — 修复设计 |
在平台基类上使用 implements(而非 extends) | 遗留问题 — 丢失 this.ctx、this.env。适用于 DurableObject、WorkerEntrypoint、Workflow |
在平台基类内部使用 env.X | 在继承 DurableObject、WorkerEntrypoint 等的类中,应使用 this.env.X |
any、无不安全转换(参见 references/review.md)npx tsc --noEmit,对 no-floating-promises 进行代码检查references/rules.md 了解每个规则的正确模式此技能涵盖 Workers 特定的最佳实践和代码审查。对于相关主题:
durable-objects 技能wrangler 技能每周安装数
1.8K
仓库
GitHub 星标数
609
首次出现
2026年2月12日
安全审计
安装于
codex1.6K
opencode1.6K
gemini-cli1.6K
github-copilot1.6K
amp1.6K
kimi-cli1.6K
Your knowledge of Cloudflare Workers APIs, types, and configuration may be outdated. Prefer retrieval over pre-training for any Workers code task — writing or reviewing.
Fetch the latest versions before writing or reviewing Workers code. Do not rely on baked-in knowledge for API signatures, config fields, or binding shapes.
| Source | How to retrieve | Use for |
|---|---|---|
| Workers best practices | Fetch https://developers.cloudflare.com/workers/best-practices/workers-best-practices/ | Canonical rules, patterns, anti-patterns |
| Workers types | See references/review.md for retrieval steps | API signatures, handler types, binding types |
| Wrangler config schema | node_modules/wrangler/config-schema.json | Config fields, binding shapes, allowed values |
| Cloudflare docs | Search tool or https://developers.cloudflare.com/workers/ | API reference, compatibility dates/flags |
Before reviewing or writing Workers code, retrieve the current best practices page and relevant type definitions. If the project's node_modules has an older version, prefer the latest published version.
# Fetch latest workers types
mkdir -p /tmp/workers-types-latest && \
npm pack @cloudflare/workers-types --pack-destination /tmp/workers-types-latest && \
tar -xzf /tmp/workers-types-latest/cloudflare-workers-types-*.tgz -C /tmp/workers-types-latest
# Types at /tmp/workers-types-latest/package/index.d.ts
references/rules.md — all best practice rules with code examples and anti-patternsreferences/review.md — type validation, config validation, binding access patterns, review process| Rule | Summary |
|---|---|
| Compatibility date | Set compatibility_date to today on new projects; update periodically on existing ones |
| nodejs_compat | Enable the nodejs_compat flag — many libraries depend on Node.js built-ins |
| wrangler types | Run wrangler types to generate Env — never hand-write binding interfaces |
| Secrets | Use wrangler secret put, never hardcode secrets in config or source |
| wrangler.jsonc | Use JSONC config for non-secret settings — newer features are JSON-only |
| Rule | Summary |
|---|---|
| Streaming | Stream large/unknown payloads — never await response.text() on unbounded data |
| waitUntil | Use ctx.waitUntil() for post-response work; do not destructure ctx |
| Rule | Summary |
|---|---|
| Bindings over REST | Use in-process bindings (KV, R2, D1, Queues) — not the Cloudflare REST API |
| Queues & Workflows | Move async/background work off the critical path |
| Service bindings | Use service bindings for Worker-to-Worker calls — not public HTTP |
| Hyperdrive | Always use Hyperdrive for external PostgreSQL/MySQL connections |
| Rule | Summary |
|---|---|
| Logs & Traces | Enable observability in config with head_sampling_rate; use structured JSON logging |
| Rule | Summary |
|---|---|
| No global request state | Never store request-scoped data in module-level variables |
| Floating promises | Every Promise must be awaited, returned, voided, or passed to ctx.waitUntil() |
| Rule | Summary |
|---|---|
| Web Crypto | Use crypto.randomUUID() / crypto.getRandomValues() — never Math.random() for security |
| No passThroughOnException | Use explicit try/catch with structured error responses |
| Anti-pattern | Why it matters |
|---|---|
await response.text() on unbounded data | Memory exhaustion — 128 MB limit |
| Hardcoded secrets in source or config | Credential leak via version control |
Math.random() for tokens/IDs | Predictable, not cryptographically secure |
Bare fetch() without await or waitUntil | Floating promise — dropped result, swallowed error |
| Module-level mutable variables for request state | Cross-request data leaks, stale state, I/O errors |
| Cloudflare REST API from inside a Worker | Unnecessary network hop, auth overhead, added latency |
any, no unsafe casts (see references/review.md)npx tsc --noEmit, lint for no-floating-promisesreferences/rules.md for each rule's correct patternThis skill covers Workers-specific best practices and code review. For related topics:
durable-objects skillwrangler skillWeekly Installs
1.8K
Repository
GitHub Stars
609
First Seen
Feb 12, 2026
Security Audits
Gen Agent Trust HubWarnSocketPassSnykPass
Installed on
codex1.6K
opencode1.6K
gemini-cli1.6K
github-copilot1.6K
amp1.6K
kimi-cli1.6K
99,500 周安装
ctx.passThroughOnException() as error handling | Hides bugs, makes debugging impossible |
Hand-written Env interface | Drifts from actual wrangler config bindings |
| Direct string comparison for secret values | Timing side-channel — use crypto.subtle.timingSafeEqual |
Destructuring ctx (const { waitUntil } = ctx) | Loses this binding — throws "Illegal invocation" at runtime |
any on Env or handler params | Defeats type safety for all binding access |
as unknown as T double-cast | Hides real type incompatibilities — fix the design |
implements on platform base classes (instead of extends) | Legacy — loses this.ctx, this.env. Applies to DurableObject, WorkerEntrypoint, Workflow |
env.X inside platform base class | Should be this.env.X in classes extending DurableObject, WorkerEntrypoint, etc. |