How to flash a message in Nodejs-Express-EJS app

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.set("view engine", "ejs");
  secret: 'secret'
app.get('/', function(reqres){
  req.flash('notify', 'This is a test notification')

app.get('/redirect', function(reqres){
  req.flash('notify', 'Redirect successful!')

app.listen(3000,()=>{console.log('listening to 3000');})

In the above example we declares a middle ware using


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.


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>
        <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">
    <div class="container">
       <% const m=getMessages() %>
       <% if (m.notify) { %>
        <% m.notify.forEach((element=> { %>
        <%= element %>
        <% }) %>
       <% } %>



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 %>

View complete source code

Other EJS posts

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.