I am trying to solve an issue that’s been happening to me for a little while now. Most of my database operations can be performed without any issues, but it seems like I am randomly getting MongoServerSelectionErrors
which cause my application to crash.
This is happening both in my local and production environment, and I haven’t found any way to reliably reproduce it.
I’m using
"mongodb": "^6.5.0",
"mongoose": "^8.3.1",
And for next-auth
I’m also using "@auth/mongodb-adapter": "^2.6.0"
(not sure if it could be related to this one)
Here is the entire error message taken from my Vercel logs:
Unhandled Rejection: MongoServerSelectionError: Server selection timed out after 30000 ms
at EventTarget.<anonymous> (/var/task/node_modules/.pnpm/[email protected]/node_modules/mongodb/lib/sdam/topology.js:289:34)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:786:20)
at EventTarget.dispatchEvent (node:internal/event_target:721:26)
at abortSignal (node:internal/abort_controller:369:10)
at TimeoutController.abort (node:internal/abort_controller:403:5)
at Timeout.<anonymous> (/var/task/node_modules/.pnpm/[email protected]/node_modules/mongodb/lib/utils.js:976:92)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-ygz1cvo-shard-00-00.frnyejo.mongodb.net:27017' => [ServerDescription],
'ac-ygz1cvo-shard-00-01.frnyejo.mongodb.net:27017' => [ServerDescription],
'ac-ygz1cvo-shard-00-02.frnyejo.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-k31dqm-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
My mongo config file:
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
const options = {};
let client;
let clientPromise;
if (!uri) {
console.error("⚠️ MONGODB_URI missing from .env");
} else {
try {
client = new MongoClient(uri, options);
clientPromise = client.connect();
} catch (err) {
console.error("MongoDB client error: " + err);
}
}
export default clientPromise;
And mongoose config file:
import mongoose from "mongoose";
let mongooseConnection = null;
const connectMongo = async () => {
if (mongooseConnection) {
return mongooseConnection;
}
if (!process.env.MONGODB_URI) {
throw new Error("MONGODB_URI is not defined");
}
try {
const db = await mongoose.connect(process.env.MONGODB_URI, {
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
heartbeatFrequencyMS: 10000,
});
mongooseConnection = db;
return db;
} catch (e) {
console.error("Mongoose connection error: " + e);
throw e;
}
};
export default connectMongo;
Also, here’s a screenshot from my Mongo Compass Monitoring tab
Has anyone had this issue and found a way to solve it?
I have tried changing parameters in the connection options, but without any success.