Recently delving into Nextjs, I'm currently in the process of setting up a MongoDB connection using middleware configuration.
Let me showcase my code:
import type { NextApiRequest, NextApiResponse } from 'next'
import { connectMongoDB } from '../../middlewares/connect-db'
const handler = (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const { login, pwd } = req.body
if (login === '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a4b4e4743446a4b4e47434404494547">[email protected]</a>' && pwd === 'Admin@123') {
res.status(200).json({ message: 'Successfully logged in!' })
}
return res.status(400).json({ error: 'Failed to log in.' })
}
return res.status(405).json({ error: 'Unsupported Method' })
}
export default connectMongoDB(handler)
Let's take a look at the middleware/connect-db
code:
import type { NextApiRequest, NextApiHandler, NextApiResponse } from 'next'
import mongoose from 'mongoose'
export const connectMongoDB = (handler: NextApiHandler) => {
;async (req: NextApiRequest, res: NextApiResponse) => {
//check connection
if (mongoose.connections[0].readyState) {
return handler(req, res)
}
const { DB_CONNECTION_STRING } = process.env
if (!DB_CONNECTION_STRING) {
return res.status(500).json({ error: 'DB Connection Error' })
}
mongoose.connection.on('connected', () =>
console.log('DB Connection established')
)
mongoose.connection.on('error', () => console.log('DB Connection Error'))
await mongoose.connect(DB_CONNECTION_STRING)
return handler(req, res)
}
}
This is how my project structure looks like:
The function export was working fine before. Not sure why it's throwing errors now.
Thanks for any help in advance.
Even after renaming functions and verifying the DB_CONNECTION_STRING
, the issue persists even after app restarts.