Jakub S.
Jakub S.

Reputation: 628

How to create flash messages in Express/NodeJS?

This question has been asked a million times already, but I never really understood the answers and when I did, they did not suit my specific needs.

I currently have flash messages implemented using this:

app.use(function(req, res, next){    
  res.locals.sessionFlash = req.session.sessionFlash;
  delete req.session.sessionFlash;
  next();
});

And when I want to use the message in a route, I have to explicitly recall it like this:

res.render('...', {
    sessionFlash: res.locals.sessionFlash
});

Is there a simpler way to do this (preferably one where I would not need to pull the messages from the session manually)?

Upvotes: 1

Views: 691

Answers (1)

Bamieh
Bamieh

Reputation: 10936

This behavior is used by big frameworks such as sails.js

you can see code here: https://github.com/balderdashy/sails/blob/0506f0681590dc92986985bc39609c88b718a997/lib/router/res.js

you can achieve it in various ways, but these are the simplest.

1: overriding

you can override the function through "middlewares"

app.use( function( req, res, next ) {
    // grab reference of render
    var _render = res.render;
    // override logic
    res.render = function( view, options, fn ) {
        // do some custom logic
        _.extend( options, {session: true} );
        // continue with original render
        _render.call( this, view, options, fn );
    }
    next();
} );

I took this snippet from: https://stackoverflow.com/a/24051339/5384679 you can replicate without lodash etc.

2: wrapping render in a new function

make your own function to wrap the session flashMessage, you can use this to your advantage, i used some es6 syntax out of laziness, but could be replaced easily by es5 code.

res.sendView = function(path, options) {
  this.render(path, {
     sessionFlash: res.locals.sessionFlash,
     ...options
  });
}
// now you can use res.sendView instead of res.render.

Upvotes: 1

Related Questions