I have an authentication route wired with PassportJS like this:
router.post('/',
passport.authenticate('local', { failureRedirect: '/' }),
async (req, res, next, done) => { // Middleware 1
console.log('FIRST MIDDLEWARE');
const { body: { remember_me, username } } = req;
// issue a remember me cookie if the option was checked
if (!remember_me) { return next(); }
const token = uuidv4();
const tokenEntry = await new Token({ token, userId: req.user.id }).save();
console.log('TOKEN ENTRY', tokenEntry);
return next();
},
(req, res) => { // Middleware 2
console.log('SECOND MIDDLEWARE');
res.cookie(process.env.USER_DATA_COOKIE, signedUserData(req), {
httpOnly: true,
secure: true,
});
res.json({ success: true });
});
But when run, the first console.log()
never executes. Why? Shouldn't it get called before the second one?
I think your passport.authenticate middleware calling direlctly done at the end of a function. So it will skip all the upcoming middlewares and directly runs your API callback function.
This answer will help you.