I recently started creating serverless functions in Vercel that connected to MongoDB.
After playing around with the application I discovered in the MongoDB metrics I had ramped up a whopping 200 connections.
A quick google search and I found this link defining the best practices when connecting MongoDB to Vercel .
Unfortunately it was written in vanilla JS but I rewrote it into TypeScript.
Any issues - Give me a shout, otherwise you're welcome 😊
'use strict'; // Import the dependency. import { MongoClient, MongoClientOptions } from 'mongodb'; const uri = process.env.MONGODB_URI!; const options = { useUnifiedTopology: true, useNewUrlParser: true, } as MongoClientOptions; let client; let clientPromise: Promise<MongoClient>; const globalWithMongoClientPromise = global as typeof globalThis & { _mongoClientPromise: Promise<MongoClient>; }; if (process.env.NODE_ENV === 'development') { // In development mode, use a global variable so that the value // is preserved across module reloads caused by HMR (hot module replacement). if (!globalWithMongoClientPromise._mongoClientPromise) { client = new MongoClient(uri!, options); globalWithMongoClientPromise._mongoClientPromise = client.connect(); } clientPromise = globalWithMongoClientPromise._mongoClientPromise as Promise<MongoClient>; } else { // In production mode, it's best to not use a global variable. client = new MongoClient(uri!, options); clientPromise = client.connect(); } // Export a module-scoped MongoClient promise. By doing this in a // separate module, the client can be shared across functions. export default clientPromise;
You use the client in the same way as the original post.
You may also need to add
// eslintrc.json "@typescript-eslint/no-non-null-assertion": "off"