workers-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
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.
你对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.
SourceHow to retrieveUse for
Workers best practicesFetch
https://developers.cloudflare.com/workers/best-practices/workers-best-practices/
Canonical rules, patterns, anti-patterns
Workers typesSee
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 docsSearch tool or
https://developers.cloudflare.com/workers/
API reference, compatibility dates/flags
在编写或审查Workers代码前,获取最新版本内容。不要依赖内置知识来处理API签名、配置字段或绑定结构。
来源检索方式适用场景
Workers最佳实践获取
https://developers.cloudflare.com/workers/best-practices/workers-best-practices/
标准规则、模式、反模式
Workers类型查看
references/review.md
获取检索步骤
API签名、处理器类型、绑定类型
Wrangler配置 schema
node_modules/wrangler/config-schema.json
配置字段、绑定结构、允许值
Cloudflare文档使用搜索工具或访问
https://developers.cloudflare.com/workers/
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
node_modules
has an older version, prefer the latest published version.
bash
undefined
在审查或编写Workers代码前,先获取当前的最佳实践页面和相关类型定义。如果项目的
node_modules
中是旧版本,优先使用最新发布的版本。
bash
undefined

Fetch 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
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

类型文件路径:/tmp/workers-types-latest/package/index.d.ts

undefined
undefined

Reference Documentation

参考文档

  • references/rules.md
    — all best practice rules with code examples and anti-patterns
  • references/review.md
    — type validation, config validation, binding access patterns, review process
  • references/rules.md
    — 包含所有最佳实践规则及代码示例和反模式
  • references/review.md
    — 类型验证、配置验证、绑定访问模式、审查流程

Rules Quick Reference

规则速查

Configuration

配置

RuleSummary
Compatibility dateSet
compatibility_date
to today on new projects; update periodically on existing ones
nodejs_compatEnable the
nodejs_compat
flag — many libraries depend on Node.js built-ins
wrangler typesRun
wrangler types
to generate
Env
— never hand-write binding interfaces
SecretsUse
wrangler secret put
, never hardcode secrets in config or source
wrangler.jsoncUse JSONC config for non-secret settings — newer features are JSON-only
规则概述
Compatibility date新项目将
compatibility_date
设置为当前日期;现有项目定期更新该字段
nodejs_compat启用
nodejs_compat
标识——许多库依赖Node.js内置功能
wrangler types运行
wrangler types
生成
Env
——切勿手动编写绑定接口
密钥使用
wrangler secret put
,切勿在配置或源码中硬编码密钥
wrangler.jsonc对非敏感设置使用JSONC格式配置——新特性仅支持JSON格式

Request & Response Handling

请求与响应处理

RuleSummary
StreamingStream large/unknown payloads — never
await response.text()
on unbounded data
waitUntilUse
ctx.waitUntil()
for post-response work; do not destructure
ctx
规则概述
流处理对大体积/未知大小的负载使用流处理——切勿在无限制数据上执行
await response.text()
waitUntil使用
ctx.waitUntil()
处理响应后的任务;不要解构
ctx

Architecture

架构

RuleSummary
Bindings over RESTUse in-process bindings (KV, R2, D1, Queues) — not the Cloudflare REST API
Queues & WorkflowsMove async/background work off the critical path
Service bindingsUse service bindings for Worker-to-Worker calls — not public HTTP
HyperdriveAlways use Hyperdrive for external PostgreSQL/MySQL connections
规则概述
优先使用绑定而非REST使用进程内绑定(KV、R2、D1、Queues)——而非Cloudflare REST API
队列与工作流将异步/后台工作移出关键路径
服务绑定Worker间调用使用服务绑定——而非公开HTTP调用
Hyperdrive外部PostgreSQL/MySQL连接始终使用Hyperdrive

Observability

可观测性

RuleSummary
Logs & TracesEnable
observability
in config with
head_sampling_rate
; use structured JSON logging
规则概述
日志与追踪在配置中启用
observability
并设置
head_sampling_rate
;使用结构化JSON日志

