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

NextAuth(v5)+MongoDB适配Credentials Provider遇Edge运行时错误

NextAuth v5 + MongoDB适配器 触发Edge Runtime不支持Node.js 'stream'模块错误

环境信息

  • Node.js版本:v20.11.0
  • 依赖:NextAuth v5、@auth/mongodb-adapter、MongoDB官方mongodb包

错误内容

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

相关代码

auth.ts

import NextAuth from 'next-auth'
import authConfig from '@/auth.config'
import {MongoDBAdapter} from '@auth/mongodb-adapter'
import clientPromise from './app/lib/auth.mongoClient'
import type {Adapter} from '@auth/core/adapters'

export const {
  handlers: { GET, POST },
    auth,
    signIn,
    signOut,
} = NextAuth({
  adapter: <Adapter>MongoDBAdapter(clientPromise),
  session: {strategy : "jwt"},
  ...authConfig,
  
})

auth.config.ts

import type { NextAuthConfig } from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
import { LoginSchema } from './zodSchemas'
import clientPromise from './app/lib/auth.mongoClient'


export default {
  providers: [
    Credentials({
      async authorize(credentials) {

        const validatedFields = LoginSchema.safeParse(credentials)

        if(validatedFields.success){
          const user = credentials.user
          const password = credentials.password

          const database = (await clientPromise).db()
          const users = database.collection('users')

          // TO DO --> find user in database and check password

        }

      },
    }),
  ],
} satisfies NextAuthConfig

auth.mongoClient.ts

// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient } from "mongodb"

if (!process.env.MONGODB_URI) {
  throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
}
declare global {
    var _mongoClientPromise: Promise<MongoClient>;
  }
  
const uri = process.env.MONGODB_URI
const options = { }

let client
let clientPromise: Promise<MongoClient>

if (process.env.NODE_ENV === "development") {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise

问题原因与解决方法

原因

NextAuth v5默认启用Edge Runtime,但MongoDB官方的MongoClient依赖Node.js专属核心模块(比如stream),这些模块在Edge Runtime环境下无法被加载,因此触发错误。

解决步骤

  1. 强制指定Node.js Runtime:在auth.ts文件顶部添加一行代码,明确告诉Next.js使用Node.js运行时:
export const runtime = "nodejs";
  1. 按需调整适配器使用:如果你配置了session: {strategy: "jwt"},JWT策略本身不需要数据库存储会话,若暂时不需要适配器处理其他Auth逻辑(如账号关联、第三方登录数据存储),可以先移除adapter配置,减少依赖冲突。
  2. 确保数据库调用在Node环境执行:auth.config.ts中authorize函数里的MongoDB操作会随Auth路由的运行时环境执行,因此只要Auth路由使用Node.js Runtime,这部分代码就能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:17:50