Snorflake Snorflake - 6 months ago 30
Node.js Question

How can I delete flash messages once a page has loaded using express?

So I was using express.js under node.js and came across this question. I have a login page where if you get a password/username wrong it will flash a message (Basic stuff using passport). But if you keep trying, the other error messages will stack (Only 1 of each, but they're still there after they're not relevant).

Is there a way i can delete the flash messages once they've been displayed? I'm using this flash.

Here's what I've tried so far:

router.get("/login", function(req, res){
res.render("login");
res.locals.flash = [];
});


and my post req

router.post("/login", passport.authenticate(
"local",
{
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}
));

Answer

I suggest you use the connect-flash package, with this one you can do smtg like this :

app.post('/login', function(req, res){
  // if credentials are wrong
  req.flash('msg', 'Try again !')
  res.redirect('/login');
});

app.get('/login', function(req, res){
  res.render('login', { message : req.flash('msg') });
});

In the views, you just need to check for message existence and output it , with ejs it would be smtg like this :

<% if(message){ %> 
  <%= message %>
<% } %>

package:connect-flash