Hey guys, I’m currently trying to integrate Mongoose into a Next project. I have seen the official integration guide, but I would prefer not to import the db connection in every single file and call await dbConnection
everywhere.
Using the middleware with runtime: 'nodejs'
seems like a nice solution, but I would have to use the canary release (to be able to use the nodejs runtime on middlware). Checking the docs I found the instrumentation
file, and it has the following:
This function will be called once when a new Next.js server instance is initiated.
Sometimes, it may be useful to import a file in your code because of the side effects it will cause.`
So I was thinking that I could have something like this:
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
await mongoose.connect(MONGODB_URI)
}
}
I know this is not the right place to initialize a db, but can it technically work? Should I completely discard this idea and just use the Middleware approach or the official approach?