Лучшие практики Cloudflare Workers

Проверяет код и конфигурацию Cloudflare Workers по правилам для прода: даты совместимости, логи и трейсы, стриминг, waitUntil, биндинги вместо REST, Web Crypto, типы Env. Для случаев, когда Worker пишут, ревьюят или готовят к выкладке.

DevOpsПак: Скиллы Cloudflare68 строкworkers-best-practices
Автор
Источник
cloudflare/skills/skills/workers-best-practices @ 5108325
Лицензия
Apache-2.0

Об этом скилле

Что делает

Скилл — чек-лист для написания и ревью кода Cloudflare Workers, который готовят к проду. Он велит агенту не полагаться на память о Workers: точка отсчёта — установленный в проекте Wrangler, сгенерированные типы и настройки совместимости, а утверждения про API, поля конфигурации и лимиты сверяются с developers.cloudflare.com.

В SKILL.md три правила по умолчанию: compatibility_date на сегодня для нового Worker, включённые Workers Logs и Traces (трейсам нужен свой observability.traces.enabled) и явное размещение рядом с региональной базой, к которой идёт несколько запросов подряд. Дальше — пятнадцать антипаттернов. Среди них чтение неограниченного тела при лимите памяти 128 МБ, промисы без await и без ctx.waitUntil(), изменяемое состояние на уровне модуля, Math.random() для токенов, === для секретов, самописный Env вместо wrangler types и env.X вместо this.env.X внутри класса DurableObject.

references/configuration.md — даты совместимости, nodejs_compat, секреты и настройки наблюдаемости. runtime-patterns.md — стриминг, Queues и Workflows, сервисные биндинги, Hyperdrive, Web Crypto и тесты на @cloudflare/vitest-plugin. platform-apis.md — сигнатуры обработчиков, доступ к биндингам и то, что можно сериализовать на границах с очередями, шагами Workflow, хранилищем Durable Objects и WebSocket. skill-feedback.md готовит публичный issue в cloudflare/skills и отправляет его только после того, как вы одобрите текст.

Когда включать и когда не надо

Когда пишете новый Worker, готовите его к проду или смотрите пулреквест, который трогает код Worker или wrangler.jsonc.

Это не справочник по CLI и не руководство по Durable Objects — за этим скилл отправляет к соседним скиллам. Для точечной правки полный аудит не нужен.

Как поставить и вызвать

Команда установки ниже скачивает SKILL.md, четыре справочника и лицензию. Агент сам подхватывает скилл по описанию. Вызвать вручную:

  • Claude Code: /workers-best-practices или попросить скилл по имени.
  • Codex: $workers-best-practices.
  • Cursor: наберите / в чате Agent и выберите workers-best-practices.

Пример: /workers-best-practices Проверь src/index.ts и wrangler.jsonc перед выкладкой этого Worker.

Агенту нужен доступ в сеть, чтобы читать документацию; ключи API и MCP-серверы не нужны.

Чем отличается от похожих

Durable Objects в Cloudflare, Wrangler CLI для Cloudflare и CLI cf для API Cloudflare из того же пакета подробно разбирают то, на что этот скилл только ссылается. Код-ревью по практикам Sentry — общий чек-лист ревью, о рантайме Workers он ничего не знает. В Ревью безопасности по стеку есть спецификации для Express, Next.js и других стеков, но не для Workers. Бессерверный Postgres в Neon одной строкой советует node-postgres с Hyperdrive на Cloudflare; здесь добавлено, что Hyperdrive сам по себе не размещает Worker рядом с базой.

Установка

Выполните одну команду — она сохранит SKILL.md и файлы, которые он использует, в папку скиллов агента. Claude Code и Codex подхватывают новый скилл без перезапуска; если скилл не появился, перезапустите агента.

Скилл написан на английском — агент поймёт его и ответит вам по-русски.

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 }

Другой агент: сохраните файл в его папку скиллов или дайте ему ссылку на файл: https://anymodel.org/en/skills/cloudflare/workers-best-practices/SKILL.md

SKILL.md

Исходник

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.

Подключить через AnyModel API

Скилл работает на той модели, которую использует агент. Подключите Claude Code, Codex или Cursor к AnyModel и запускайте его на Claude, GPT, Gemini и других моделях по одному ключу — оплата за токены, без подписки.

Ещё из пака Скиллы Cloudflare

Wrangler CLI для Cloudflare

Ведёт команды и конфигурацию Wrangler в проектах с wrangler.jsonc или wrangler.toml: сверяется со справкой и документацией, бережёт секреты, окружения и Previews. Для случаев, когда Worker деплоят, настраивают или чинят через Wrangler.

Durable Objects в Cloudflare

Помогает писать и ревьюить Durable Objects в Cloudflare: объект на сущность, хранилище SQLite и миграции, RPC-методы, alarms, WebSocket и тесты на Vitest. Для случаев, когда приложению на Workers нужны общее состояние и координация.

Agents SDK от Cloudflare

Помогает строить приложения на Agents SDK от Cloudflare: агенты с состоянием на Durable Objects, RPC, расписания, очереди, Workflows, чат на AIChatAgent, MCP и почта. Для случаев, когда нужен ИИ-агент или чат на Workers.

Веб-фреймворки на Cloudflare Workers

Настраивает приложения на Astro, SvelteKit, React Router, TanStack Start, Nuxt, Hono и SPA под Cloudflare Workers, выбирая C3, Wrangler или cf по состоянию проекта. Для случаев, когда приложение создают, переносят или деплоят на Workers.

Локальная разработка Workers

Запускает и отлаживает Workers локально через cf dev, wrangler dev или плагин Vite, а в Local Explorer читает и наполняет данные биндингов и смотрит трейсы. Для случаев, когда локальный запрос падает или непонятно, что вернул биндинг.

CLI cf для API Cloudflare

Находит и выполняет команды CLI cf от Cloudflare (бета) через cf cli search, cf schema и пробные прогоны, выбирает между cf и Wrangler. Для случаев, когда нужно работать с DNS, зонами, D1, KV или R2 из терминала или начать проект на Workers.

Аудит скорости сайта

Проводит аудит скорости страницы через Chrome DevTools MCP: трейс, Core Web Vitals по порогам, сеть, снимок доступности и настройки сборки, с исправлениями по приоритету. Для случаев, когда страница тормозит или оценка Lighthouse низкая.