错误:边缘运行时不支持 Node.js 'X' 模块。
Error: The edge runtime does not support Node.js 'X' module.
ID: nextjs/edge-function-cannot-access-node-module
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 13.5 | active | — | — | — |
| Next.js 14.0 | active | — | — | — |
| Next.js 14.2 | active | — | — | — |
| Next.js 15.0 | active | — | — | — |
根因分析
配置了 'runtime: edge' 的模块或 API 路由尝试导入 Edge Runtime 中不可用的 Node.js 内置模块(例如 'fs'、'crypto'、'path')。
English
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.
官方文档
https://nextjs.org/docs/app/api-reference/edge解决方案
-
移除 Node.js 模块导入并使用边缘兼容的替代方案。例如,用 Web Crypto API 替换 'crypto':'const key = await crypto.subtle.generateKey(...)'。
-
在路由段配置中将运行时更改为 'nodejs':export const runtime = 'nodejs'; 然后保留 Node.js 模块导入。
-
在客户端组件中对 Node.js 模块使用带有 'ssr: false' 的动态导入,但确保路由不是边缘运行时。
无效尝试
常见但无效的做法:
-
90% 失败
'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.
-
70% 失败
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.
-
60% 失败
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.