workers-best-practices

Meninjau dan menulis kode Cloudflare Workers sesuai praktik terbaik produksi. Muat saat menulis Workers baru, meninjau kode Worker, mengonfigurasi wrangler.jsonc, atau memeriksa anti-pola Workers umum (streaming, janji mengambang, status global, rahasia, binding, observabilitas). Lebih mengutamakan pengambilan dari dokumentasi Cloudflare daripada pengetahuan terlatih.

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

Lebih banyak skill dari Cloudflare

agents-sdk
Cloudflare
Bangun agen AI di Cloudflare Workers menggunakan Agents SDK. Muat saat membuat agen stateful, alur kerja tahan lama, aplikasi WebSocket real-time, tugas terjadwal, server MCP, atau aplikasi obrolan. Mencakup kelas Agent, manajemen status, RPC yang dapat dipanggil, integrasi Workflows, dan React hooks.
building-ai-agent-on-cloudflare
Cloudflare
Membangun agen AI di Cloudflare menggunakan Agents SDK dengan manajemen status, WebSocket waktu nyata, tugas terjadwal, integrasi alat, dan kemampuan obrolan. Menghasilkan kode agen siap produksi yang di-deploy ke Workers. Gunakan ketika: pengguna ingin "membangun agen", "agen AI", "agen obrolan", "agen stateful", menyebut "Agents SDK", membutuhkan "AI waktu nyata", "WebSocket AI", atau bertanya tentang "manajemen status" agen, "tugas terjadwal", atau "pemanggilan alat".
development
building-mcp-server-on-cloudflare
Cloudflare
Membangun server MCP (Model Context Protocol) jarak jauh di Cloudflare Workers dengan alat, autentikasi OAuth, dan deployment produksi. Menghasilkan kode server, mengonfigurasi penyedia autentikasi, dan melakukan deployment ke Workers. Gunakan ketika: pengguna ingin "membangun server MCP", "membuat alat MCP", "MCP jarak jauh", "deploy MCP", menambahkan "OAuth ke MCP", atau menyebutkan Model Context Protocol di Cloudflare. Juga terpicu pada "autentikasi MCP" atau "deployment MCP".
development
cloudflare
Cloudflare
Kemampuan platform Cloudflare yang komprehensif mencakup Workers, Pages, penyimpanan (KV, D1, R2), AI (Workers AI, Vectorize, Agents SDK), jaringan (Tunnel, Spectrum), keamanan (WAF, DDoS), dan infrastruktur-sebagai-kode (Terraform, Pulumi). Gunakan untuk tugas pengembangan Cloudflare apa pun.
durable-objects
Cloudflare
Buat dan tinjau Cloudflare Durable Objects. Gunakan saat membangun koordinasi stateful (ruang obrolan, game multipemain, sistem pemesanan), mengimplementasikan metode RPC, penyimpanan SQLite, alarm, WebSocket, atau meninjau kode DO untuk praktik terbaik. Mencakup integrasi Workers, konfigurasi wrangler, dan pengujian dengan Vitest.
sandbox-sdk
Cloudflare
Bangun aplikasi sandbox untuk eksekusi kode yang aman. Muat saat membangun eksekusi kode AI, interpreter kode, sistem CI/CD, lingkungan pengembangan interaktif, atau mengeksekusi kode yang tidak tepercaya. Mencakup siklus hidup Sandbox SDK, perintah, file, interpreter kode, dan URL pratinjau.
web-perf
Cloudflare
Menganalisis kinerja web menggunakan Chrome DevTools MCP. Mengukur Core Web Vitals (FCP, LCP, TBT, CLS, Speed Index), mengidentifikasi sumber daya yang memblokir rendering, rantai ketergantungan jaringan, pergeseran tata letak, masalah caching, dan celah aksesibilitas. Gunakan saat diminta untuk mengaudit, memprofilkan, men-debug, atau mengoptimalkan kinerja pemuatan halaman, skor Lighthouse, atau kecepatan situs.
wrangler
Cloudflare
CLI Cloudflare Workers untuk men-deploy, mengembangkan, dan mengelola Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines, dan Secrets Store. Muat sebelum menjalankan perintah wrangler untuk memastikan sintaksis dan praktik terbaik yang benar.