Connections not closed with nextJS

Hello,
I like to discuss abot this article. I have tested this article, and all working, BUT this article has really big issue with MongoDB connections.
When we use the code described in database.js - the code if (!client.isConnected()) await client.connect(); will trigger every time database.js called. Consequently, we will have a every time new connection that will NOT be closed after DB call. It means we can easily reach 500-1000 open connections (picture).
Some help for this issue I have found inside NEXTJS documentation, but it can’t solve my problem. I have already created a lot of API paths called middleware.
Do you have any suggestions to modify database.js to close the connection after the call triggered?
Thanks a lot

Hey @Il_Chi,

We have an updated guide that has better practices for handling MongoDB connections in a much more efficient way. You can read the article here: How to Integrate MongoDB Into Your Next.js App or view the preferred utility file here: next.js/mongodb.js at canary · vercel/next.js · GitHub. This will work much better.

Please give it a try and let me know if you experience further issues :slight_smile:

2 Likes

According to your reply and article, you are using const { db } = await connectToDatabase(); It’s ok, but my problem is I have already created a lot of stuff with API using nextConnect(). Will share my solution below!
Thanks for fast reply!

Ablout code below: using cached for serverless nextjs API calls

import nextConnect from 'next-connect';
import { MongoClient } from 'mongodb';

const mongoClient = new MongoClient(process.env.mongoApiUrl, {

  useNewUrlParser: true,

  useUnifiedTopology: true,

});

//with serverless we need to use cache to prevent re-opening connection

let cached = global.mongo

if (!cached) {

  cached = global.mongo = { conn: null, promise: null }

}

async function database(req, res, next) {

  if (!cached.promise) {

    cached.promise = mongoClient.connect().then((client) => {

      return {

        client,

        db: client.db(process.env.MONGODB_DB),

      }

    })

    cached.conn = await cached.promise

  }

  req.dbClient = cached.conn.client

  req.db = cached.conn.db

  return next();

}

const middleware = nextConnect();

middleware.use(database);

export default middleware;

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.