Guide to Send Flash Messages using Nodejs

Agarwal Peeyush
4 min readAug 18, 2023

--

Photo by Gabriel Heinzer on Unsplash

Absolutely, here’s a comprehensive guide on how to implement flash messages in a Node.js web application. Flash messages are quick notifications that are frequently used to show consumers feedback or alerts after specific actions. For this, we’ll make use of the Express.js framework and the express-flash middleware.

Implementing Flash Messages in a Nodejs Web Application

Prerequisites:

  1. Node.js Installation: Ensure you have Node.js installed on your machine. You can download it from https://nodejs.org/.

2. Express.js Installation: If you don’t have Express.js installed, you can install it in your project directory using the following command:

npm install express

3. Basic Understanding of Express.js: This guide assumes you have a basic understanding of how to set up a web application using Express.js.

Setting Up the Project:

  1. Create a New Directory for Your Project: Create a new directory for your project and navigate to it in your terminal:
mkdir flash-messages-example
cd flash-messages-example

2. Initialize a New Node.js Project: Run the following command to initialize a new Node.js project and create a package.json file:

npm init --yes or npm init --y

3. Install Express.js: Install Express.js as a local dependency in your project:

npm install express or npm i express

4. Create the Project Structure: Create a new directory named views and another directory named public. Inside the public directory, create a css folder and place a CSS file named styles.css in it. Your project structure should look like this:

flash-messages-example/
├── node_modules/
├── public/
│ └── css/
│ └── styles.css
├── views/
└── package.json

Writing the Code:

  1. Create an Express Application: Create a file named app.js in your project directory and add the following code:
const express = require('express');
const app = express();

// Set up middleware and routes here

const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

2. Set Up the Middleware: In the app.js file, add the following middleware to set up Express.js, including serving static files and configuring the express-flash middleware:

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

app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));

// Configure session and flash middleware
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
app.use(flash());

// Set up routes here

const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Note: You need to run the following command to install the dependencies:

npm install express-flash or npm i express-flash
npm install express-sessionor npm i express-session

3. Create Routes: Create a directory named routes in your project directory. Inside the routes directory, create a file named index.js and add the following code:

const express = require('express');
const router = express.Router();

// Route to display the index page
router.get('/', (req, res) => {
res.render('index');
});

router.get('/show-message', (req, res) => {
req.flash('info', 'Flash Message Added');
res.redirect('/show-flash-message');
})

router.get('/show-flash-message', (req, res) => {
res.render('index', { messages: req.flash('info') });
})

module.exports = router;

4. Create Views: Inside the views directory, create a file named index.ejs and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/styles.css">
<title>Flash Messages Example</title>
</head>
<body>
<h1>Flash Messages Example</h1>

<% if (messages.length > 0) { %>
<div class="flash-messages">
<% messages.forEach(message => { %>
<div class="flash-message">
<%= message %>
</div>
<% }); %>
</div>
<% } %>

<a href="/show-message">Show Flash Message</a>
</body>
</html>

5. Create CSS Styling: Inside the public/css directory, create a file named styles.css and add the following CSS to style the flash messages:

body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}

h1 {
margin-top: 20px;
}

.flash-messages {
margin-top: 20px;
}

.flash-message {
background-color: #dff0d8;
color: #3c763d;
padding: 10px;
border-radius: 5px;
margin: 10px auto;
width: 300px;
}

6. Define Routes in app.js: In the app.js file, require the index.js route and define the route to show the flash message:

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

app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));

app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
app.use(flash());

// Require the routes
const indexRoute = require('./routes/index');

// Use the routes
app.use('/', indexRoute);

const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

6. Set default engine in app.js: In the app.js file, add the following code to serve static files:

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

app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
app.use(flash());

app.set('view engine', 'ejs');

// Require the routes
const indexRoute = require('./routes/index');

// Use the routes
app.use('/', indexRoute);

const PORT = process.env.PORT || 9000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Running the Application:

  1. In your terminal, run the following command to start your Node.js server:
node app.js

2. Open your web browser and navigate to http://localhost:9000. You should see the “Flash Messages Example” page.

3. Click on the “Show Flash Message” link to add a flash message. The message should be displayed on the page.

Summary: In this guide, you’ve learned how to implement flash messages in a Node.js web application using the Express.js framework and the express-flash middleware. Flash messages are a great way to provide short-lived notifications or feedback to users after specific actions. By following the steps outlined above, you can easily integrate flash messages into your own web applications, enhancing the user experience.

Note: We have other packages too like connect-flash, req-flash etc.

Happy Learning! Feel free to connect with me on LinkedIn!

--

--

Responses (3)