I am using the relatively newer setup with Next.js API routes, this doesn't use express but instead the API setup to create your routes to an endpoint.
My problem is I'd like to have a route called api/user which will return the user i.e. req.user:
The following comes from with-passport-and-next-connect
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
if (req.session.user) {
const { _id } = req.session.user
res.json({ user: { _id } })
} else {
res.json({ user: null })
}
})
export default handler
That file references this auth file:
import nextConnect from 'next-connect'
import passport from '../lib/passport'
import session from '../lib/session'
const auth = nextConnect()
.use(
session({
name: 'sess',
secret: process.env.TOKEN_SECRET,
cookie: {
maxAge: 60 * 60 * 8, // 8 hours,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
},
})
)
.use((req, res, next) => {
// Initialize mocked database
// Remove this after you add your own database
req.session.users = req.session.users || []
next()
})
.use(passport.initialize())
.use(passport.session())
export default auth
I have added this in my version:
.use((req, res, next) => {
connectDB()
next()
})
But that yields nothing.
In api/login I added this line
req.session.user = req.user;
after the authenticate function. But that doesn’t add the user to the session object.
handler
.use(auth)
.post((req, res, next) => {
emailValidator(req, res, next, 'email', 'password');
},
async (req, res, next) => {
await connectDB();
passport.authenticate('local', (err, user, info) => {
req.session.user = req.user;
Could anyone please help me with this?
Thanks in advance.