{
  "id": "ai-breaks-cloudflare-workers-runtime",
  "type": "failures",
  "category": "failures",
  "locale": "fr",
  "url": "/fr/failures/ai-breaks-cloudflare-workers-runtime",
  "title": "Comment résoudre le problème de l'IA qui casse l'environnement d'exécution de Cloudflare Workers",
  "description": "Les agents d'IA importent des modules intégrés Node.js comme fs, crypto et path dans Cloudflare Workers, ce qui provoque des erreurs d'exécution car l'environnement d'exécution de Workers n'est pas Node.js.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "security",
    "typescript"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "L'agent écrit du code qui fonctionne localement sous Node.js mais échoue au déploiement ou à l'exécution dans Cloudflare Workers, car l'environnement d'exécution de Workers est un isolat V8 — pas Node.js.\n\n## Le symptôme\n\nL'agent importe des modules intégrés Node.js ou des packages npm qui nécessitent en interne des API 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## Pourquoi cela se produit\n\nLa plupart des données d'entraînement des agents ciblent Node.js. Le modèle sait que `crypto`, `fs` et `path` fonctionnent pour le hachage, l'accès aux fichiers et la manipulation des chemins, donc il les utilise. Il ne distingue pas l'environnement d'exécution de Workers de Node.js sauf indication explicite.\n\n## Comment le repérer\n\n- `import ... from \"crypto\"` / `\"fs\"` / `\"path\"` / `\"http\"` / `\"stream\"` dans les fichiers Worker.\n- `wrangler dev` fonctionne mais `wrangler deploy` génère un avertissement de bundling concernant des modules Node.js non résolus.\n- La section des indicateurs de compatibilité Wrangler dans `wrangler.toml` est manquante ou utilise une date antérieure au `2022-11-30`.\n- Dépendances qui utilisent en interne `require(\"node:...\")` sans un shim de compatibilité Workers.\n\n## Comment le corriger\n\nUtilisez les API Web Standard — elles sont disponibles nativement dans 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 correction\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## Test\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```"
}