P PasteCode
Rule

Regras do Codex para Cloudflare Workers

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.

CodexCursorClaude Code CloudflareTypeScript
.md .json Atualizado 8 de jun. de 2026

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.

Arquivo de Regras do Codex

Codex Rules
# Cloudflare Workers Rules
## Runtime constraints — READ FIRST
- This project runs on the Cloudflare Workers runtime (V8 isolate), NOT Node.js.
Node.js built-ins (`fs`, `path`, `crypto` from `node:crypto` pre-Workers-crypto,
`child_process`, `net`, `dgram`) are NOT available unless explicitly listed as
available in the wrangler compatibility flags.
- Allowed globals: `fetch`, `Request`, `Response`, `Headers`, `URL`, `URLSearchParams`,
`ReadableStream`, `WritableStream`, `TransformStream`, `TextEncoder`, `TextDecoder`,
`crypto` (Web Crypto API), `caches` (Cache API), `setTimeout`, `clearTimeout`.
- Do NOT use `process.env`. Environment variables and secrets are accessed via the
`Env` bindings object passed to the `fetch` handler as the second argument.
- Do NOT import `node:*` modules unless `nodejs_compat` is set in `wrangler.toml`
and you have confirmed the specific module is available in that compat mode.
## Bindings pattern
- All KV, R2, D1, Durable Object, Queue, and AI bindings are declared in
`wrangler.toml` and typed in `src/types/env.d.ts` (or `worker-configuration.d.ts`).
- Access bindings only through the `env` parameter of the `ExportedHandler` fetch
method: `export default { async fetch(req, env, ctx) { ... } }`.
- Never instantiate KV or R2 clients manually — use the env binding directly.
- Run `wrangler types` after adding a new binding to regenerate the TypeScript types.
## Request/Response handling
- Always return a `Response` object from the `fetch` handler. Never `throw` outside
a try/catch at the handler boundary — unhandled errors surface as opaque 500s.
- Use `ctx.waitUntil()` for fire-and-forget async work (logging, analytics writes)
so the isolate is not terminated before the side effect completes.
- Stream large responses with `ReadableStream` rather than buffering them entirely
in memory — Workers have a 128 MB memory limit per isolate.
## Build and deploy
- Use `wrangler dev` for local development (not `node server.js` or any other runner).
- Test with `wrangler dev --remote` before deploying to catch binding resolution
issues that only appear against real Cloudflare infrastructure.
- Deploy with `wrangler deploy`. Never edit the production worker via the Cloudflare
dashboard directly — it diverges from the codebase.
- Bundle size must stay under 1 MB (compressed). Run `wrangler deploy --dry-run`
and check the reported bundle size before merging large dependency additions.
## TypeScript conventions
- Strict mode enabled. No `any`. Use `unknown` for untrusted external data and
narrow it with Zod or manual type guards before use.
- The `Env` interface must be in sync with `wrangler.toml`. If you add a binding
in `wrangler.toml`, add the corresponding property to `Env` in the same PR.
- Use `satisfies ExportedHandler<Env>` on the default export to catch binding
type mismatches at compile time.
## Definition of done
- `wrangler check` (or `tsc --noEmit`) passes with zero errors.
- `wrangler dev` starts without warnings.
- `wrangler deploy --dry-run` reports bundle size under 1 MB.
- No `process.env` references in source. No `node:*` imports unless compat flag is set.

Por que essas regras

  • 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.
  • 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.

Adequado para

  • APIs Cloudflare Workers, middleware de borda, roteadores Workers baseados em Hono, Workers com bindings D1/KV/R2.

Não adequado para

  • 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.