How to send flash messages in Express 4.0?

This Gist should answer your question:

https://gist.github.com/raddeus/11061808

in your application setup file:

app.use(flash());

Put that right after you set up your session and cookie parser. That’s really all you should need to use flash.

You are using:

req.flash('signupMessage', anyValue);

before redirecting to /signup right?

Here’s a fun little tidbit that I currently use for a personal site(in my main application file):

app.use(function(req, res, next){
    res.locals.success_messages = req.flash('success_messages');
    res.locals.error_messages = req.flash('error_messages');
    next();
});

Now every view will have access to any error or success messages that you flash. Works well for me.

One final thing (this is nitpicky but you may gain some knowledge). If you change:

<% if (message.length > 0) { %>

to:

<% if (message) { %>

It will work the same way but will not fail if message is undefined. undefined and empty strings are both considered “falsy” values in javascript.

EDIT: My cookie/session/flash setup goes as follows:

app.use(cookieParser('secretString'));
app.use(session({cookie: { maxAge: 60000 }}));
app.use(flash());

Maybe seeing your application setup code would help. Also note that using app.configure is no longer necessary in Express 4.

Final edit: https://gist.github.com/raddeus/11061808

That is a working example. Go to localhost:3000 after running that app and you should see ['it worked'] on your screen.

Leave a Comment