In my Express 4 API, I am using Passport.js for authentication. While most things are working fine, I have encountered difficulty in sending proper JSON responses such as error messages or objects with Passport. An example is the LocalStrategy used for logging in:
passport.use(
'login',
new LocalStrategy(
{
usernameField: 'email',
},
(email, password, done) => {
User.findOne({ email: email }, (err, foundUser) => {
if (err) return done(err);
if (!foundUser) {
return done(null, false, {
message: 'Invalid Username.',
});
}
if (!foundUser.comparePassword(password)) {
return done(null, false, {
message: 'Invalid Password.',
});
}
return done(null, foundUser);
});
})
);
Despite setting custom messages for authentication failure, these messages do not appear in my API responses. How can I send such messages when something goes wrong during authentication?
app.post(
'/signup',
passport.authenticate('signup', {
successRedirect: '/user',
failureMessage: true,
successMessage: true,
})
);
Furthermore, rather than setting redirects like successRedirect
, I aim to deliver proper JSON responses for each scenario. In case of an error, I want to send it as a JSON object instead of redirecting to a route. Is there a way to achieve this?