Cloudflare Workers best practices

Checks Cloudflare Workers code and config against production rules: current compatibility dates, logs and traces, streaming, waitUntil, bindings over REST calls, Web Crypto, generated Env types. Use when writing, reviewing or shipping a Worker.

DevOpsPack: Cloudflare skills68 linesworkers-best-practices
Author
Source
cloudflare/skills/skills/workers-best-practices @ 5108325
License
Apache-2.0

About this skill

What it does

The skill is a checklist for writing and reviewing Cloudflare Workers code headed for production. It tells the agent not to trust its memory of Workers: the project's installed Wrangler, generated types and compatibility settings are the baseline, and claims about APIs, config fields or limits are checked against developers.cloudflare.com.

SKILL.md sets three defaults: today's compatibility_date for a new Worker, Workers Logs and Traces switched on (traces need their own observability.traces.enabled), and explicit placement near a regional database that gets several queries in a row. Fifteen anti-patterns follow, among them buffering an unbounded body against the 128 MB memory limit, promises neither awaited nor passed to ctx.waitUntil(), mutable module-level state, Math.random() for tokens, === on secrets, a hand-written Env instead of wrangler types, and env.X instead of this.env.X inside a DurableObject class.

references/configuration.md covers compatibility dates, nodejs_compat, secrets and observability settings. runtime-patterns.md has streaming, Queues and Workflows, service bindings, Hyperdrive, Web Crypto and tests with @cloudflare/vitest-plugin. platform-apis.md checks handler signatures, binding access and what Queues, Workflow steps, Durable Object storage and WebSockets can serialize. skill-feedback.md drafts a public issue for cloudflare/skills, posted only after you approve the text.

When to use it, and when not

Use it when writing a new Worker, preparing one for production or reviewing a pull request that touches Worker code or wrangler.jsonc.

It is not a CLI or Durable Objects guide; for those it hands off to sibling skills. A narrow edit does not call for a full audit.

How to run it

The install command below puts SKILL.md, the four references and the licence in place. The agent picks the skill up by its description; to call it yourself:

  • Claude Code: /workers-best-practices, or ask for the skill by name.
  • Codex: $workers-best-practices.
  • Cursor: type / in the Agent chat and pick workers-best-practices.

Example: /workers-best-practices Review src/index.ts and wrangler.jsonc before we ship this Worker.

The agent needs web access for the linked docs; no API keys or MCP servers.

How it differs from similar skills

Cloudflare Durable Objects, Wrangler CLI and Cloudflare cf CLI from the same pack cover what this skill only points to. Code review, Sentry practices is a general review checklist with no knowledge of the Workers runtime. Security best-practice review has specs for Express, Next.js and other stacks, none for Workers. Neon serverless Postgres says in one line to use node-postgres with Hyperdrive on Cloudflare; this skill adds that Hyperdrive alone does not place the Worker near the database.

Install

Run one command — it saves SKILL.md and the files it uses into your agent's skills folder. Claude Code and Codex pick up a new skill without a restart; if it does not show up, restart the agent.

Claude Code — macOS, Linux
curl -fsSL --create-dirs -o ~/.claude/skills/workers-best-practices/SKILL.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/SKILL.md -o ~/.claude/skills/workers-best-practices/LICENSE https://anymodel.org/en/skills/cloudflare/workers-best-practices/LICENSE -o ~/.claude/skills/workers-best-practices/references/configuration.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/configuration.md -o ~/.claude/skills/workers-best-practices/references/platform-apis.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/platform-apis.md -o ~/.claude/skills/workers-best-practices/references/runtime-patterns.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/runtime-patterns.md -o ~/.claude/skills/workers-best-practices/references/skill-feedback.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/skill-feedback.md
Codex, Cursor — macOS, Linux
curl -fsSL --create-dirs -o ~/.agents/skills/workers-best-practices/SKILL.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/SKILL.md -o ~/.agents/skills/workers-best-practices/LICENSE https://anymodel.org/en/skills/cloudflare/workers-best-practices/LICENSE -o ~/.agents/skills/workers-best-practices/references/configuration.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/configuration.md -o ~/.agents/skills/workers-best-practices/references/platform-apis.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/platform-apis.md -o ~/.agents/skills/workers-best-practices/references/runtime-patterns.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/runtime-patterns.md -o ~/.agents/skills/workers-best-practices/references/skill-feedback.md https://anymodel.org/en/skills/cloudflare/workers-best-practices/references/skill-feedback.md
Claude Code — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE','references/configuration.md','references/platform-apis.md','references/runtime-patterns.md','references/skill-feedback.md') { $p = Join-Path "$HOME\.claude\skills\workers-best-practices" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/cloudflare/workers-best-practices/$f" -UseBasicParsing -OutFile $p }
Codex, Cursor — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE','references/configuration.md','references/platform-apis.md','references/runtime-patterns.md','references/skill-feedback.md') { $p = Join-Path "$HOME\.agents\skills\workers-best-practices" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/cloudflare/workers-best-practices/$f" -UseBasicParsing -OutFile $p }

Any other agent: save the file into its skills folder, or give it the link to the file: https://anymodel.org/en/skills/cloudflare/workers-best-practices/SKILL.md

SKILL.md

Raw

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-objects skill
  • Workflows: see Rules of Workflows
  • CLI commands: load the cf-cli skill, or the wrangler skill 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.

Connect through AnyModel API

This skill runs on whatever model your agent uses. Point Claude Code, Codex or Cursor at AnyModel to run it on Claude, GPT, Gemini and more with one key — pay per token, no subscription.

More from the pack Cloudflare skills

Wrangler CLI

Guides Wrangler commands and config in projects with wrangler.jsonc or wrangler.toml, checking installed help and current docs and guarding secrets, environments and Previews. Use when deploying, configuring or debugging a Worker with Wrangler.

Cloudflare Durable Objects

Builds and reviews Cloudflare Durable Objects: one object per entity, SQLite storage and migrations, RPC methods, alarms, WebSockets and Vitest tests, with links to current docs. Use when a Workers app needs shared state or coordination.

Cloudflare Agents SDK

Builds and reviews apps on Cloudflare's Agents SDK: stateful agents on Durable Objects, callable RPC, scheduling, queues, Workflows, AIChatAgent chat, MCP and email. Use when building an AI agent or chat app on Workers.

Web frameworks on Cloudflare Workers

Sets up Astro, SvelteKit, React Router, TanStack Start, Nuxt, Hono and SPA apps on Cloudflare Workers, choosing C3, Wrangler or cf by the project's state. Use when creating, migrating or deploying a framework app on Workers.

Local Workers development

Runs and debugs Workers locally with cf dev, wrangler dev or the Vite plugin, using Local Explorer to read and seed binding data and query traces. Use when a local request fails or you need to see what a binding returned.

Cloudflare cf CLI

Finds and runs commands of Cloudflare's beta cf CLI through cf cli search, cf schema and dry runs, and picks cf or Wrangler per project. Use when managing DNS, zones, D1, KV or R2 from the terminal or starting a new Workers project.

Web performance audit

Audits a web page's loading performance through Chrome DevTools MCP: a trace, Core Web Vitals against thresholds, network, an accessibility snapshot and bundle config, with ranked fixes. Use when a page is slow or its Lighthouse score is low.