非本地网络下NextAuth出现MongoServerSelectionError问题求助
问题:NextAuth认证功能因MongoServerSelectionError失效
开发NextAuth项目时,不在本地网络环境下认证功能会触发MongoServerSelectionError。回到家中并为当前IP开放网络权限后,该错误仍持续出现。错误日志指向SSL相关问题,但对SSL配置完全不熟悉,需要简单可行的修复方案。
代码文件
lib/mongodb.ts
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: Promise<MongoClient>; if (process.env.NODE_ENV === "development") { // 开发模式下使用全局变量,避免HMR导致模块重载时重复创建连接 const globalWithMongo = global as typeof globalThis & { _mongoClientPromise?: Promise<MongoClient>; }; if (!globalWithMongo._mongoClientPromise) { client = new MongoClient(uri, options); globalWithMongo._mongoClientPromise = client.connect(); } clientPromise = globalWithMongo._mongoClientPromise; } else { // 生产模式下不使用全局变量 client = new MongoClient(uri, options); clientPromise = client.connect(); } export default clientPromise;
api/auth/[...nextAuth].ts
/* eslint-disable @typescript-eslint/no-unused-vars */ import NextAuth from "next-auth"; import GithubProvider from "next-auth/providers/github"; import { MongoDBAdapter } from "@auth/mongodb-adapter"; import clientPromise from "@/app/lib/mongodb"; const handler = NextAuth({ providers: [ GithubProvider({ clientId: process.env.GITHUB_ID!, clientSecret: process.env.GITHUB_SECRET!, }), ], adapter: MongoDBAdapter(clientPromise, { databaseName: "db1", collections: { Users: "users", }, }), callbacks: { async signIn({ user, account, profile }) { return true; }, async session({ session, user }) { return session; }, }, }); export { handler as GET, handler as POST };
错误日志
[next-auth][error][adapter_error_getUserByAccount] 40B81BEE01000000:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1590:SSL alert number 80 { message: '40B81BEE01000000:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1590:SSL alert number 80\n', stack: 'MongoServerSelectionError: 40B81BEE01000000:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1590:SSL alert number 80\n' + '\n' + ' at Topology.selectServer (/Users/garrett/Documents/[03] Code/reformify/node_modules/mongodb/lib/sdam/topology.js:303:38)\n' + ' at async Topology._connect (/Users/garrett/Documents/[03] Code/reformify/node_modules/mongodb/lib/sdam/topology.js:196:28)\n' + ' at async Topology.connect (/Users/garrett/Documents/[03] Code/reformify/node_modules/mongodb/lib/sdam/topology.js:158:13)\n' + ' at async topologyConnect (/Users/garrett/Documents/[03] Code/reformify/node_modules/mongodb/lib/mongo_client.js:223:17)\n' + ' at async MongoClient._connect (/Users/garrett/Documents/[03] Code/reformify/node_modules/mongodb/lib/mongo_client.js:236:13)\n' + ' at async MongoClient.connect (/Users/garrett/Documents/[03] Code/reformify/node_modules/mongodb/lib/mongo_client.js:161:13)', name: 'MongoServerSelectionError' } [next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 40B81BEE01000000:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1590:SSL alert number 80 Error [GetUserByAccountError]: 40B81BEE01000000:error:0A000438:SSL routines:ssl3_read_bytes:tlsv1 alert internal error:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1590:SSL alert number 80 at Topology.selectServer (node_modules/mongodb/src/sdam/topology.ts:610:29) at async Topology._connect (node_modules/mongodb/src/sdam/topology.ts:463:21) at async Topology.connect (node_modules/mongodb/src/sdam/topology.ts:410:6) at async topologyConnect (node_modules/mongodb/src/mongo_client.ts:596:8) at async MongoClient._connect (node_modules/mongodb/src/mongo_client.ts:608:6) at async MongoClient.connect (node_modules/mongodb/src/mongo_client.ts:520:6) { code: undefined }
修复方案
针对SSL连接导致的错误,直接修改MongoDB客户端配置即可,以下是两种简单的修复方式:
方式1:强制启用SSL并跳过验证(仅开发环境临时使用)
修改lib/mongodb.ts中的options对象:
const options = { ssl: true, sslValidate: false };
这种方式会跳过SSL证书验证,快速解决开发环境的连接问题,但不建议在生产环境使用。
方式2:使用正确的SSL证书验证(生产环境推荐)
如果你的MongoDB服务(比如MongoDB Atlas)提供了CA证书,下载证书后,修改配置:
import fs from "fs"; const options = { ssl: true, sslValidate: true, sslCA: fs.readFileSync("/path/to/your-ca-certificate.pem") };
替换/path/to/your-ca-certificate.pem为实际的证书文件路径。
额外检查
确认你的MONGODB_URI连接字符串中是否包含ssl=true参数,通常MongoDB Atlas生成的连接字符串默认已经包含该参数,如果没有,可以手动添加到URI末尾:?ssl=true。
修改完成后,重启开发服务器,重新测试认证流程即可。
内容的提问来源于stack exchange,提问作者garrett
相关产品推荐
相关产品推荐