Code Patterns

代码模式

RuleSummary
No global request stateNever store request-scoped data in module-level variables
Floating promisesEvery Promise must be
await
ed,
return
ed,
void
ed, or passed to
ctx.waitUntil()
规则概述
无全局请求状态切勿在模块级变量中存储请求作用域的数据
浮动Promise每个Promise必须被
await
、
return
、
void
,或传递给
ctx.waitUntil()

Security

安全

RuleSummary
Web CryptoUse
crypto.randomUUID()
/
crypto.getRandomValues()
— never
Math.random()
for security
No passThroughOnExceptionUse explicit try/catch with structured error responses
规则概述
Web Crypto使用
crypto.randomUUID()
/
crypto.getRandomValues()
——切勿用
Math.random()
处理安全相关场景
禁止passThroughOnException使用显式try/catch并返回结构化错误响应

Anti-Patterns to Flag

需要标记的反模式

Anti-patternWhy it matters
await response.text()
on unbounded data
Memory exhaustion — 128 MB limit
Hardcoded secrets in source or configCredential 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 stateCross-request data leaks, stale state, I/O errors
Cloudflare REST API from inside a WorkerUnnecessary network hop, auth overhead, added latency
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 valuesTiming 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.
反模式影响
在无限制数据上执行
await response.text()
内存耗尽——Workers内存限制为128MB
源码或配置中硬编码密钥凭证通过版本控制泄露
使用
Math.random()
生成令牌/ID
可预测,不具备密码学安全性
未加
await
或
waitUntil
的裸
fetch()
浮动Promise——结果丢失,错误被吞掉
使用模块级可变变量存储请求状态请求间数据泄露、状态过期、I/O错误
在Worker内部调用Cloudflare REST API不必要的网络跳转、认证开销、延迟增加
将
ctx.passThroughOnException()
作为错误处理方式
隐藏bug,无法调试
手动编写
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

Review Workflow

审查流程

  1. Retrieve — fetch latest best practices page, workers types, and wrangler schema
  2. Read full files — not just diffs; context matters for binding access patterns
  3. Check types — binding access, handler signatures, no
    any
    , no unsafe casts (see
    references/review.md
    )
  4. Check config — compatibility_date, nodejs_compat, observability, secrets, binding-code consistency
  5. Check patterns — streaming, floating promises, global state, serialization boundaries
  6. Check security — crypto usage, secret handling, timing-safe comparisons, error handling
  7. Validate with tools —
    npx tsc --noEmit
    , lint for
    no-floating-promises
  8. Reference rules — see
    references/rules.md
    for each rule's correct pattern
  1. 检索 — 获取最新的最佳实践页面、Workers类型和Wrangler schema
  2. 阅读完整文件 — 不要只看差异;绑定访问模式需要上下文信息
  3. 检查类型 — 绑定访问、处理器签名、无
    any
    类型、无不安全类型转换(详见
    references/review.md
    )
  4. 检查配置 — compatibility_date、nodejs_compat、可观测性、密钥、绑定与代码的一致性
  5. 检查模式 — 流处理、浮动Promise、全局状态、序列化边界
  6. 检查安全 — 加密使用、密钥处理、计时安全比较、错误处理
  7. 工具验证 — 运行
    npx tsc --noEmit
    ,使用lint检查
    no-floating-promises
  8. 参考规则 — 查看
    references/rules.md
    获取各规则的正确模式

Scope

适用范围

This skill covers Workers-specific best practices and code review. For related topics:
  • Durable Objects: load the
    durable-objects
    skill
  • Workflows: see Rules of Workflows
  • Wrangler CLI commands: load the
    wrangler
    skill
本技能涵盖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代码会被直接复制到生产环境。
  • 正确性优先于完整性:一个简洁可运行的示例胜过包含错误的全面示例。