This is a Next.js demo app that connects to MongoDB using the native driver and caches the connection using globalThis — perfect for avoiding connection overloads in serverless environments like Vercel.
✅ Built for developers hitting the "too many connections" issue when deploying MongoDB-backed apps on Next.js.
- Uses
globalThisto cache MongoDB connections across function invocations - Prevents re-connecting on every API call
- Great for local dev with hot module reloading (HMR)
- Vercel-ready — handles cold starts and minimizes connection bursts
git clone https://github.com/your-username/next-mongo-globalthis-demo.git
cd next-mongo-globalthis-demoCreate a .env.local file:
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority&maxPoolSize=10npm installnpm run devVisit:
http://localhost:3000/api/pingAnd check your terminal logs — you should see one of:
🌱 New MongoDB client created (dev)
✅ Reusing existing MongoDB client (dev)-
Push your project to GitHub
-
Import it to Vercel
-
Add your
MONGODB_URIin Vercel's Environment Variables settings -
Deploy!
You can view your function logs in the Vercel dashboard (under Functions > Logs) to confirm caching behavior:
-
Cold start logs will show:
🚀 Creating MongoDB client (prod/serverless) -
Reused logs may not show anything (depending on platform re-use)
globalThis is the modern, cross-platform way to store and reuse variables across:
- Browser vs Node.js
- Serverless cold vs warm starts
- Local dev with hot reload
It ensures the MongoDB connection (or promise) sticks around as long as the instance lives, preventing new connections on every API hit.