P PasteCode
Error

Cómo solucionar que la IA rompa el runtime de Cloudflare Workers

Los agentes de IA importan módulos integrados de Node.js como fs, crypto y path en Cloudflare Workers, lo que provoca errores de ejecución porque el runtime de Workers no es Node.js.

CursorClaude CodeCodexWindsurf CloudflareTypeScript
.md .json Actualizado 8 jun 2026

El agente escribe código que funciona localmente bajo Node.js pero falla al implementar o ejecutar en Cloudflare Workers porque el runtime de Workers es un aislado V8, no Node.js.

El síntoma

El agente importa módulos integrados de Node.js o paquetes npm que internamente requieren APIs de Node.js.

// 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 qué ocurre

La mayoría de los datos de entrenamiento de agentes están orientados a Node.js. El modelo sabe que crypto, fs y path funcionan para hash, acceso a archivos y manipulación de rutas, por lo que recurre a ellos. No distingue el runtime de Workers de Node.js a menos que se le indique explícitamente.

Cómo identificarlo

  • import ... from "crypto" / "fs" / "path" / "http" / "stream" en archivos del Worker.
  • wrangler dev funciona pero wrangler deploy lanza una advertencia de empaquetado sobre módulos de Node.js no resueltos.
  • La sección de indicadores de compatibilidad de Wrangler en wrangler.toml falta o usa una fecha anterior a 2022-11-30.
  • Dependencias que internamente usan require("node:...") sin un shim de compatibilidad para Workers.

Cómo solucionarlo

Utilice APIs web estándar — están disponibles de forma nativa en Workers.

// 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);
},
};
# wrangler.toml — enable Node.js compat shims for packages that need them
compatibility_date = "2024-09-23"
compatibility_flags = ["nodejs_compat"]
[ ] 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

Instrucción de corrección

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.

Prueba

Terminal window
# 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"