Search code examples
node.jspassport.jspassport-localpassport-local-mongoose

How to add error/success messages in "log in logic" with Passport JS?


I would like to show flash messages of errors (username not exist, password not match...) and success (success messages after log in). This is my code:

router.post("/login", passport.authenticate("local", 
    {
        successRedirect: "/home",
        failureRedirect: "/login"
    }), (req, res) => {
});

I tried adding the flash messages after the CB something like this but doesn't work:

router.post("/login", passport.authenticate("local", 
    {
        successRedirect: "/home",
        failureRedirect: "/login"
    }), (req, res) => {

        req.flash("error", "message blablabla...");
        res.redirect("/login");
});

Need help with this :)


Solution

  • According to passport.js documentation you should be able to do something like this

    router.post("/login", passport.authenticate("local", 
        {
            successRedirect: "/home",
            failureRedirect: "/login",
            failureFlash: 'Invalid username or password.',
            successFlash: 'Welcome!' 
        }));