Skip to content

Instantly share code, notes, and snippets.

@skolhustick
Created December 28, 2021 14:01
Show Gist options
  • Save skolhustick/a4acf5f603c587b83109edbbd164f3e2 to your computer and use it in GitHub Desktop.
Save skolhustick/a4acf5f603c587b83109edbbd164f3e2 to your computer and use it in GitHub Desktop.
// lib/mongodb.js
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {
useUnifiedTopology: true,
useNewUrlParser: true
}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment