nextjs runtime_error ai_generated partial

Error: The edge runtime does not support Node.js 'X' module.

ID: nextjs/edge-function-cannot-access-node-module

Also available as: JSON · Markdown · 中文
75%Fix Rate
85%Confidence
1Evidence
2023-10-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Next.js 13.5 active
Next.js 14.0 active
Next.js 14.2 active
Next.js 15.0 active

Root Cause

A module or API route configured with 'runtime: edge' tries to import a Node.js built-in module (e.g., 'fs', 'crypto', 'path') that is not available in the Edge Runtime.

generic

中文

配置了 'runtime: edge' 的模块或 API 路由尝试导入 Edge Runtime 中不可用的 Node.js 内置模块(例如 'fs'、'crypto'、'path')。

Official Documentation

https://nextjs.org/docs/app/api-reference/edge

Workarounds

  1. 80% success Remove the Node.js module import and use Edge-compatible alternatives. For example, replace 'crypto' with the Web Crypto API: 'const key = await crypto.subtle.generateKey(...)'.
    Remove the Node.js module import and use Edge-compatible alternatives. For example, replace 'crypto' with the Web Crypto API: 'const key = await crypto.subtle.generateKey(...)'.
  2. 70% success Change the runtime to 'nodejs' in the route segment config: export const runtime = 'nodejs'; then keep the Node.js module import.
    Change the runtime to 'nodejs' in the route segment config: export const runtime = 'nodejs'; then keep the Node.js module import.
  3. 60% success Use dynamic imports with 'ssr: false' for the Node.js module inside a client component, but ensure the route is not edge-runtime.
    Use dynamic imports with 'ssr: false' for the Node.js module inside a client component, but ensure the route is not edge-runtime.

中文步骤

  1. 移除 Node.js 模块导入并使用边缘兼容的替代方案。例如,用 Web Crypto API 替换 'crypto':'const key = await crypto.subtle.generateKey(...)'。
  2. 在路由段配置中将运行时更改为 'nodejs':export const runtime = 'nodejs'; 然后保留 Node.js 模块导入。
  3. 在客户端组件中对 Node.js 模块使用带有 'ssr: false' 的动态导入,但确保路由不是边缘运行时。

Dead Ends

Common approaches that don't work:

  1. 90% fail

    'use client' does not change the runtime context; the edge runtime still blocks Node.js modules. The error persists because the module is loaded at build time or runtime.

  2. 70% fail

    Changing the runtime alone does not resolve the import issue; the module must be replaced or polyfilled. The error may change to a different module-related error.

  3. 60% fail

    Edge Runtime has a specific Web API subset; browser polyfills often use Node.js APIs internally and still fail. The polyfill may not be compatible with the edge sandbox.