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.
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
You just need to set up environmental variables. This tutorial could be useful