Table of Contents

Introduction

The connect-flash module in NodeJS allows developers to render a pop-up message whenever a user is redirected to a particular webpage. For example, in your Nodejs demo application, you want to notify your users on logging in and logging out. For that, you can use flash messages in NodeJs app with the help of the connect-flash module.

Prerequisites: Flash Messages in NodeJs

Before getting started with the development of our demo app let’s see what are the prerequisites-

  • Node.js and NPM installed
  • Fundamentals of NodeJS and its modules

Initialize the application

The first step would be creating package.json to initialize the project. For that, run the below command

Copy Text
npm init

Install dependencies

To implement flash messages in NodeJs with connect-flash module, you need to install the required dependencies using the command.

Copy Text
npm install connect-flash express express-session --save

Express: Required by the library connect-flash to run.

Express-session: to create a session whenever a message is flashed, so that the user can be redirected to a particular page.

Setting up index.js

Now, heading towards the coding part. Create a file named index.js. You can name it anything you want. Now, open the index.js file and import modules using the below code.

Copy Text
const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
  
const app = express();

Now, it’s time to get our hands on the logical part and implement it. Write the code in index.js file as shown below.

Copy Text
const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
  
const app = express();
  
const port = process.env.PORT || 3001;
  
app.use(session({
    secret:'flashblog',
    saveUninitialized: true,
    resave: true
}));
  
app.use(flash());
  
app.get('/', (req, res) => {
  req.flash('message', 'Welcome to Blog');
  res.redirect('/display-message');
});
  
app.get('/display-message', (req, res) => {
    res.send(req.flash('message'));
});
  
app.listen(port, (err) => {
  console.log('Server is up and listening on', port);
});

Explanation

  • Define a port number on which our demo application will run once you’re have imported the modules.
  • Define a session-secret to encrypt our sensitive information.
  • SaveUninitialized will refrain the browser from using empty sessions. Now, call the connect-flash module with the help of app.use(flash()).

Later define routes:

  • / – used for displaying the specified message and then later redirecting the user to /display-message route.
  • /display-message – used for showing the particular message on the web page.

Voila! We made our demo app to listen to the port.

Are you seeking to elevate your Node.js app’s user experience?
Look no further! As a leading Node.js development company, we specialize in crafting expert Flash Messages tailored to captivate your users. Get in touch today!

Run the application

Once done with the development part. Run the application by the following command and test the functionality.

Copy Text
node index.js

The browser will be redirected to the /display-message and it will show the following output.

Run the app

Display Flash Messages on the View File

Now we will display flash messages on the view file. For this, we need to use the ejs view engine. To install ejs run the below command.

Copy Text
npm install ejs

Open index.js and add below code

Copy Text
app.set('view engine', 'ejs');
 
app.use(function(req, res, next){
    res.locals.message = req.flash();
    next();
});

Create views folder on root of the application and create display.ejs in the same folder. Now render the view template (display.ejs) in display-message route using the below code.

Copy Text
app.get('/display-message', (req, res) => {
    res.render("display");
});

Once done, add the below line in views/index.js.

Copy Text
<%= message.success %>

To beautify the flash message we will use bootstrap css. Include bootstrap css file into view template and use the below code.

Copy Text
<link data-minify="1" href="https://www.bacancytechnology.com/blog/wp-content/cache/min/1/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css?ver=1732884284" rel="stylesheet" type="text/css" >
<% if(message.success){ %>
<div class="alert alert-success" role="alert">
    <%= message.success %>
</div>
<% } %>

Restart the node server and open http://localhost:3001/ in the browser.

The output will look something like this.

Display Flash Messages

Github Repository

Feel free to visit the source code: flash-messages-in-nodejs. You can clone the github repository and play around with the code as well.

Conclusion

I hope the quick guide was helpful to implement Flash messages in NodeJS using the connect-flash module. Are you a NodeJS enthusiast? If yes, then there’s an opportunity for you! Visit the NodeJS tutorials page and learn the basics and advanced of NodeJS.

Bacancy has dedicated and skilled developers who thoroughly go through the client’s requirements to meet the optimum solutions. In case, you are looking for a NodeJS developer who has sharp problem-solving instincts then contact us and hire Node developer.

Hire Node.js Developer

Connect Now

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?