Unhandled Promise rejection: Vercel + MongoDB

My app https://mysticleads.com is hosted on vercel. It is using next + MongoDB node.js SDK and I am following this repo https://github.com/vercel/mongodb-starter/blob/main/lib/mongodb.ts

The issue is it giving me this error anytime a user “first” lands on the home page

2024-01-30T14:51:25.319Z ba64318f-9366-4bd2-a5e7-d81e884c3b88 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoServerSelectionError: connection timed out","reason":{"errorType":"MongoServerSelectionError","errorMessage":"connection timed out","reason":{"type":"ReplicaSetNoPrimary","servers":{},"stale":false,"compatible":true,"heartbeatFrequencyMS":10000,"localThresholdMS":15,"setName":"atlas-wwfy0e-shard-0","maxElectionId":null,"maxSetVersion":null,"commonWireVersion":0,"logicalSessionTimeoutMinutes":null},"stack":["MongoServerSelectionError: connection timed out"," at EventTarget.<anonymous> (/var/task/node_modules/mongodb/lib/sdam/topology.js:276:34)"," at [nodejs.internal.kHybridDispatch] (node:internal/event_target:757:20)"," at EventTarget.dispatchEvent (node:internal/event_target:692: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/mongodb/lib/utils.js:1011:92)"," at listOnTimeout (node:internal/timers:569:17)"," at process.processTimers (node:internal/timers:512:7)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: MongoServerSelectionError: connection timed out"," at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)"," at process.emit (node:events:529:35)"," at emit (node:internal/process/promises:149:20)"," at processPromiseRejections (node:internal/process/promises:283:27)"," at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}
[ERROR] [1706626285320] LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
Error: Runtime exited with error: exit status 128
Runtime.ExitError

I’ve added this line to the end of MongoDB uri which kinda improves the situation a little serverSelectionTimeoutMS=60000&readPreference=secondaryPreferred

But I am still getting straight 500 for new visitors.

Please HELP

Ask me if you need anything else.

Hi @Saswat_Singh,

Could you confirm if you can connect to the replica set via mongosh? Also, share the driver version, MongoDB server version, and where it is deployed, is it MongoDB Atlas or on-prem?

Bets regards,
Kushagra