Message flash allow us to pass a message to client side of Node-Express web app. Suppose a user search for a product and you need to show message ( for example : we found 2 result matching your search ). For this flash functionality will be a great help.
A middle ware required for this.To add the flashing functionality in Nodejs-Express app we have to do the following
- Create session
- Use a middle-ware
- Set message
- Render the message in EJS template
There are few npm libraries available for flashing message , but I will choose the express-flash-messages.
Install the package
Let’s add the module to your project dependencies using
npm i express-flash-messages --save
Express app setup
const session = require('express-session') const express=require('express') const flash=require('express-flash-messages') app=express() app.use(flash()); app.set("view engine", "ejs"); app.use(session({ secret: 'secret' })) app.get('/', function(req, res){ req.flash('notify', 'This is a test notification') res.render('index') }) app.get('/redirect', function(req, res){ req.flash('notify', 'Redirect successful!') res.redirect('/') }) app.listen(3000,()=>{console.log('listening to 3000');})
In the above example we declares a middle ware using
app.use(flash());
also created a session which is required for the middle ware and then set our flash messages using req (req.flash())object.
We have two routes,one for default route and other for redirection. Both of the routes have flash message too.
Rendering
We are using a EJS view engine for templating. Flash message rendering depends on template engine. Let’s have a look at our EJS template
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Flash Message</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <h1>Express-Flash</h1> <h4></h4> </head> <body> <div class="container"> <% const m=getMessages() %> <% if (m.notify) { %> <% m.notify.forEach((element) => { %> <%= element %> <% }) %> <% } %> </div> </body> </html>
Using the getMessage() we can fetch all flashed messages and loop through the collection. Note that we do not pass any parameter in the rendering .
= is used for rendering the value in <%= element %>
Other EJS posts
- How to use css in Nodejs-Express project - Learn how to use CSS/Bootstrap in Express-EJS templates
- Reusable partial EJS-templates in Express - Learn how to build web/static-blog app with Express and EJS reusable /partial templating system
- How to flash a message in Nodejs-Express-EJS app - How to add a message-flashing in a Nodejs-Express app and render the flashed messages in EJS template