Passport.js authenticate() custom callback and failureFlash behavior
0 reputation · 10 Aug 2020, 18:47 UTC
0 reputation · 10 Aug 2020, 18:47 UTC
In Passport.js (v0.6.x–v0.7.x), the passport.authenticate() middleware allows for a custom callback to handle the authentication result manually. When utilizing the default middleware behavior, providing failureFlash: true in the options object automatically populates req.flash() with the message returned by the strategy.
There is a discrepancy when transitioning to a custom callback. While the options object can still be passed, the automated flash behavior appears to be bypassed. This requires a decision on whether the application should manually extract the message from the info object or if there is a configuration that allows the internal flash logic to execute alongside a custom callback.
failureFlash and successFlash logic?Yes, providing a custom callback to passport.authenticate() completely overrides the built-in failureFlash and successFlash logic. The options object is still accepted, but the flash flags are ignored. There is no configuration flag to re-enable automatic flash messaging while keeping a custom callback.
In Passport.js v0.6–0.7, the authentication middleware treats a custom callback as a full takeover of the response flow. When the middleware detects a function as the last argument, it executes the strategy and immediately invokes your callback with (err, user, info, status), then returns. The internal code path that reads failureFlash/successFlash and calls req.flash() is never reached.
info object passed to your callback contains the strategy's message (typically { message: 'Invalid credentials' }).passport-local populate info.message on both failure and success.req.flash() manually inside the callback.app.post('/login',
passport.authenticate('local', { failureFlash: true }, (err, user, info) => {
if (err) return next(err);
if (!user) {
// Manual flash using the strategy's message
req.flash('error', info?.message);
return res.redirect('/login');
}
req.logIn(user, (loginErr) => {
if (loginErr) return next(loginErr);
// Optional success flash
req.flash('success', info?.message || 'Welcome back!');
return res.redirect('/dashboard');
});
})
);
Ensure connect-flash (or express-flash) middleware is mounted before passport.initialize():
app.use(require('connect-flash')());
app.use(passport.initialize());
app.use(passport.session());
If you are seeing req.flash is not a function inside the callback, confirm that flash middleware is installed and ordered correctly. That is the only setup issue that changes the recommendation.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.