In ExpressJS we can implement flash messages in HTTP redirects using a specific NPM module.
connect-flash is a module that actually helps us to add a feature already present in frameworks such as Laravel, that is the HTTP redirect with a message to show in the views.
This module is based on the sessions that we can create and manage with the module express-session. To use it in Express, we then create a session and then include the module as middleware.
'use strict';
const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
app.use(session({
secret: 'secret key',
resave: false,
saveUninitialized: false
}));
app.use(flash());
This middleware adds the flash()
method to the request
object. Used as a setter, we can set up a message like this.
app.get('/logout', (req, res) => {
req.flash('message', 'You are now logged out.');
res.redirect('/');
});
The message consists of a key (in the example it is message
) and a value. If you want you can add more values using an array.
req.flash('message', ['You are now logged out.', 'Login']);
So we can retrieve the message using the same method as getter passing the key as the only argument.
app.get('/', (req, res) => {
res.render('index', { message: req.flash('message') });
});
In the views we can show the message like this:
<% if (message) { %>
<div class="alert alert-info"><%= message %></div>
<% } %>
In conclusion, this module proves extremely effective to implement a very useful feature when doing HTTP redirects we and don't want to use a query string.