Connecting to MongoDB cluster from NextJS app hosted on Vercel

I am building a NextJS web app hosted on Vercel. One of my api routes contains the following code to connect to my cluster:

const {MongoClient} = require('mongodb');

// connect to client
const uri = process.env.URI
const client = await MongoClient.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true}) // this line hangs on Vercel

const companies = client.db("myDatabase").collection("companies");

// update document    
const updateDoc = {$set: set};
const result = await companies.updateOne(filter, updateDoc)
console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s): `, updateDoc);

// close connection to client    
await client.close();

This runs fine on localhost. However, when running on Vercel, the code hangs on the MongoClient.connect() line. There are no errors but the connection doesn’t resolve.

I have whitelisted all IP addresses in Network Access in Atlas (“Allow Access from anywhere”) as I’ve seen that Vercel does not have a particular IP address but still getting the same issue.

Any idea what could be causing the issue?

The code in general is correct - if you are using the 4.x driver you can remove the useNewUrlParser and userUnifiedTopology options from the connect call. I would double check the URI env variable is correct and that the function can actually reach the cluster. Also it’s usually best to cache the connected client in the initialization phase as we describe here: I’d also check the default timeout of the function and maybe it needs more time for the connection phase. Another thing to potentially help debug is to listen to the monitor heartbeats and see if there is a potential issue there.

const client = new MongoClient(uri);
client.on('serverHeartbeatStarted', (event) => {
client.on('serverHeartbeatSucceeded', (event) => {
client.on('serverHeartbeatFailed', (event) => {
await client.connect();

Hi @Durran_Jordan, thanks for your reply!

I’ve doubled checked the uri and it looks like this (with my username and password):


It’s the same uri I used from my localhost and I was able to connect fine from there so I don’t think that’d be the issue.

I’ve added the 3 monitor heartbeats listeners in my code. I get the following console logs:

ServerHeartbeatStartedEvent {
  connectionId: ''
ServerHeartbeatStartedEvent {
  connectionId: ''
ServerHeartbeatStartedEvent {
  connectionId: ''

I also sometimes see this error popping up:

2022-06-05T10:02:01.926Z	dc5eee5e-9613-42b7-8193-9035eaff8971	ERROR	MongoServerSelectionError: Server selection timed out after 30000 ms
    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:312:38)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      '' => [ServerDescription],
      '' => [ServerDescription],
      '' => [ServerDescription]
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-c5yrqw-shard-0',
    logicalSessionTimeoutMinutes: undefined

Does this Timeout message shed any light on the cause of the issue?

Many thanks for your help!

@Durran_Jordan are you able to help at all?

Since my last message, I’ve implemented the new Vercel integration but I’m experiencing the same issue. The MONGODB_URI produced automatically through the integration looks fine, but the connection hangs on await client.connect().

I’ve been stuck on this for months now and would really appreciate some help in identifying where the issue may come from!

Many thanks in advance!

Have you tried using this tutorial. [How to Integrate MongoDB Into Your Next.js App | MongoDB](https://How to Integrate MongoDB Into Your Next.js App) There is file that makes the connection to the atlas and makes the cache.

Good Luck.