NEXT JS
June 3, 2026 1 min read

How to Create a MongoDB Connection in Next.js: Step-by-Step Guide

HS
HEMANT SINGH
Technical Writer & Educator
import {MongoClient} from "mongodb"
const uri="mongodb+srv://capscom:password@cluster0.hwmwcdy.mongodb.net/?retryWrites=true&w=majority"
let client;
let clientPromise;

const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

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