When I run my web app, which doesn’t use any framework, and I make a GET database call it breaks in every possible way. When I run it locally everything is good but as soon as I try to use Vercel it all breaks. Sometimes even the UI breaks showing the same errors.
I keep getting the same issue over and over. Even though in my MongoDB whitelist, I have made it so every IP can access it I am still getting the issue. I can make POST requests to my database, but any GET requests I make fail somehow.
I have even used an integration so Vercel is now integrated in MongoDB Atlas but it still doesn’t work.
The code I use to connect to the db:
require('dotenv').config();
const { MongoClient, ServerApiVersion } = require('mongodb');
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
await mongoose.connection.db.admin().command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} catch (err) {
console.log(err);
}
}
connectDB();
Here’s the code I use as Middleware:
const sessionMiddleware = session({
name: 'session',
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
cookie: {
maxAge: 24 * 60 * 60 * 1000, // 24 hours session expiration
secure: process.env.ENV === 'PROD', // Use secure cookies in production (HTTPS)
sameSite: 'Lax',
httpOnly: true // Prevent client-side JS from accessing the cookie
},
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI, // Your MongoDB connection string
collectionName: 'sessions', // Optional, specify a custom collection to store sessions
ttl: 24 * 60 * 60, // Optional, set session TTL (expiration) in seconds (24 hours)
autoRemove: 'native', // Optional, automatically remove expired sessions
mongoOptions: {
socketTimeoutMS: 60000, // Adjust as needed (e.g., 60 seconds)
connectTimeoutMS: 30000 // Adjust as needed (e.g., 30 seconds)
}
})
});
Here are the two errors I get most often:
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/
at _handleConnectionErrors (/var/task/node_modules/mongoose/lib/connection.js:909:11)
at NativeConnection.openUri (/var/task/node_modules/mongoose/lib/connection.js:860:11)
at runNextTicks (node:internal/process/task_queues:60:5)
at listOnTimeout (node:internal/timers:545:9)
at process.processTimers (node:internal/timers:519:7)
at async connectDB (/var/task/config/db.js:8:9) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-74jwl2r-shard-00-01.3n1qqxt.mongodb.net:27017' => [ServerDescription],
'ac-74jwl2r-shard-00-02.3n1qqxt.mongodb.net:27017' => [ServerDescription],
'ac-74jwl2r-shard-00-00.3n1qqxt.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-us7z8p-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}
Unhandled Rejection: MongoServerSelectionError: Server selection timed out after 30000 ms
at Topology.selectServer (/var/task/node_modules/mongodb/lib/sdam/topology.js:303:38)
at runNextTicks (node:internal/process/task_queues:60:5)
at listOnTimeout (node:internal/timers:545:9)
at process.processTimers (node:internal/timers:519:7)
at async Topology._connect (/var/task/node_modules/mongodb/lib/sdam/topology.js:196:28)
at async Topology.connect (/var/task/node_modules/mongodb/lib/sdam/topology.js:158:13)
at async topologyConnect (/var/task/node_modules/mongodb/lib/mongo_client.js:209:17)
at async MongoClient._connect (/var/task/node_modules/mongodb/lib/mongo_client.js:222:13)
at async MongoClient.connect (/var/task/node_modules/mongodb/lib/mongo_client.js:147:13)
at async MongoClient.connect (/var/task/node_modules/mongodb/lib/mongo_client.js:308:16) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-74jwl2r-shard-00-01.3n1qqxt.mongodb.net:27017' => [ServerDescription],
'ac-74jwl2r-shard-00-02.3n1qqxt.mongodb.net:27017' => [ServerDescription],
'ac-74jwl2r-shard-00-00.3n1qqxt.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-us7z8p-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
{}
}
Node.js process exited with exit status: 128. The logs above can help with debugging the issue.