workers-best-practices

作者: Cloudflare

审查并根据生产最佳实践对Cloudflare Workers代码进行审核。在编写新的Workers、审查Worker代码、配置wrangler.jsonc或检查常见的Workers反模式(流式处理、浮动Promise、全局状态、机密、绑定、可观测性)时加载。倾向于从Cloudflare文档中检索信息,而非依赖预训练知识。

npx skills add https://github.com/cloudflare/skills --skill workers-best-practices

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.

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 stepsAPI signatures, handler types, binding types
Wrangler config schemanode_modules/wrangler/config-schema.jsonConfig fields, binding shapes, allowed values
Cloudflare docsSearch tool or https://developers.cloudflare.com/workers/API reference, compatibility dates/flags

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.

# 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

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

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

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

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

Observability

RuleSummary
Logs & TracesEnable observability in config with head_sampling_rate; use structured JSON logging

Code Patterns

RuleSummary
No global request stateNever store request-scoped data in module-level variables
Floating promisesEvery Promise must be awaited, returned, voided, or passed to ctx.waitUntil()

Security

RuleSummary
Web CryptoUse crypto.randomUUID() / crypto.getRandomValues() — never Math.random() for security
No passThroughOnExceptionUse explicit try/catch with structured error responses

Anti-Patterns to Flag

Anti-patternWhy it matters
await response.text() on unbounded dataMemory exhaustion — 128 MB limit
Hardcoded secrets in source or configCredential leak via version control
Math.random() for tokens/IDsPredictable, not cryptographically secure
Bare fetch() without await or waitUntilFloating 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 handlingHides bugs, makes debugging impossible
Hand-written Env interfaceDrifts 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 paramsDefeats type safety for all binding access
as unknown as T double-castHides 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 classShould be this.env.X in classes extending DurableObject, WorkerEntrypoint, etc.

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 toolsnpx tsc --noEmit, lint for no-floating-promises
  8. Reference rules — see references/rules.md for each rule's correct pattern

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

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.

来自 Cloudflare 的更多技能

agents-sdk
Cloudflare
在Cloudflare Workers上使用Agents SDK构建AI代理。创建有状态代理、持久化工作流、实时WebSocket应用、定时任务、MCP服务器或聊天应用时加载。涵盖Agent类、状态管理、可调用RPC、Workflows集成及React钩子。
official
building-ai-agent-on-cloudflare
Cloudflare
基于Cloudflare构建AI智能体,使用Agents SDK实现状态管理、实时WebSocket、定时任务、工具集成及聊天功能。生成可直接部署到Workers的生产级智能体代码。 适用场景:用户需要“构建智能体”、“AI智能体”、“聊天智能体”、“有状态智能体”,提及“Agents SDK”,需要“实时AI”、“WebSocket AI”,或询问智能体“状态管理”、“定时任务”、“工具调用”。
developmentofficial
building-mcp-server-on-cloudflare
Cloudflare
在 Cloudflare Workers 上构建远程 MCP(模型上下文协议)服务器,支持工具、OAuth 认证和生产部署。生成服务器代码、配置认证提供者并部署到 Workers。 使用场景:用户想要“构建 MCP 服务器”、“创建 MCP 工具”、“远程 MCP”、“部署 MCP”、添加“MCP 的 OAuth”,或提及 Cloudflare 上的模型上下文协议。也会在“MCP 认证”或“MCP 部署”时触发。
developmentofficial
cloudflare
Cloudflare
全面的Cloudflare平台技能,涵盖Workers、Pages、存储(KV、D1、R2)、AI(Workers AI、Vectorize、Agents SDK)、网络(Tunnel、Spectrum)、安全(WAF、DDoS)以及基础设施即代码(Terraform、Pulumi)。适用于任何Cloudflare开发任务。
official
durable-objects
Cloudflare
创建和审查Cloudflare Durable Objects。用于构建有状态协调(聊天室、多玩家游戏、预订系统)、实现RPC方法、SQLite存储、警报、WebSocket,或审查DO代码以遵循最佳实践。涵盖Workers集成、wrangler配置以及使用Vitest进行测试。
official
sandbox-sdk
Cloudflare
构建沙盒化应用程序以实现安全代码执行。在构建AI代码执行、代码解释器、CI/CD系统、交互式开发环境或执行不受信任的代码时加载。涵盖Sandbox SDK生命周期、命令、文件、代码解释器和预览URL。
official
web-perf
Cloudflare
使用Chrome DevTools MCP分析网页性能。测量核心网页指标(FCP、LCP、TBT、CLS、速度指数),识别渲染阻塞资源、网络依赖链、布局偏移、缓存问题及可访问性差距。当被要求审计、分析、调试或优化页面加载性能、Lighthouse评分或网站速度时使用。
official
wrangler
Cloudflare
Cloudflare Workers CLI,用于部署、开发和管理 Workers、KV、R2、D1、Vectorize、Hyperdrive、Workers AI、Containers、Queues、Workflows、Pipelines 及 Secrets Store。在运行 wrangler 命令前加载,以确保正确的语法和最佳实践。
official