You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决切换Turbopack后出现的crypto.getRandomValues()不支持问题?

解决方案:Turbopack + NextAuth 出现 crypto.getRandomValues() 不支持错误
  • 方案一:添加crypto polyfill(推荐)
    在项目根目录的next.config.js中添加Turbopack的别名配置,指定crypto的polyfill:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      experimental: {
        turbo: {
          resolveAlias: {
            'crypto': 'crypto-browserify',
          },
        },
      },
    }
    
    module.exports = nextConfig
    

    然后安装对应的依赖包:

    npm install crypto-browserify --save-dev
    # 或者用yarn
    yarn add crypto-browserify -D
    
  • 方案二:临时降级uuid版本
    如果你不想配置polyfill,可以暂时降级uuid到不依赖crypto.getRandomValues()的旧版本,比如v3.4.0:

    npm install uuid@3.4.0
    

    注意:这个方案只是临时 workaround,旧版本uuid可能存在安全隐患,不建议长期使用。

  • 方案三:自定义NextAuth的JWT生成逻辑
    绕过uuid的默认实现,自己写JWT的编码逻辑,用Node.js原生的crypto.randomBytes生成随机值:
    首先安装jsonwebtoken依赖:

    npm install jsonwebtoken
    

    然后在pages/api/auth/[...nextauth].js中修改配置:

    import NextAuth from "next-auth"
    import CredentialsProvider from "next-auth/providers/credentials"
    import { randomBytes } from 'crypto'
    import jwt from 'jsonwebtoken'
    
    export default NextAuth({
      providers: [
        // 这里保留你的认证提供者配置
        CredentialsProvider({
          name: "Credentials",
          credentials: {
            username: { label: "Username", type: "text" },
            password: { label: "Password", type: "password" }
          },
          async authorize(credentials, req) {
            // 替换成你的实际认证逻辑
            const user = { id: 1, name: "Test User" }
            return user
          }
        })
      ],
      session: {
        strategy: "jwt",
      },
      jwt: {
        async encode({ secret, token }) {
          // 生成自定义JWT ID
          const jti = randomBytes(16).toString('hex')
          // 用jsonwebtoken生成JWT
          return jwt.sign({ ...token, jti }, secret, { expiresIn: '1d' })
        },
        async decode({ secret, token }) {
          // 对应解码逻辑
          return jwt.verify(token, secret)
        }
      },
    })
    

内容的提问来源于stack exchange,提问作者Nazar Duma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 04:34:54