nextjs runtime_error ai_generated true

错误:Edge 运行时不支持 Node.js API 'X'。请使用 'edge-runtime' 兼容的 API。

Error: The Edge Runtime does not support Node.js API 'X'. Use 'edge-runtime' compatible APIs.

ID: nextjs/middleware-edge-runtime-node-api

其他格式: JSON · Markdown 中文 · English
95%修复率
90%置信度
1证据数
2023-09-15首次发现

版本兼容性

版本状态引入弃用备注
[email protected] active
[email protected] active
[email protected] active

根因分析

Next.js 中间件在 Edge 运行时上运行,与 Node.js 相比 API 有限。使用 Node.js 特定模块如 'fs'、'path' 或 'crypto'(没有 Web Crypto)会抛出此错误。

English

Middleware in Next.js runs on the Edge Runtime, which has a limited set of APIs compared to Node.js. Using Node.js-specific modules like 'fs', 'path', or 'crypto' (without Web Crypto) throws this error.

generic

官方文档

https://nextjs.org/docs/app/building-your-application/routing/middleware#runtime

解决方案

  1. 将依赖 Node.js 的逻辑移出中间件,放入单独的 API 路由或服务器组件中。
  2. 使用 Edge 运行时中可用的 Web API,例如 Web Crypto(crypto.subtle)替代 Node.js crypto。

无效尝试

常见但无效的做法:

  1. 95% 失败

    The Edge Runtime does not have a file system; any import of 'fs' will fail at runtime.

  2. 90% 失败

    Dynamic imports also run on the Edge Runtime and are blocked; they don't fall back to Node.js.