How to Display Flash Messages using connect-flash Module in Node.js ?
Connect-flash module for Node.js allows the developers to send a message whenever a user is redirecting to a specified web-page. For example, whenever, a user successfully logged in to his/her account, a message is flashed(displayed) indicating his/her success in the authentication.
Prerequisites Before starting with the application, you must have the following:
- An IDE of your choice installed in your system.
- Node.js and NPM installed and configured.
- Basic knowledge of Node.js and its modules.
Installation and Setup: First, initialize our application with a package.json file. Then install the dependencies that are required for our application by the following command:
npm install express express-session connect-flash --save
Here, express is required by the connect-flash library to run. We are using express-session so that a session can be created whenever a message is flashed and the user is redirected to the specified page.
Now, create a file and name it as app.js. You can give any name of your choice. Now, open the app.js file and import the modules by the following code:
Implementation: Now, comes the main part that is implementation. Write the following code in app.js file:
After importing all the required dependencies, we are defining a port number on which our app will run. Now, we are defining a session-secret by using of which our sensitive information is encrypted. SaveUninitialized prevents the browser from using empty sessions. Now we are calling our connect-flash module by using app.use(flash()).
Now, here comes the main part of our application. We are defining a route / , which will first flash(display) the specified message and then redirects the user to /gfg route. The /gfg will show the specified message on the web-page. And, finally, we made our application to listen to the specified port and if any error is encountered then the error is logged on the console.
Now, run the application by the following command:
Output: The browser will directly redirects the user to /gfg route and will display the output as shown below:
Conclusion: Connect-flash module for Node.js is very useful for developers whenever a flash message is to be sent. In this article, we learned about the connect-flash module. We installed and imported the required dependencies in our application. Finally, we implemented our module and seen how it actually works in a browser.