Flash messaging in Express 4: express-flash vs. custom middleware in ejs, handlebars, or jade

Flash Messages

Flash messaging in Express can be confusing to the newcomer. I know because I am a newcomer. The confusion tends to arise from the distinction between the concept of flash messaging, a temporary message from the server available to templates, and the various implementations of flash messaging, which include express-flash and other modules. This Gist provides a minimal example of 2 approaches to flash messaging, the express-flash module and custom middleware, using 3 common templating engines.

The express-flash module exposes getter and setter methods for a flash message of the form, { flash: { type: 'type', message: 'message' }} and depends on the express-session module. The method req.flash(type, message) sets the value of a new flash message and adds it to an array of messages of the same type. The method req.flash(type) gets the value of all flash messages matching of the same type and returns either a string value for the message if there is only 1 of that type, or an array of string values for messages matching that type. The flash messages have a lifetime of one request and are deleted afterward.

The custom middleware is lifted with modifications from Ethan Brown’s excellent book, Web Development with Node & Express, and depends on the express-session module. In it, res.locals.sessionFlash acts as a the getter and req.session.sessionFlash acts as the setter for messages with a lifetime of one request. As in the express-flash module, these flashes take the form, { type: 'type', message: 'message' }, but only do so to follow established convention. They could as easily take the form, { class: 'class', intro: 'intro', text: 'text' } and be exposed via res.locals.myFlashMessages and req.session.myFlashMessages.

There are a couple of important distinctions between the 2 approaches illustrated above.

First, the custom middleware option exposes all of the properties of the flash object, not just the message. So sessionFlash.type and sessionFlash.message are both available to the templates above just by including the sessionFlash value, whereas the expressFlash message type would have to have been explicitly specified in app.js and passed as a separate value, ie expressFlashType, to the template.

Second, the custom middleware does not include a mechanism for adding multiple messages of the same type to an array. As it is written, res.locals.sessionFlash and req.session.sessionFlash are single occupancy variables.

Of note, res.locals.flash and req.session.flash can be used in the custom middleware above, but I chose different targets to avoid collision with the express-flash messages.

Both approaches offer simple mechanisms for passing temporary messages to the browser. Which one of the many options you choose depends on your needs. I hope this has been helpful.