Search code examples
javascriptnode.jsexpresssessionflash-message

express-flash messages are empty after refresh


The express-flash module does not work correctly. When I add a message, it's empty on the next page refresh.

This is a part of my app.js:

var flash = require('express-flash');
var session = require('express-session');
app.use(session({
  secret: 'keyboard ctrl',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 }
}))
app.use(flash());
app.get( '/', login);

And this is in my login module

exports.login = function(req, res){
    console.log(req.flash('error'));
    req.flash('error','Test errors!');
    res.render('user_login');
};

The log output is always an empty array when I refresh the page multiple times.


Solution

  • express-flash extends connect-flash so you don't require a redirect (or a new page load) before the flash messages are available.

    It does so by patching res.render() to retrieve all flash messages, so they become available as messages inside your templates.

    However, after retrieving all flash messages, the list of messages will be emptied, because it is assumed that when they are retrieved, they are used. That's how connect-flash works.

    So after calling res.render in your login handler, the list of messages will be empty.

    Having a list of flash messages persist across page reloads isn't trivial to implement, because you have to determine if something is a reload or a "normal" page load.