Repository navigation
Can't connect to DB inside Next.js middleware #13751
Replies: 1 comment
|
This is not a Mongoose connection bug. Next.js middleware runs on the Edge runtime, not on Node.
The official Do not open a Mongo connection in middleware. Keep middleware to JWT / cookie checks, then load the user in a Node handler: // middleware.ts — no mongoose
export async function middleware(request: NextRequest) {
const token = request.cookies.get('token')?.value
if (!token) {
return NextResponse.redirect(new URL('/login', request.url))
}
// verify JWT only (an Edge-compatible lib such as `jose`)
return NextResponse.next()
}
export const config = { matcher: ['/dashboard/:path*'] }// app/api/me/route.ts — Node, mongoose is fine here
import dbConnect from '@/lib/dbConnect'
import User from '@/models/User'
export async function GET() {
await dbConnect()
const user = await User.findOne({ /* from the verified token */ }).lean()
return Response.json(user)
}If you truly need Node APIs in front of every request, use a Node Docs: Next.js middleware and Edge vs Node. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
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 :
Then when i'm triggering it i get this error :
All reactions