Next.js api route lose db connection in dev mode

Received mongo atlas connection reaching limit notification email when developing a React app in local environment. A quick guess is connection is not closed properly. Further investigation showes it’s coming from the disposed page lose connection and new request create a new connection each time. Also found similar issue in A solution is to save the connection in global state to be reused like below:

import mongoose from "mongoose";
let connection;
if (process.env.NODE_ENV === "development") {
  if (!global.connection) global.connection = {};
  connection = global.connection;
} else {
  connection = {};

async function connectDb() {
  if (connection.isConnected) {
    // Use existing database connection
    console.log("Using existing connection");
  // Use new database connection
  const db = await mongoose.connect(process.env.MONGO_SRV, {
    useCreateIndex: true,
    useFindAndModify: false,
    useNewUrlParser: true,
    useUnifiedTopology: true,
  console.log("DB Connected");
  connection.isConnected = db.connections[0].readyState;

export default connectDb;

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *