workers-best-practices — скилл для Claude Code: обзор и установка
Скилл настраивает ИИ на проверку продакшен-кода Cloudflare Workers по актуальным правилам рантайма, типам Wrangler и антипаттернам.
npx skills add cloudflare/skills --skill workers-best-practices -a claude-codeЧто делает workers-best-practices
Скилл запрещает агенту полагаться на устаревшие знания из предобучения и требует сверять код с версиями проекта и типами Wrangler. Он проверяет даты совместимости и контролирует параметры телеметрии. Для продакшена обязательно включать и observability.enabled, и observability.traces.enabled — верхнеуровневый флаг сам по себе трейсинг не запускает.
Агент отслеживает утечки памяти при буферизации больших тел через response.text() и потерю контекста в ctx.waitUntil(). Он находит мутации глобального состояния между запросами. Для генерации токенов скилл требует Web Crypto вместо Math.random(). Типы биндингов нужно генерировать через wrangler types, не подменяя их типом any.
Скилл сфокусирован только на базовых воркерах. Логику Durable Objects или Workflows он не заменит, потому что для них у Cloudflare созданы отдельные наборы инструкций. Это строгий фильтр для пулл-реквестов, исключающий скрытые сбои ввода-вывода ещё до деплоя.
Какие задачи решает
- проверить код Cloudflare Workers на утечки памяти при буферизации
- настроить структурированное логирование и трейсинг в Wrangler
- найти забытые фоновые промисы мимо
ctx.waitUntil() - заменить небезопасную генерацию токенов на Web Crypto
- проверить типизацию биндингов Wrangler без использования
any
Примеры запросов агенту
- Проверь этот воркер на антипаттерны перед деплоем в продакшен
- Помоги настроить observability и даты совместимости в wrangler.toml
- Проведи ревью фоновых вызовов и чтения тел ответов в worker.ts
Как установить workers-best-practices
1Через Skills CLI (Vercel)
npx skills add cloudflare/skills --skill workers-best-practices -a claude-code2Вручную: положить файлы
~/.claude/skills/workers-best-practices/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/workers-best-practices/
1Через Skills CLI (Vercel)
npx skills add cloudflare/skills --skill workers-best-practices -a codex2Вручную: положить файлы
.agents/skills/workers-best-practices/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add cloudflare/skills --skill workers-best-practices -a cursor2Вручную: положить файлы
.cursor/skills/workers-best-practices/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install cloudflare/skills workers-best-practices2Вручную: положить файлы
.github/skills/workers-best-practices/SKILL.md1Через Skills CLI (Vercel)
npx skills add cloudflare/skills --skill workers-best-practices -a gemini-cli2Командой платформы
gemini skills install https://github.com/cloudflare/skills --path skills/workers-best-practicesВручную: положить файлы
.devin/skills/workers-best-practices/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add cloudflare/skills --skill workers-best-practices -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
Из того же набора18
Весь набор →Похожие
Вопросы о workers-best-practices
Как установить workers-best-practices в Claude Code?
Выполните команду npx skills add cloudflare/skills --skill workers-best-practices -a claude-code.
Что делает скилл workers-best-practices?
Он направляет модель на поиск ошибок в коде Cloudflare Workers: опасной буферизации данных, пропущенных вызовов ctx.waitUntil(), некорректных типов и вызовов REST API вместо прямых биндингов.
Подходит ли этот скилл для Durable Objects?
Нет, для Durable Objects используется отдельный скилл durable-objects. Этот набор правил закрывает только логику самого рантайма Workers и настройки Wrangler.
Исходный текст
SKILL.md · Apache-2.0
---
name: workers-best-practices
description: Cloudflare Workers best practices for production applications. Use when writing, reviewing, or configuring Workers.
---
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](references/configuration.md) | Compatibility dates, bindings, generated types, secrets, logs, and traces |
| [Runtime patterns](references/runtime-patterns.md) | Streaming, promise lifetime, request state, service calls, security, and runtime tests |
| [Platform API checks](references/platform-apis.md) | Handler signatures, platform classes, binding access, and serialization |
For missing evidence, consult [Workers best practices](https://developers.cloudflare.com/workers/best-practices/workers-best-practices/index.md) or find the affected product in the [Cloudflare docs directory](https://developers.cloudflare.com/directory/index.md). 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](references/configuration.md#keep-compatibility_date-current).
## Enable Observability
Enable [Workers Logs](https://developers.cloudflare.com/workers/observability/logs/workers-logs/index.md) and [Traces](https://developers.cloudflare.com/workers/observability/traces/index.md) 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](references/configuration.md#enable-workers-logs-and-traces).
## 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](references/runtime-patterns.md#stream-request-and-response-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](references/runtime-patterns.md#use-web-crypto-for-secure-token-generation). |
| 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](references/platform-apis.md#binding-access--the-most-common-error). |
| 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](references/platform-apis.md#serialization-boundaries). |
## 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](https://developers.cloudflare.com/workflows/build/rules-of-workflows/index.md)
- **CLI commands**: load the `cf-cli` skill, or the `wrangler` skill in a project with a Wrangler configuration file
© cloudflare · Apache-2.0 · cloudflare/skills