# Como Corrigir a Quebra do Runtime do Cloudflare Workers pela IA

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

**Type:** Failure  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Cloudflare, TypeScript  
**Updated:** 2026-06-08

---

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.

## O sintoma

O agente importa módulos embutidos do Node.js ou pacotes npm que internamente requerem APIs do Node.js.

```ts
// worker.ts — WRONG
import { createHash } from "crypto";          // Node built-in — not available
import { readFileSync } from "fs";            // Node built-in — not available
import { resolve } from "path";              // Node built-in — not available
import { IncomingMessage } from "http";      // Node built-in — not available

export default {
  async fetch(request: Request, env: Env) {
    const hash = createHash("sha256").update("data").digest("hex");
    return new Response(hash);
  },
};
// Error at runtime: Cannot read properties of undefined (reading 'createHash')
```

## Por que isso acontece

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

## Como identificar

- `import ... from "crypto"` / `"fs"` / `"path"` / `"http"` / `"stream"` em arquivos Worker.
- `wrangler dev` funciona, mas `wrangler deploy` lança um aviso de empacotamento sobre módulos Node.js não resolvidos.
- A seção de flags de compatibilidade do Wrangler em `wrangler.toml` está ausente ou usa uma data anterior a `2022-11-30`.
- Dependências que internamente usam `require("node:...")` sem um shim de compatibilidade do Workers.

## Como corrigir

Use APIs Web Standard — elas estão disponíveis nativamente no Workers.

```ts
// worker.ts — CORRECT
export default {
  async fetch(request: Request, env: Env) {
    // Web Crypto API — standard, available in Workers
    const encoder = new TextEncoder();
    const data = encoder.encode("data");
    const hashBuffer = await crypto.subtle.digest("SHA-256", data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hash = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
    return new Response(hash);
  },
};
```

```toml
# wrangler.toml — enable Node.js compat shims for packages that need them
compatibility_date = "2024-09-23"
compatibility_flags = ["nodejs_compat"]
```

```txt
[ ] No imports from "crypto", "fs", "path", "http", "stream", "os", "buffer" (use node: prefix + nodejs_compat flag if unavoidable)
[ ] Use crypto.subtle for hashing/signing (Web Crypto API)
[ ] Use env bindings (KV, R2, D1) instead of fs for storage
[ ] Set compatibility_date to a recent date in wrangler.toml
[ ] Add nodejs_compat flag only for third-party packages that require it
[ ] Run "wrangler deploy --dry-run" to catch bundling errors before deploying
```

## Prompt de Correção

```txt title="Fix Prompt"
This code imports Node.js built-in modules (crypto, fs, path, http) that are
not available in the Cloudflare Workers runtime. Rewrite it using Web Standard
APIs: crypto.subtle for hashing/encryption, the Fetch API for HTTP, and
Cloudflare bindings (KV, R2, D1) for storage. If a third-party dependency
requires Node.js APIs, add nodejs_compat to compatibility_flags in wrangler.toml
and note that in a comment.
```

## Teste

```bash
# Dry-run deploy to catch Node.js module errors
wrangler deploy --dry-run --outdir dist 2>&1 | grep -i "error\|unresolved\|node:" && echo "FAIL" || echo "OK"

# Check for raw Node built-in imports
grep -rn '^import.*from "(crypto|fs|path|http|stream|os)"' src/ \
  && echo "FAIL: Node.js built-in import found" || echo "OK"
```