MongoDB returns 502 error in Vercel hosted app

1.2k views Asked by At

I'm building a web app in next.js and hosting it on Vercel. I have set up a database cluster in MongoDB Atlas, which I can connect to in development (from localhost) and from MongoDB compass, but when I deploy it to Vercel, client.connect() gives me an HTTP 502 error.

Is there any reason why I can connect from localhost but not from my Vercel-deployed app? My connection string is mongodb+srv://<username>:<password>@testcluster.i2ddc.mongodb.net/data?retryWrites=true&w=majority as per the connection instructions on the Atlas dashboard.

1

There are 1 answers

0
semperlabs On BEST ANSWER

Have you added Vercel ip to whitelist on Network Access configuration in MongoDb dashboard? You can try to add middleware to connect, and catch any error. I would also try without "retryWrites=true" in the connection string.

Middleware

import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

export default async function database(req, res, next) {
  if (!client.isConnected()) await client.connect();
  req.dbClient = client;
  req.db = client.db(process.env.DB_NAME);
  await setUpDb(req.db);
  return next();
}

You just need to set up environmental variables. This tutorial could be useful