{
  "id": "ai-breaks-cloudflare-workers-runtime",
  "type": "failures",
  "category": "failures",
  "locale": "pt",
  "url": "/pt/failures/ai-breaks-cloudflare-workers-runtime",
  "title": "Como Corrigir a Quebra do Runtime do Cloudflare Workers pela IA",
  "description": "Agentes de IA importam módulos embutidos do Node.js como fs, crypto e path para o Cloudflare Workers, causando erros em tempo de execução porque o runtime do Workers não é Node.js.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "security",
    "typescript"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "O agente escreve código que funciona localmente com Node.js, mas falha ao fazer deploy ou em tempo de execução no Cloudflare Workers porque o runtime do Workers é um isolado V8 — não Node.js.\n\n## O sintoma\n\nO agente importa módulos embutidos do Node.js ou pacotes npm que internamente requerem APIs do Node.js.\n\n```ts\n// worker.ts — WRONG\nimport { createHash } from \"crypto\";          // Node built-in — not available\nimport { readFileSync } from \"fs\";            // Node built-in — not available\nimport { resolve } from \"path\";              // Node built-in — not available\nimport { IncomingMessage } from \"http\";      // Node built-in — not available\n\nexport default {\n  async fetch(request: Request, env: Env) {\n    const hash = createHash(\"sha256\").update(\"data\").digest(\"hex\");\n    return new Response(hash);\n  },\n};\n// Error at runtime: Cannot read properties of undefined (reading 'createHash')\n```\n\n## Por que isso acontece\n\nA maioria dos dados de treinamento do agente tem como alvo o Node.js. O modelo sabe que `crypto`, `fs` e `path` funcionam para hash, acesso a arquivos e manipulação de caminhos, então ele os utiliza. Ele não distingue o runtime do Workers do Node.js a menos que seja explicitamente instruído.\n\n## Como identificar\n\n- `import ... from \"crypto\"` / `\"fs\"` / `\"path\"` / `\"http\"` / `\"stream\"` em arquivos Worker.\n- `wrangler dev` funciona, mas `wrangler deploy` lança um aviso de empacotamento sobre módulos Node.js não resolvidos.\n- A seção de flags de compatibilidade do Wrangler em `wrangler.toml` está ausente ou usa uma data anterior a `2022-11-30`.\n- Dependências que internamente usam `require(\"node:...\")` sem um shim de compatibilidade do Workers.\n\n## Como corrigir\n\nUse APIs Web Standard — elas estão disponíveis nativamente no Workers.\n\n```ts\n// worker.ts — CORRECT\nexport default {\n  async fetch(request: Request, env: Env) {\n    // Web Crypto API — standard, available in Workers\n    const encoder = new TextEncoder();\n    const data = encoder.encode(\"data\");\n    const hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n    const hashArray = Array.from(new Uint8Array(hashBuffer));\n    const hash = hashArray.map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n    return new Response(hash);\n  },\n};\n```\n\n```toml\n# wrangler.toml — enable Node.js compat shims for packages that need them\ncompatibility_date = \"2024-09-23\"\ncompatibility_flags = [\"nodejs_compat\"]\n```\n\n```txt\n[ ] No imports from \"crypto\", \"fs\", \"path\", \"http\", \"stream\", \"os\", \"buffer\" (use node: prefix + nodejs_compat flag if unavoidable)\n[ ] Use crypto.subtle for hashing/signing (Web Crypto API)\n[ ] Use env bindings (KV, R2, D1) instead of fs for storage\n[ ] Set compatibility_date to a recent date in wrangler.toml\n[ ] Add nodejs_compat flag only for third-party packages that require it\n[ ] Run \"wrangler deploy --dry-run\" to catch bundling errors before deploying\n```\n\n## Prompt de Correção\n\n```txt title=\"Fix Prompt\"\nThis code imports Node.js built-in modules (crypto, fs, path, http) that are\nnot available in the Cloudflare Workers runtime. Rewrite it using Web Standard\nAPIs: crypto.subtle for hashing/encryption, the Fetch API for HTTP, and\nCloudflare bindings (KV, R2, D1) for storage. If a third-party dependency\nrequires Node.js APIs, add nodejs_compat to compatibility_flags in wrangler.toml\nand note that in a comment.\n```\n\n## Teste\n\n```bash\n# Dry-run deploy to catch Node.js module errors\nwrangler deploy --dry-run --outdir dist 2>&1 | grep -i \"error\\|unresolved\\|node:\" && echo \"FAIL\" || echo \"OK\"\n\n# Check for raw Node built-in imports\ngrep -rn '^import.*from \"(crypto|fs|path|http|stream|os)\"' src/ \\\n  && echo \"FAIL: Node.js built-in import found\" || echo \"OK\"\n```"
}