Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

How do I share a MongoDB connection across requests in Next.js?

clock icon

asked 1 month ago

message icon

2

eye icon

427

I keep hitting connection-pool exhaustion in development. Every time I save a file, a new Mongoose connection seems to be created.

1import mongoose from "mongoose"
2
3export async function connect() {
4 return mongoose.connect(process.env.MONGODB_URI!)
5}
1import mongoose from "mongoose"
2
3export async function connect() {
4 return mongoose.connect(process.env.MONGODB_URI!)
5}

In production this looks fine, but locally the connection count climbs until Atlas starts refusing new ones. What is the accepted pattern here?

2 Answers

The problem is hot reloading. Next.js re-evaluates the module on every save, so the module-level state is thrown away and a fresh connection is opened.

Cache the connection on globalThis, which survives module reloads:

1let cached = global.mongoose
2
3if (!cached) {
4 cached = global.mongoose = { conn: null, promise: null }
5}
6
7export async function dbConnect() {
8 if (cached.conn) return cached.conn
9
10 if (!cached.promise) {
11 cached.promise = mongoose.connect(process.env.MONGODB_URI!, {
12 dbName: "devflow",
13 })
14 }
15
16 cached.conn = await cached.promise
17 return cached.conn
18}
1let cached = global.mongoose
2
3if (!cached) {
4 cached = global.mongoose = { conn: null, promise: null }
5}
6
7export async function dbConnect() {
8 if (cached.conn) return cached.conn
9
10 if (!cached.promise) {
11 cached.promise = mongoose.connect(process.env.MONGODB_URI!, {
12 dbName: "devflow",
13 })
14 }
15
16 cached.conn = await cached.promise
17 return cached.conn
18}

Caching the promise as well as the connection matters — without it, concurrent requests during a cold start each kick off their own connect().

Adding to the above: set maxPoolSize explicitly. The driver default of 100 is far more than a serverless function needs, and on Atlas free tiers you will hit the cluster limit long before you hit the pool limit.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions