FLASH MESSAGES IN NODEJS USING CONNECTFLASH MODULE
www.bacancytechnology.com
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
npm init
Install dependencies
To implement flash messages in NodeJs with connect-flash module, you need to install the required dependencies using the command.
npm install connect-flash express expresssession --save
Express: Required by the library connectflash 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.
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.
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.
Run the application
Once done with the development part. Run the application by the following command and test the functionality.
node index.js
The browser will be redirected to the /display-message and it will show the following output.
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.
npm install ejs
Open index.js and add below code
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.
app.get('/display-message', (req, res) => { res.render("display"); });
Once done, add the below line in views/index.js.
<%= message.success %>
To beautify the flash message we will use bootstrap css. Include bootstrap css file into view template and use the below code.
<link href="https://cdn.jsdelivr.net/npm/bootstra p@5.1.1/dist/css/bootstrap.min.css" 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.
Github Repository
Feel free to visit the source code: flashmessages-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 problemsolving instincts then contact us and hire Node.js developer.
Thank You
www.bacancytechnology.com