{
  "id": "ai-breaks-cloudflare-workers-runtime",
  "type": "failures",
  "category": "failures",
  "locale": "es",
  "url": "/es/failures/ai-breaks-cloudflare-workers-runtime",
  "title": "Cómo solucionar que la IA rompa el runtime de Cloudflare Workers",
  "description": "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.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "security",
    "typescript"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "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.\n\n## El síntoma\n\nEl agente importa módulos integrados de Node.js o paquetes npm que internamente requieren APIs de 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 qué ocurre\n\nLa 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.\n\n## Cómo identificarlo\n\n- `import ... from \"crypto\"` / `\"fs\"` / `\"path\"` / `\"http\"` / `\"stream\"` en archivos del Worker.\n- `wrangler dev` funciona pero `wrangler deploy` lanza una advertencia de empaquetado sobre módulos de Node.js no resueltos.\n- La sección de indicadores de compatibilidad de Wrangler en `wrangler.toml` falta o usa una fecha anterior a `2022-11-30`.\n- Dependencias que internamente usan `require(\"node:...\")` sin un shim de compatibilidad para Workers.\n\n## Cómo solucionarlo\n\nUtilice APIs web estándar — están disponibles de forma nativa en 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## Instrucción de corrección\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## Prueba\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```"
}