How to reuse MongoDB connection for multiple API routes? #12294
Unanswered
SergiiMost
asked this question in
Help
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
While using Express, one of the easy ways to reuse a MongoDB connection was to open a new connection when the Node.js application starts and attach it to
app.locals
. Something like this:/server.js
And then I can reuse this DB connection wherever i need :
const db = req.app.locals.db
So, how do I do it in Next.js without Express server? I don't think it's a good idea to just open MongoDB connections in every API route. There should be a good way to cache that connection and reuse it between API routes. I couldn't find a good explanation regarding my question. I would appreciate any help or clarification. Thank you!
Beta Was this translation helpful? Give feedback.
All reactions