Express JS Tutorial | Flash Message
Flash messages are a way to display temporary messages to the user after a specific action has been taken, such as submitting a form or updating a record. They are commonly used in web applications to provide feedback to the user and are often displayed at the top of the page for a few seconds before disappearing.
Implementing Flash Messages in Express.js
To implement flash messages in Express.js, we can use the express-flash
middleware along with express-session
. First, we need to install these packages using npm:
npm install express-flash express-session
Next, we need to include the express-session
middleware in our Express application and configure it. Then, we can include the express-flash
middleware after the session middleware. Here’s an example of how to set this up in an Express application:
const express = require('express');
const session = require('express-session');
const flash = require('express-flash');
const app = express();
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
app.use(flash());
Using Flash Messages
Once we’ve set up the flash middleware, we can use the req.flash()
method to set a flash message. For example, if we want to set a success message after a form submission, we can do the following:
app.post('/submit-form', (req, res) => {
// form processing logic
req.flash('success', 'Form submitted successfully!');
res.redirect('/form');
});
To display the flash message in our view, we can use an if statement to check if the message exists and then display it accordingly. Here’s an example using EJS:
<% if (success) { %>
<div class="alert alert-success">
<%= success %>
</div>
<% } %>
Conclusion
Flash messages are a useful way to provide feedback to users in a web application. By using the express-flash
middleware in Express.js, we can easily implement flash messages and improve the user experience.