Next.js issue with multiple unclosed connections

I was following this post How to Integrate MongoDB Into Your Next.js App by @ado and noticed that if you make a bunch of requests through your Next.js Api Routes in dev mode (eg yarn dev) and then stop dev mode (eg ctrl+c) - you can see in the MongoDB logs that it releases a tonne of connections. Somewhere along the way the connections aren’t closing after each request and are just staying active until you stop Next.js

@ado did you notice anything like this yourself?

PS: I also noticed that your connectToDatabase function waits for the promise to complete before caching, which means that if you call this rapidly multiple times you will end up with more than one connection. Here is my revisted version:

import { MongoClient } from 'mongodb'

let uri = process.env.MONGO_URI
let dbName = process.env.MONGO_DB

let promise = null
let cached = null

if (!uri) throw new Error('Missing environment variable MONGO_URI')
if (!dbName) throw new Error('Missing environment variable MONGO_DB')

export async function connectToDatabase() {
  if (cached) return cached
  if (!promise) {
    promise = MongoClient.connect(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
  }
  const client = await promise
  const db = await client.db(dbName)
  cached = {
    client,
    db,
  }
  return cached
}

It looks like these guys are having the same issues: https://github.com/vercel/next.js/discussions/12229

Hi Ash,

Thank you for reaching out. I have not experienced the issue personally, but looking at the linked discussion it seems others are experiencing it as well. Let me do a little bit of digging to see if I can figure out what is going on and maybe get some guidance from the Vercel guys on how to best handle this.

In your revised code, are you seeing the results you’d expect or is it still creating too many connections?

Thanks,
Ado

1 Like

Hi Ado,

The revised code prevents a situation where if you call connectToDatabase() a second time (or more) before the first one has cached, it results in another MongoClient being created and overwritten as the cached version.

That said, the connection issue still exists, i just wanted to rule that out.