I'm using express + passport to handle authentication for a react app. Because I'm using react, I don't want to automatically redirect the login request via express, instead I want to return JSON.
However, I've noticed that simply returning JSON and then calling next(null, user) seems to prevent passport from running the serializeUser method. By calling next passport should automatically call the req.login function, which doesn't appear to happen when I've sent json.
It appears that if I manually call req.login and then send the JSON, it works (the serialize method is called, the user has a session).
Is there a way to send a json response and call next without having to manually invoke req.login? Feels like I'm just not doing things the correct way.
module.exports = function(app) {
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user) => {
if (err) {
res.json({ errorMessage: err.message });
return next(err);
}
if (!user) {
res.json({ errorMessage: 'Invalid user.' });
return next(err);
}
// This fails to invoke the session serialization:
// res.json({
// success: true,
// username: user.username
// });
// return next(null, user);
// This works:
req.logIn(user, loginErr => {
if (loginErr) {
return next(loginErr);
}
res.json({
success: true,
username: user.username
});
return;
});
})(req, res, next);
});
};