workers-best-practices

tarafından Cloudflare

Cloudflare Workers kodlarını üretim en iyi uygulamalarına göre inceler ve yazar. Yeni Workers yazarken, Worker kodunu gözden geçirirken, wrangler.jsonc yapılandırırken veya yaygın Workers anti-desenlerini (streaming, asılı promise'ler, global durum, sırlar, bağlamalar, gözlemlenebilirlik) kontrol ederken yüklenir. Önceden eğitilmiş bilgi yerine Cloudflare dokümanlarından alma eğilimindedir.

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 tarafından daha fazla skill

agents-sdk
Cloudflare
Cloudflare Workers üzerinde Agents SDK kullanarak AI ajanları oluşturun. Durum bilgisi olan ajanlar, dayanıklı iş akışları, gerçek zamanlı WebSocket uygulamaları, zamanlanmış görevler, MCP sunucuları veya sohbet uygulamaları oluştururken yükleyin. Agent sınıfı, durum yönetimi, çağrılabilir RPC, Workflows entegrasyonu ve React hook'larını kapsar.
building-ai-agent-on-cloudflare
Cloudflare
Cloudflare üzerinde Agents SDK kullanarak durum yönetimi, gerçek zamanlı WebSocket'ler, zamanlanmış görevler, araç entegrasyonu ve sohbet yeteneklerine sahip AI ajanları oluşturur. Workers'a dağıtılmak üzere üretime hazır ajan kodu üretir. Şu durumlarda kullan: kullanıcı "ajan oluştur", "AI ajanı", "sohbet ajanı", "durum bilgili ajan" yapmak istediğinde, "Agents SDK"dan bahsettiğinde, "gerçek zamanlı AI", "WebSocket AI" ihtiyacı olduğunda veya ajan "durum yönetimi", "zamanlanmış görevler" ya da "araç çağırma" hakkında soru sorduğunda.
development
building-mcp-server-on-cloudflare
Cloudflare
| Cloudflare Workers üzerinde araçlar, OAuth kimlik doğrulaması ve üretim dağıtımı ile uzak MCP (Model Context Protocol) sunucuları oluşturur. Sunucu kodu üretir, kimlik doğrulama sağlayıcılarını yapılandırır ve Workers'a dağıtır. Şu durumlarda kullanılır: Kullanıcı "MCP sunucusu oluştur", "MCP araçları oluştur", "uzak MCP", "MCP dağıt", MCP'ye "OAuth ekle" veya Cloudflare'da Model Context Protocol'den bahsettiğinde. Ayrıca "MCP kimlik doğrulaması" veya "MCP dağıtımı" ifadelerinde de tetiklenir.
development
cloudflare
Cloudflare
Kapsamlı Cloudflare platform becerisi; Workers, Pages, depolama (KV, D1, R2), yapay zeka (Workers AI, Vectorize, Agents SDK), ağ (Tunnel, Spectrum), güvenlik (WAF, DDoS) ve altyapı-kod-olarak (Terraform, Pulumi) konularını kapsar. Herhangi bir Cloudflare geliştirme görevi için kullanın.
durable-objects
Cloudflare
Cloudflare Durable Objects oluşturun ve inceleyin. Durum bilgisi olan koordinasyon (sohbet odaları, çok oyunculu oyunlar, rezervasyon sistemleri) oluştururken, RPC yöntemleri, SQLite depolama, alarmlar, WebSocket'ler uygularken veya DO kodunu en iyi uygulamalar için incelerken kullanın. Workers entegrasyonu, wrangler yapılandırması ve Vitest ile test etmeyi kapsar.
sandbox-sdk
Cloudflare
Güvenli kod yürütme için sandbox uygulamaları oluşturun. AI kod yürütme, kod yorumlayıcıları, CI/CD sistemleri, etkileşimli geliştirme ortamları veya güvenilmeyen kod yürütme sırasında yükleyin. Sandbox SDK yaşam döngüsü, komutlar, dosyalar, kod yorumlayıcı ve önizleme URL'lerini kapsar.
web-perf
Cloudflare
Chrome DevTools MCP kullanarak web performansını analiz eder. Temel Web Verilerini (FCP, LCP, TBT, CLS, Hız İndeksi) ölçer, render engelleyen kaynakları, ağ bağımlılık zincirlerini, düzen kaymalarını, önbellekleme sorunlarını ve erişilebilirlik eksikliklerini belirler. Sayfa yükleme performansını, Lighthouse puanlarını veya site hızını denetleme, profilleme, hata ayıklama veya optimize etme istendiğinde kullanın.
wrangler
Cloudflare
Cloudflare Workers CLI, Workers, KV, R2, D1, Vectorize, Hyperdrive, Workers AI, Containers, Queues, Workflows, Pipelines ve Secrets Store dağıtmak, geliştirmek ve yönetmek için kullanılır. Doğru sözdizimi ve en iyi uygulamaları sağlamak için wrangler komutlarını çalıştırmadan önce yükleyin.