{
  "id": "codex-rules-for-cloudflare-workers",
  "type": "rules",
  "category": "rules",
  "locale": "pt",
  "url": "/pt/rules/codex-rules-for-cloudflare-workers",
  "title": "Regras do Codex para Cloudflare Workers",
  "description": "Regras do Codex para projetos Cloudflare Workers que previnem o uso da API Node.js, reforçam padrões de bindings e mantêm os agentes dentro das restrições do runtime Workers.",
  "tools": [
    "Codex",
    "Cursor",
    "Claude Code"
  ],
  "stack": [
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "typescript",
    "conventions",
    "deploy"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "Adicione isto como `AGENTS.md` ou um trecho de prompt de sistema do Codex. Cloudflare Workers executam no runtime de isolamento V8 — não Node.js — então os agentes precisam de orientações explícitas para evitar gerar código que falha silenciosamente no desenvolvimento local, mas quebra na implantação.\n\n## Arquivo de Regras do Codex\n\n```txt title=\"Codex Rules\"\n# Cloudflare Workers Rules\n\n## Runtime constraints — READ FIRST\n- This project runs on the Cloudflare Workers runtime (V8 isolate), NOT Node.js.\n  Node.js built-ins (`fs`, `path`, `crypto` from `node:crypto` pre-Workers-crypto,\n  `child_process`, `net`, `dgram`) are NOT available unless explicitly listed as\n  available in the wrangler compatibility flags.\n- Allowed globals: `fetch`, `Request`, `Response`, `Headers`, `URL`, `URLSearchParams`,\n  `ReadableStream`, `WritableStream`, `TransformStream`, `TextEncoder`, `TextDecoder`,\n  `crypto` (Web Crypto API), `caches` (Cache API), `setTimeout`, `clearTimeout`.\n- Do NOT use `process.env`. Environment variables and secrets are accessed via the\n  `Env` bindings object passed to the `fetch` handler as the second argument.\n- Do NOT import `node:*` modules unless `nodejs_compat` is set in `wrangler.toml`\n  and you have confirmed the specific module is available in that compat mode.\n\n## Bindings pattern\n- All KV, R2, D1, Durable Object, Queue, and AI bindings are declared in\n  `wrangler.toml` and typed in `src/types/env.d.ts` (or `worker-configuration.d.ts`).\n- Access bindings only through the `env` parameter of the `ExportedHandler` fetch\n  method: `export default { async fetch(req, env, ctx) { ... } }`.\n- Never instantiate KV or R2 clients manually — use the env binding directly.\n- Run `wrangler types` after adding a new binding to regenerate the TypeScript types.\n\n## Request/Response handling\n- Always return a `Response` object from the `fetch` handler. Never `throw` outside\n  a try/catch at the handler boundary — unhandled errors surface as opaque 500s.\n- Use `ctx.waitUntil()` for fire-and-forget async work (logging, analytics writes)\n  so the isolate is not terminated before the side effect completes.\n- Stream large responses with `ReadableStream` rather than buffering them entirely\n  in memory — Workers have a 128 MB memory limit per isolate.\n\n## Build and deploy\n- Use `wrangler dev` for local development (not `node server.js` or any other runner).\n- Test with `wrangler dev --remote` before deploying to catch binding resolution\n  issues that only appear against real Cloudflare infrastructure.\n- Deploy with `wrangler deploy`. Never edit the production worker via the Cloudflare\n  dashboard directly — it diverges from the codebase.\n- Bundle size must stay under 1 MB (compressed). Run `wrangler deploy --dry-run`\n  and check the reported bundle size before merging large dependency additions.\n\n## TypeScript conventions\n- Strict mode enabled. No `any`. Use `unknown` for untrusted external data and\n  narrow it with Zod or manual type guards before use.\n- The `Env` interface must be in sync with `wrangler.toml`. If you add a binding\n  in `wrangler.toml`, add the corresponding property to `Env` in the same PR.\n- Use `satisfies ExportedHandler<Env>` on the default export to catch binding\n  type mismatches at compile time.\n\n## Definition of done\n- `wrangler check` (or `tsc --noEmit`) passes with zero errors.\n- `wrangler dev` starts without warnings.\n- `wrangler deploy --dry-run` reports bundle size under 1 MB.\n- No `process.env` references in source. No `node:*` imports unless compat flag is set.\n```\n\n## Por que essas regras\n\n- **Sem `process.env`** é o erro mais comum em Cloudflare Workers que agentes de IA cometem. Agentes treinados em bases de código Node.js e Next.js recorrem a `process.env.MY_SECRET` por padrão. No Workers, isso é `undefined` em tempo de execução — os bindings vêm através do argumento `env`, não do ambiente do processo.\n- **`ctx.waitUntil()` para efeitos colaterais** previne uma classe sutil de bugs de perda de dados. Workers encerram o isolamento assim que a `Response` é retornada. Qualquer `await` que seja executado após o envio da resposta sem `waitUntil` é descartado silenciosamente, causando perda de eventos de analytics, falhas em escritas de log ou atualizações parciais de banco de dados.\n\n## Adequado para\n\n- APIs Cloudflare Workers, middleware de borda, roteadores Workers baseados em Hono, Workers com bindings D1/KV/R2.\n\n## Não adequado para\n\n- Cloudflare Pages Functions (runtime similar, mas convenção de roteamento baseada em arquivos diferente) ou projetos que são implantados intencionalmente no Node.js via a flag `nodejs_compat` com APIs completas do Node.js habilitadas."
}