Search code examples
node.jsexpresspassport.jspassport-local

How to flash a message from Passport.js?


I've created login and register with express and passport js. I want to add a message for wrong password or email.

in my index.js (main) added passport and body parser middleware with referring to the routes :

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// route files
let index = require("./routes/index");
let auth = require("./routes/auth");
app.use("/", index);
app.use("/auth", auth);

and I created passport configuration :

const LocalStrategy = require("passport-local").Strategy;
const User = require("../models/User");
const config = require("../config/database");
const bcrypt = require("bcryptjs");

module.exports = function(passport) {
  // Local Strategy
  passport.use(
    new LocalStrategy(
      {
        usernameField: "email",
        passwordField: "password"
      },
      (username, password, done) => {
        // Match Email
        let query = { email: username };
        User.findOne(query, function(err, user) {
          if (err) throw err;
          if (!user) {
            return done(null, false, { message: "No user found" });
          }

          // Match Password
          bcrypt.compare(password, user.password, function(err, isMatch) {
            if (err) throw err;
            if (isMatch) {
              return done(null, user);
            } else {
              return done(null, false, { message: "Wrong password" });
            }
          });
        });
      }
    )
  );

  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });
  });
};

also added a route for it :

// Login Process
router.post("/login", (req, res, next) => {
  passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/auth/login",

    failureFlash: true
  })(req, res, next);
});

the successRedirect and failureRedirect work fine, but it doesn't give me any error. I did it on a youtube video in the video it works but in my code it doesn't.

configuration of connect flash :

const flash = require("connect-flash");
app.use(require("connect-flash")());

Solution

  • Nothing wrong with your code, its just the version of express you are using. From the Passportjs Flash Message documentation,

    Note: Using flash messages requires a req.flash() function. Express 2.x provided this functionality, however it was removed from Express 3.x. Use of connect-flash middleware is recommended to provide this functionality when using Express 3.x.

    So you need to install connect-flash express middleware as it is recommended.

    var flash = require('connect-flash');
    var app = express();
    
    app.configure(function() {
      app.use(express.cookieParser('keyboard cat'));
      app.use(express.session({ cookie: { maxAge: 60000 }}));
      app.use(flash());
    });
    

    With the flash middleware in place, all requests will have a req.flash() function that can be used for flash messages.

    app.get('/flash', function(req, res){
      req.flash('info', 'Flash is back!')
      res.redirect('/');
    });
    
    app.get('/', function(req, res){
      res.render('index', { messages: req.flash('info') });
    });
    

    This might help you.