跳到主要内容

1 篇博文 含有标签「middleware」

查看所有标签

使用 Node.js 作为 Next.js 中间件的运行时

· 阅读需 1 分钟
1adybug
子虚伊人

Next.js 中,如果你在中间件使用了 Node.jsAPI, 那么可能会产生以下报错

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

解决方法如下:

  1. 安装 next@canary

  2. next.config.ts 中添加以下配置

    import { NextConfig } from "next"

    const nextConfig: NextConfig = {
    experimental: {
    nodeMiddleware: true,
    },
    }

    export default nextConfig
  3. middleware.ts 中添加以下配置

    export const runtime = "nodejs"

当然,最好的做法是不使用 Node.js 作为中间件的运行时,而是使用 Edge 作为中间件的运行时,尽量使用 Edge 的 API 来实现中间件的功能。