NextAuth集成MongoDBAdapter后Google登录报错求助
问题排查:NextAuth + MongoDBAdapter 导致Google登录失败
问题描述
- 原本Google登录功能正常,添加MongoDBAdapter配置后,终端抛出
MongoServerSelectionError、adapter_error_getuserbyaccount、oauth_callback_handler_error错误 - UI端Google弹出提示:“尝试使用其他账号登录”
- 已验证所有环境变量正确性;使用官网推荐的
@auth/mongodb-adapter导入路径,换成教程中的@next-auth/mongodb-adapter会触发新错误
相关代码
pages/index.js
import { useSession, signIn, signOut } from "next-auth/react" export default function Home() { const { data: session } = useSession() if (session) { return ( <> Signed in as {session.user.email} <br /> <button onClick={() => signOut()}>Sign out</button> </> ) } return ( <> Not signed in <br /> <button onClick={() => signIn('google')}>Sign in</button> </> ) }
pages/_app.js
import "@/styles/globals.css"; import { SessionProvider } from "next-auth/react" export default function App({ Component, pageProps: { session, ...pageProps }, }) { return ( <SessionProvider session={session}> <Component {...pageProps} /> </SessionProvider> ) }
lib/mongodb.js
// 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"'); } const uri = process.env.MONGODB_URI; const options = {}; let client; let clientPromise; 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;
pages/api/auth/[...nextauth].js
import NextAuth from "next-auth"; import { MongoDBAdapter } from "@auth/mongodb-adapter"; import GoogleProvider from "next-auth/providers/google"; import clientPromise from '@/lib/mongodb'; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET, }), ], adapter: MongoDBAdapter(clientPromise), // 问题触发行 });
排查解决方案
- 检查MongoDB连接权限:确认MONGODB_URI对应的数据库账号有读写权限,IP白名单是否包含当前开发环境的IP(本地开发可临时添加
0.0.0.0/0) - 验证MongoDB连接状态:在
lib/mongodb.js中添加连接日志,确认是否能成功连接MongoDB:// 修改client.connect部分 global._mongoClientPromise = client.connect() .then(() => { console.log("MongoDB连接成功"); return client; }) .catch(err => { console.error("MongoDB连接失败:", err); throw err; }); - 清理旧数据与会话:删除MongoDB中
users、accounts、sessions、verificationtokens集合,同时清除浏览器Cookie和缓存,避免旧会话冲突 - 确认版本兼容性:检查
package.json中next-auth与@auth/mongodb-adapter的版本是否匹配(NextAuth v4.23+需搭配@auth/mongodb-adapter) - 检查Google OAuth回调配置:确认Google Cloud的OAuth客户端中,授权回调URL包含
http://localhost:3000/api/auth/callback/google(本地开发),生产环境替换为对应域名 - 调整MongoDB连接选项:如果是MongoDB Atlas,尝试在连接选项中添加
{ useNewUrlParser: true, useUnifiedTopology: true }(部分旧版本依赖需要)
内容的提问来源于stack exchange,提问作者apex2022
相关产品推荐
相关产品推荐

