I'm new to Nextjs and i'm trying to setup a MongoDB connection through a middleware config.
Here is 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 === '[email protected]' && 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)
Here is 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 stablished')
)
mongoose.connection.on('error', () => console.log('DB Connection Error'))
await mongoose.connect(DB_CONNECTION_STRING)
return handler(req, res)
}
}
Here is my project structure:
It worked when I exported de handler function as default. I'm not sure why it is not accepting my export now.
Ty in advance.
I've tried to rename functions, triple checked my DB_CONNECTION_STRING
and restarted the app at every change.
The problem stems from the definition of connectMongoDB()
. You defined an arrow function in connectMongoDB()
but you never output this arrow function. It will output void
as a result and the subroutine that will use the export is not expecting void
. [1]
One solution would be to assign the arrow function to a variable and return it after:
export const connectMongoDB = (handler: NextApiHandler) => {
let connect = async (req: NextApiRequest, res: NextApiResponse) => {
•••Rest of code•••
}
return connect
}
[1] One nit: You have an unexpected token ;
.