workers-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseYour knowledge of Cloudflare Workers APIs, types, and configuration may be outdated. Prefer retrieval over pre-training for any Workers code task — writing or reviewing.
你对Cloudflare Workers API、类型和配置的认知可能已过时。在任何Workers代码任务(编写或审查)中,优先通过检索获取最新信息,而非依赖预训练知识。
Retrieval Sources
检索来源
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 | Canonical rules, patterns, anti-patterns |
| Workers types | See | API signatures, handler types, binding types |
| Wrangler config schema | | Config fields, binding shapes, allowed values |
| Cloudflare docs | Search tool or | API reference, compatibility dates/flags |
在编写或审查Workers代码前,获取最新版本内容。不要依赖内置知识来处理API签名、配置字段或绑定结构。
| 来源 | 检索方式 | 适用场景 |
|---|---|---|
| Workers最佳实践 | 获取 | 标准规则、模式、反模式 |
| Workers类型 | 查看 | API签名、处理器类型、绑定类型 |
| Wrangler配置 schema | | 配置字段、绑定结构、允许值 |
| Cloudflare文档 | 使用搜索工具或访问 | API参考、兼容性日期/标识 |
FIRST: Fetch Latest References
第一步:获取最新参考资料
Before reviewing or writing Workers code, retrieve the current best practices page and relevant type definitions. If the project's has an older version, prefer the latest published version.
node_modulesbash
undefined在审查或编写Workers代码前,先获取当前的最佳实践页面和相关类型定义。如果项目的中是旧版本,优先使用最新发布的版本。
node_modulesbash
undefinedFetch latest workers types
获取最新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
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
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
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
类型文件路径:/tmp/workers-types-latest/package/index.d.ts
undefinedundefinedReference Documentation
参考文档
- — all best practice rules with code examples and anti-patterns
references/rules.md - — type validation, config validation, binding access patterns, review process
references/review.md
- — 包含所有最佳实践规则及代码示例和反模式
references/rules.md - — 类型验证、配置验证、绑定访问模式、审查流程
references/review.md
Rules Quick Reference
规则速查
Configuration
配置
| Rule | Summary |
|---|---|
| Compatibility date | Set |
| nodejs_compat | Enable the |
| wrangler types | Run |
| Secrets | Use |
| wrangler.jsonc | Use JSONC config for non-secret settings — newer features are JSON-only |
| 规则 | 概述 |
|---|---|
| Compatibility date | 新项目将 |
| nodejs_compat | 启用 |
| wrangler types | 运行 |
| 密钥 | 使用 |
| wrangler.jsonc | 对非敏感设置使用JSONC格式配置——新特性仅支持JSON格式 |
Request & Response Handling
请求与响应处理
| Rule | Summary |
|---|---|
| Streaming | Stream large/unknown payloads — never |
| waitUntil | Use |
| 规则 | 概述 |
|---|---|
| 流处理 | 对大体积/未知大小的负载使用流处理——切勿在无限制数据上执行 |
| waitUntil | 使用 |
Architecture
架构
| 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 |
| 规则 | 概述 |
|---|---|
| 优先使用绑定而非REST | 使用进程内绑定(KV、R2、D1、Queues)——而非Cloudflare REST API |
| 队列与工作流 | 将异步/后台工作移出关键路径 |
| 服务绑定 | Worker间调用使用服务绑定——而非公开HTTP调用 |
| Hyperdrive | 外部PostgreSQL/MySQL连接始终使用Hyperdrive |
Observability
可观测性
| Rule | Summary |
|---|---|
| Logs & Traces | Enable |
| 规则 | 概述 |
|---|---|
| 日志与追踪 | 在配置中启用 |
Code Patterns
代码模式
| Rule | Summary |
|---|---|
| No global request state | Never store request-scoped data in module-level variables |
| Floating promises | Every Promise must be |
| 规则 | 概述 |
|---|---|
| 无全局请求状态 | 切勿在模块级变量中存储请求作用域的数据 |
| 浮动Promise | 每个Promise必须被 |
Security
安全
| Rule | Summary |
|---|---|
| Web Crypto | Use |
| No passThroughOnException | Use explicit try/catch with structured error responses |
| 规则 | 概述 |
|---|---|
| Web Crypto | 使用 |
| 禁止passThroughOnException | 使用显式try/catch并返回结构化错误响应 |
Anti-Patterns to Flag
需要标记的反模式
| Anti-pattern | Why it matters |
|---|---|
| Memory exhaustion — 128 MB limit |
| Hardcoded secrets in source or config | Credential leak via version control |
| Predictable, not cryptographically secure |
Bare | 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 |
| Hides bugs, makes debugging impossible |
Hand-written | Drifts from actual wrangler config bindings |
| Direct string comparison for secret values | Timing side-channel — use |
Destructuring | Loses |
| Defeats type safety for all binding access |
| Hides real type incompatibilities — fix the design |
| Legacy — loses |
| Should be |
| 反模式 | 影响 |
|---|---|
在无限制数据上执行 | 内存耗尽——Workers内存限制为128MB |
| 源码或配置中硬编码密钥 | 凭证通过版本控制泄露 |
使用 | 可预测,不具备密码学安全性 |
未加 | 浮动Promise——结果丢失,错误被吞掉 |
| 使用模块级可变变量存储请求状态 | 请求间数据泄露、状态过期、I/O错误 |
| 在Worker内部调用Cloudflare REST API | 不必要的网络跳转、认证开销、延迟增加 |
将 | 隐藏bug,无法调试 |
手动编写 | 与实际Wrangler配置绑定产生偏差 |
| 直接字符串比较密钥值 | 计时侧信道风险——使用 |
解构 | 丢失 |
在 | 破坏所有绑定访问的类型安全 |
使用 | 隐藏真实的类型不兼容问题——应修复设计 |
对平台基类使用 | 遗留用法——丢失 |
在平台基类内部使用 | 对于继承自DurableObject、WorkerEntrypoint等的类,应使用 |
Review Workflow
审查流程
- Retrieve — fetch latest best practices page, workers types, and wrangler schema
- Read full files — not just diffs; context matters for binding access patterns
- Check types — binding access, handler signatures, no , no unsafe casts (see
any)references/review.md - Check config — compatibility_date, nodejs_compat, observability, secrets, binding-code consistency
- Check patterns — streaming, floating promises, global state, serialization boundaries
- Check security — crypto usage, secret handling, timing-safe comparisons, error handling
- Validate with tools — , lint for
npx tsc --noEmitno-floating-promises - Reference rules — see for each rule's correct pattern
references/rules.md
- 检索 — 获取最新的最佳实践页面、Workers类型和Wrangler schema
- 阅读完整文件 — 不要只看差异;绑定访问模式需要上下文信息
- 检查类型 — 绑定访问、处理器签名、无类型、无不安全类型转换(详见
any)references/review.md - 检查配置 — compatibility_date、nodejs_compat、可观测性、密钥、绑定与代码的一致性
- 检查模式 — 流处理、浮动Promise、全局状态、序列化边界
- 检查安全 — 加密使用、密钥处理、计时安全比较、错误处理
- 工具验证 — 运行,使用lint检查
npx tsc --noEmitno-floating-promises - 参考规则 — 查看获取各规则的正确模式
references/rules.md
Scope
适用范围
This skill covers Workers-specific best practices and code review. For related topics:
- Durable Objects: load the skill
durable-objects - Workflows: see Rules of Workflows
- Wrangler CLI commands: load the skill
wrangler
本技能涵盖Workers专属的最佳实践和代码审查。相关主题请参考:
- Durable Objects:加载技能
durable-objects - Workflows:查看Rules of Workflows
- Wrangler CLI命令:加载技能
wrangler
Principles
原则
- Be certain. Retrieve before flagging. If unsure about an API, config field, or pattern, fetch the docs first.
- Provide evidence. Reference line numbers, tool output, or docs links.
- Focus on what developers will copy. Workers code in examples and docs gets pasted into production.
- Correctness over completeness. A concise example that works beats a comprehensive one with errors.
- 确保准确:标记问题前先检索信息。若对API、配置字段或模式不确定,先获取文档内容。
- 提供依据:引用行号、工具输出或文档链接。
- 聚焦开发者会复制的内容:示例和文档中的Workers代码会被直接复制到生产环境。
- 正确性优先于完整性:一个简洁可运行的示例胜过包含错误的全面示例。