Creating simple blog with Node.js: flash messages

One way to give user feedback is to use the flash messages, after certain action you display information. Example user deletes the post and is redirected to main page, now display the information if all were successful or not.

To make use of the flash messages you need to add the cookieParser

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.logger());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'wasdsafeAD' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

This is the way to add information to flash messages, you can acces the object by req.flash().

if (!err) {
  req.flash('info', 'Post has been sucessfully edited');
}

To use it in all the view so I would not have to pass the flash object into every render function, is to register helper.

app.dynamicHelpers({
...
  flash: function(req, res) {
    return req.flash();
  }
});

Also i have added into layout.jade before header partial !=partial(‘alert’, flash) and in view partial is the message look.

mixin showAlert(alerts)
    for alert in alerts
      div #{alert}

- if (flash.info)
  div.alert.alert-info
    mixin showAlert(flash.info)

- if (flash.success)
  div.alert.alert-success
    mixin showAlert(flash.success)

- if (flash.error)
  div.alert.alert-error
    mixin showAlert(flash.error)