Flash Messages in Nodejs: Ultimate Guide Using The connect-flash Module

Flash Messages In Nodejs Featured Image

This one is an interesting tutorial on displaying flash messages in Nodejs applications. We will be using the connect-flash module to facilitate this feature.

I will be using a few packages and will explain to you on the go, what they’re used for. This will be a simple yet detailed step-by-step guide on generating flash messages in Nodejs.

What is the connect-flash Module?

The connect-flash module in Nodejs enables developers to display or render pop messages every time a user is redirected to a certain page. Let’s say for example you created a productivity app that lets users add or remove tasks in a to-do list. Now you want to notify the user whenever the user removes or adds tasks. Or, when a user logs in or logs out!

Exciting right? Why don’t we actually check it out!

Let’s get started with a mini-application to help you get a better understanding.

Using connect-flash to Display Flash Messages in Nodejs

To get going, we will first create a Nodejs project and then install the required packages in it.

Create a new folder or directory for your project and initiate your Node app in it:

$ npm init -y

Your package.json should now be created and look like this:

{
  "name": "7_FLASH_NODEJS_APP",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Create the .js file:

$ touch app.js

Install all the required packages:

$ npm i express connect-flash express-session ejs

I am using Express.js as the server framework for my mini-application in this tutorial.

The express-session module will help create a session each time a user is redirected to a certain page and a message is flashed.

We are using EJS as our HTML templating engine so we can serve better-looking web pages of our application. However, EJS will play its role in the second part of this post where I will be customizing the flash messages.

If you do not understand what EJS is, what it does, and how it works, click here to read this post on using EJS Template Engine in Nodejs. If you have prior knowledge about EJS, you’re good to go!

Next, set up your app.js file and import all the modules that we just installed:

const express = require('express');
const session = require('express-session');
const flash = require('connect-flash');
const path = require('path');

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

const port = 8000;

app.use(session({
    secret: 'codeforgeek',
    saveUninitialized: true,
    resave: true
}));

app.use(flash());

app.listen(port, (err) => {
    console.log(`App is running on port ${port}`);
});

These lines make sure that the ‘views’ folder is accessible globally:

const path = require('path');
app.set('views', path.join(__dirname, 'views'));

If you don’t get what the path module does, click here to read about it!

Now that we have set the basics of our application, let us move on to implementing connect-flash and creating routes for our users.

Let’s create two routes and two templates for those routes.

app.get('/', (req, res) => {
    req.flash('success', `You've been successfully redirected to the Message route!`)
    res.redirect('/message')
})

app.get('/message', (req, res) => {
    res.send(req.flash('success'))
})

In the above code snippet, I have created a home route that redirects to the message route when requested. I have also assigned a success flash message on the home route which will be displayed on the message route on successful redirection.

The req.flash() in the home route, accepts two string values as arguments. The first string defines the type of flash message you want to render, and the second string accepts the actual flash message. Although defining a type for your flash messages doesn’t change the way they look, it is good for reference for you or other developers reading your code later.

However, you could pass many types of flash messages you like but then the redirected page trying to render your flash message shouldn’t clash with similar types. This is why you should keep each of the type names unique.

For example, you can’t have two error-type flash messages in Nodejs. Your code is likely to break or behave unexpectedly when the redirected page, here the message route, tries to render that flash message and finds there more than one entry of the same type.

The message route is where the flash message of your choice is called. We defined a success type flash message and are calling that same flash message on the message route by simply passing req.flash(‘success’).

Now, whenever a user is redirected to the message route, he/she will receive a flash message saying “You’ve been successfully redirected to the Message route!”.

Let’s run our app and from your browser, go to http://localhost:8000/

Flash Messages In Nodejs Message Route

This way we can successfully render any flash messages in Nodejs.

Conclusion

Today’s is a quite interesting tutorial on displaying flash messages in Nodejs applications. This is a simple yet detailed step-by-step guide for beginners on generating flash messages in Nodejs.

Stay tuned for a sequel to this post on customizing your flash messages for users.