workers-best-practices

作者: Cloudflare

審查並指導 Cloudflare Workers 程式碼遵循生產最佳實踐。在撰寫新的 Workers、審查 Worker 程式碼、設定 wrangler.jsonc,或檢查常見的 Workers 反模式(串流、懸浮承諾、全域狀態、機密、綁定、可觀測性)時載入。傾向從 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 when writing or reviewing Workers code.

Use the project's installed versions, generated types, and Wrangler compatibility settings as the baseline for existing code. Retrieve relevant Cloudflare documentation to verify API, configuration, runtime behavior, and limit claims.

References

Read the sections relevant to the task:

ReferenceWhen to use it
Configuration and observabilityCompatibility dates, bindings, generated types, secrets, logs, and traces
Runtime patternsStreaming, promise lifetime, request state, service calls, security, and runtime tests
Platform API checksHandler signatures, platform classes, binding access, and serialization

For missing evidence, consult Workers best practices or find the affected product in the Cloudflare docs directory. Use the installed Wrangler schema for config fields. A newer type package does not supersede the project's configured target.

Keep Compatibility Dates Current

Use today's date for new Workers. Encourage periodic updates for existing Workers, reviewing compatibility changes and running relevant tests. Assess existing behavior against its configured date and flags; see compatibility guidance.

Enable Observability

Enable Workers Logs and Traces when creating or preparing a Worker for production. Set observability.enabled and observability.traces.enabled to true; the top-level setting alone does not enable traces. Use structured JSON logging and configure sampling for the workload. During reviews, flag missing logs or traces. See the configuration example.

Anti-Patterns to Flag

Anti-patternConsequence and preferred pattern
await response.text() or similar buffering on unbounded dataCan exhaust Worker memory; stream large or unbounded bodies.
Hardcoded secrets in source or configLeaks credentials through version control; use Wrangler secrets.
Math.random() for security-sensitive tokens or IDsPredictable values; use crypto.randomUUID() or crypto.getRandomValues().
Async work started without awaiting, returning, or attaching it to ctx.waitUntil()Work can be dropped and errors missed; tie it to the request or background-work lifetime.
Module-level mutable request stateLeaks data across requests and can cause I/O ownership errors; pass request state explicitly.
Cloudflare REST API calls for operations available through Worker bindingsAdds network and authentication overhead; use the available binding.
ctx.passThroughOnException() used as general error handlingCan conceal Worker failures by forwarding to the origin; use explicit error handling and structured error responses.
Hand-written Env that duplicates Wrangler bindingsCan drift from configuration; generate binding types with wrangler types.
Direct string comparison of secret valuesCan expose timing differences; use the Web Crypto comparison pattern.
Destructuring ctx methods, such as const { waitUntil } = ctxLoses the receiver; call ctx.waitUntil(...).
any on Env or handler parametersHides binding and handler contract errors; use the project's generated and platform types.
as unknown as T to force a platform type matchHides incompatibilities; fix the underlying contract.
implements used in place of extending a platform base classDoes not inherit runtime behavior, this.ctx, or this.env; use the appropriate base class.
Unbound env.X in a platform class methodBindings are available through this.env.X; see binding access patterns.
Applying one serialization rule across Queues, Workflow steps, storage, and WebSocketsCan reject valid payloads or accept unsupported ones; check the specific API and encoding.

Validation

Use the project's existing checks for affected Workers behavior: type-check binding or handler contract changes, and run relevant runtime tests for behavior changes. Preserve required repository checks; a narrow edit does not require a full Workers audit.

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

來自 Cloudflare 的更多技能

agents-sdk
Cloudflare
在 Cloudflare Workers 上使用 Agents SDK 建置 AI 代理。建立有狀態代理、持久化工作流程、即時 WebSocket 應用程式、排程任務、MCP 伺服器或聊天應用程式時載入。涵蓋 Agent 類別、狀態管理、可呼叫 RPC、Workflows 整合及 React hooks。
building-ai-agent-on-cloudflare
Cloudflare
在 Cloudflare 上使用 Agents SDK 建置 AI 代理,具備狀態管理、即時 WebSocket、排程任務、工具整合及聊天功能。產生可部署至 Workers 的正式環境代理程式碼。 適用時機:使用者想「建置代理」、「AI 代理」、「聊天代理」、「有狀態代理」,提及「Agents SDK」,需要「即時 AI」、「WebSocket AI」,或詢問代理的「狀態管理」、「排程任務」或「工具呼叫」。
development
building-mcp-server-on-cloudflare
Cloudflare
在 Cloudflare Workers 上建置遠端 MCP(模型上下文協定)伺服器,包含工具、OAuth 驗證與正式環境部署。可產生伺服器程式碼、設定驗證提供者,並部署至 Workers。 使用時機:使用者提及「建置 MCP 伺服器」、「建立 MCP 工具」、「遠端 MCP」、「部署 MCP」、為 MCP 加入「OAuth」,或提到 Cloudflare 上的模型上下文協定。亦會觸發於「MCP 驗證」或「MCP 部署」。
development
cloudflare
Cloudflare
涵蓋 Cloudflare 平台的完整技能,包括 Workers、Pages、儲存(KV、D1、R2)、AI(Workers AI、Vectorize、Agents SDK)、網路(Tunnel、Spectrum)、安全(WAF、DDoS)以及基礎設施即程式碼(Terraform、Pulumi)。適用於任何 Cloudflare 開發任務。
durable-objects
Cloudflare
建立與審查 Cloudflare Durable Objects。適用於建構有狀態的協調機制(聊天室、多人遊戲、預訂系統)、實作 RPC 方法、SQLite 儲存、警報、WebSocket,或審查 DO 程式碼以符合最佳實務。涵蓋 Workers 整合、wrangler 設定,以及使用 Vitest 進行測試。
sandbox-sdk
Cloudflare
為安全程式碼執行建置沙盒應用程式。在建立AI程式碼執行、程式碼直譯器、CI/CD系統、互動式開發環境或執行不受信任的程式碼時載入。涵蓋Sandbox SDK生命週期、指令、檔案、程式碼直譯器及預覽URL。
web-perf
Cloudflare
使用 Chrome DevTools MCP 分析網頁效能。測量核心網頁指標(FCP、LCP、TBT、CLS、速度指數),識別渲染阻塞資源、網路依賴鏈、版面位移、快取問題及無障礙缺口。當被要求稽核、剖析、除錯或優化頁面載入效能、Lighthouse 分數或網站速度時使用。
wrangler
Cloudflare
Cloudflare Workers CLI,用於部署、開發及管理 Workers、KV、R2、D1、Vectorize、Hyperdrive、Workers AI、Containers、Queues、Workflows、Pipelines 與 Secrets Store。在執行 wrangler 指令前載入,以確保正確語法與最佳實踐。