Workers Best Practices
CloudflareOfficialPublished by Cloudflare
- Skill
- Guidelines
- Cloud and DevOps
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides best practices for developing and maintaining Cloudflare Workers. It emphasizes using project-specific configurations, generated types, and current documentation to ensure code aligns with the runtime environment. It covers configuration management, observability, platform API usage, and common anti-patterns to avoid during development and code reviews.
What it does
- Provides guidance on maintaining compatibility dates and enabling observability features.
- Outlines patterns for secure secret management and environment variable usage.
- Identifies common coding anti-patterns and suggests preferred implementation alternatives.
- Advises on correct binding access patterns for module handlers and platform classes.
- Recommends using generated types to ensure consistency between configuration and code.
- Offers references for runtime patterns, platform APIs, and configuration settings.
When to use it
- When writing new Cloudflare Workers code.
- During code reviews to identify potential configuration or runtime issues.
- When configuring project settings or updating compatibility dates.
- When troubleshooting runtime behavior or binding access errors.
Advantages
- Promotes consistency between Wrangler configuration and application code.
- Helps prevent common runtime errors related to binding access and serialization.
- Encourages the use of modern, supported platform APIs and patterns.
- Reduces the risk of credential leakage through proper secret handling.
Usage examples
- “How should I handle environment variables and secrets in my Worker?”
- The skill advises using wrangler secret for sensitive data and vars for non-secret configuration, while warning against hardcoding secrets in source or config files.
- “What is the best way to define my Env interface?”
- The skill recommends running wrangler types to generate the interface automatically, rather than hand-writing it, to ensure it stays in sync with the configuration.
- “I am getting an error accessing a binding inside a class. What is wrong?”
- The skill explains that platform classes should access bindings via this.env.X, whereas module export handlers should access them via the env parameter.
- “How do I enable logging for my Worker?”
- The skill provides instructions to enable Workers Logs and Traces by setting observability.enabled and observability.traces.enabled to true in the configuration.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/cloudflare/workers-best-practices/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip workers-best-practices.zip -d .agents/skills
Documentation by Cloudflare
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:
| Reference | When to use it |
|---|---|
| Configuration and observability | Compatibility dates, bindings, generated types, secrets, logs, and traces |
| Runtime patterns | Streaming, promise lifetime, request state, service calls, security, and runtime tests |
| Platform API checks | Handler 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.
Place Compute Near Regional Databases
For Workers that make multiple sequential queries to one regional database, configure explicit placement matching the database's provider and region before deployment. Ask for missing location information, preserve existing placement choices, and verify handler eligibility and deployed request duration. See database placement.
Anti-Patterns to Flag
| Anti-pattern | Consequence and preferred pattern |
|---|---|
await response.text() or similar buffering on unbounded data | Can exhaust Worker memory; stream large or unbounded bodies. |
| Hardcoded secrets in source or config | Leaks credentials through version control; use Wrangler secrets. |
Math.random() for security-sensitive tokens or IDs | Predictable 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 state | Leaks data across requests and can cause I/O ownership errors; pass request state explicitly. |
| Cloudflare REST API calls for operations available through Worker bindings | Adds network and authentication overhead; use the available binding. |
ctx.passThroughOnException() used as general error handling | Can conceal Worker failures by forwarding to the origin; use explicit error handling and structured error responses. |
Hand-written Env that duplicates Wrangler bindings | Can drift from configuration; generate binding types with wrangler types. |
| Direct string comparison of secret values | Can expose timing differences; use the Web Crypto comparison pattern. |
Destructuring ctx methods, such as const { waitUntil } = ctx | Loses the receiver; call ctx.waitUntil(...). |
any on Env or handler parameters | Hides binding and handler contract errors; use the project's generated and platform types. |
as unknown as T to force a platform type match | Hides incompatibilities; fix the underlying contract. |
implements used in place of extending a platform base class | Does not inherit runtime behavior, this.ctx, or this.env; use the appropriate base class. |
Unbound env.X in a platform class method | Bindings are available through this.env.X; see binding access patterns. |
| Applying one serialization rule across Queues, Workflow steps, storage, and WebSockets | Can 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-objectsskillWorkflows: see Rules of Workflows
CLI commands: load the
cf-cliskill, or thewranglerskill in a project with a Wrangler configuration file
Skill feedback
If the user reports that this skill gave incorrect or outdated guidance, or is missing information, read references/skill-feedback.md.
Files
- ATTRIBUTION.mdAdded by AutoGineer880 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md6.1 KiB
- references/configuration.md6.6 KiB
- references/platform-apis.md3.8 KiB
- references/runtime-patterns.md13.5 KiB
- references/skill-feedback.md2.8 KiB
references/platform-apis.md
Workers Platform API Checks
Use the project's installed and generated types to check affected handlers and bindings. Consult current Cloudflare docs when API or runtime compatibility remains uncertain.
Type validation: binding types, handler signatures, and platform classes
Serialization boundaries: encoding and supported values for each API
Type Validation
Env interface
Every binding must have a specific type. Flag
any,unknown,object, orRecord<string, unknown>on bindings.Binding types that accept generic parameters (Durable Object namespaces, Queues, Service bindings for RPC) must include them. Read the type definition to confirm which types are generic.
Use the project's generated binding types; see configuration guidance.
Handler and class signatures
Verify affected signatures against the project's target type definitions; consult current docs if runtime support or compatibility remains uncertain.
Correct import path (most Workers platform classes import from
"cloudflare:workers")Generic type parameter on base classes (e.g.,
DurableObject<Env>)ExecutionContextas the third param in module export handlers (needed forctx.waitUntil())fetch()handlers must returnPromise<Response>
Binding access — the most common error
Module export handlers (
fetch,scheduled,queue,email): bindings viaenv.XparameterPlatform base classes (
WorkerEntrypoint,DurableObject,Workflow,Agent): bindings viathis.env.X
Flag env.X inside a class extending a platform base class. Flag this.env.X inside a module export handler.
Stale class patterns
Old patterns survive in codebases long after APIs change.
extendsvsimplements: platform classes useextends, notimplements. Theimplementspattern is legacy and losesthis.ctx,this.env.Import paths: verify module specifiers match what types actually export. Common mistake: wrong path for
"cloudflare:workers"vs"cloudflare:workflows".Renamed properties: e.g.,
this.statetothis.ctxin Durable Objects. Search types to confirm.Constructor signatures: base class constructors change. Verify expected parameters.
Serialization Boundaries
Check the API and encoding at each boundary. Structured clone support does not imply JSON compatibility or SQL parameter support.
| Boundary | What to check |
|---|---|
| Queue messages | Match the body to contentType: json requires JSON-compatible data, text a string, bytes an ArrayBuffer, and v8 supports structured-clone values such as Map and Date. Check the configured compatibility date when relying on the default encoding. |
| Workflow step results | Verify the step result against the documented serialization contract and the project's Workflow types before flagging a value. |
| Durable Object KV storage | storage.put() supports structured-clone values; do not apply a blanket ban on Map or Set. |
| Durable Object SQL | Check bound parameters against the SQL API's supported types. Encode objects explicitly for the intended column representation. |
| WebSocket messages | Use send() with a string, ArrayBuffer, or ArrayBufferView; encode objects, for example with JSON.stringify(). |
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Cloudflare
- Publisher
- Cloudflare (Official)
- Source
- cloudflare/skills · skills/workers-best-practices · commit 6eb6c78
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Cloudflare.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download workers-best-practices.zip