Next.js Discord

Discord Forum

Can't connect to DB inside Next.js middleware Mongoose

Answered
Netherland Dwarf posted this in #help-forum
Open in Discord
Netherland DwarfOP
Hello there, i'm trying to connect to my DB inside a Next.js middleware. Everything is working fine inside server components and api route handlers, it's only occuring when i'm trying to use it inside middleware.

I use this code for connection : https://github.com/vercel/next.js/blob/canary/examples/with-mongodb-mongoose/lib/dbConnect.js
And this one in the middleware :
export async function middleware(request: NextRequest) {
  await dbConnect();
}


Then when i'm triggering it i get this error :

- error src\db\connectToDb.js (62:60) @ connect
- error Cannot read properties of undefined (reading 'connect')
  60 |                     };
  61 |                     _a = cached;
> 62 |                     return [4 /*yield*/, mongoose_1.default.connect(DATABASE_URL, opts).then(function (mongoose) {
     |                                                            ^
  63 |                             return mongoose;
  64 |                         })];
  65 |                 case 1:


Github discussion here : https://github.com/Automattic/mongoose/discussions/13751
Answered by fuma
It's not recommended to connect to the database in a middleware since it's edge runtime by default.
And sometimes it can take more than 1 second to finish the query, so don't put it in middleware.

Using nodejs runtime instead should be able to fix the error. However, could I ask what is your intention? I believe there are definitely some better alternatives that you are looking for.
View full answer

10 Replies

It's not recommended to connect to the database in a middleware since it's edge runtime by default.
And sometimes it can take more than 1 second to finish the query, so don't put it in middleware.

Using nodejs runtime instead should be able to fix the error. However, could I ask what is your intention? I believe there are definitely some better alternatives that you are looking for.
Answer
it's just to avoid duplcation and to avoid a forgotten authenticate call
Like a classical authentication middleware in ExpressJS
Are you using Next.js as the backend (Don't have another backend)
If yes, just add a line of checkUser in your route handlers, or creating a wrapper for route handlers like export const POST = withAuth(req => ...)
Maybe it looks worse but you shouldn't have any database queries in middleware
@fuma Are you using Next.js as the backend (Don't have another backend)
Netherland DwarfOP
Yes this is the main backend.
Okay then, sad restriction for a middleware feature imo but np.
Thanks a lot for helping ❤️
Oh is it? I can't remember that, thanks for mentioning :BocchiHappy: