使用 Node.js 作为 Next.js 中间件的运行时
· 阅读需 1 分钟
在 Next.js 中,如果你在中间件使用了 Node.js 的 API, 那么可能会产生以下报错
Error: The edge runtime does not support Node.js 'crypto' module.
解决方法如下:
-
安装
next@canary -
在
next.config.ts中添加以下配置import { NextConfig } from "next"
const nextConfig: NextConfig = {
experimental: {
nodeMiddleware: true,
},
}
export default nextConfig -
在
middleware.ts中添加以下配置export const runtime = "nodejs"
当然,最好的做法是不使用 Node.js 作为中间件的运行时,而是使用 Edge 作为中间件的运行时,尽量使用 Edge 的 API 来实现中间件的功能。