MongoDB Atlas on Vercel: Serverless Connection Done Right
How I migrated the MCDARSENE Platform from static data to MongoDB Atlas on Vercel — and the attachDatabasePool trick that prevents connection leaks on cold starts.
import { attachDatabasePool } from "@vercel/functions";
const client = new MongoClient(uri, { maxIdleTimeMS: 5000 });
attachDatabasePool(client); // cleanup on suspension
The MCDARSENE Platform needed a real database for content management. Here's how I set up MongoDB Atlas on Vercel without burning through connections.
The problem with serverless databases
Serverless functions create a new client on every cold start. Without pooling, you hit MongoDB's connection limit fast.
The fix: attachDatabasePool
import { MongoClient } from "mongodb";
import { attachDatabasePool } from "@vercel/functions";const client = new MongoClient(process.env.MONGODB_URI, { appName: "portfolio", maxIdleTimeMS: 5000, });
attachDatabasePool(client); // cleanup on function suspension ```
Dual data source for resilience
The app falls back to static data if MongoDB is unavailable:
export function isMongoEnabled() {
return Boolean(process.env.MONGODB_URI);
}
Result
Content updates from the admin console now publish instantly to the landing page. No more redeploys for content changes.