Flash Message Middleware for Connect and Express
raw JSON →connect-flash is a middleware for Node.js applications, primarily used with Connect and Express frameworks, to provide transient flash messages. These messages are stored in the user's session and are cleared after being displayed, making them ideal for user feedback during redirects (e.g., "Successfully logged in!" or "Invalid credentials."). Originally extracted from Express 2.x for use with Express 3.x after direct flash support was removed, the package is quite old, with its latest version (0.1.1) published in 2013. Despite its age and lack of active maintenance, it continues to be utilized by many projects, often requiring adaptation for modern Express (4.x+) applications. It differentiates itself through its simplicity and direct integration with session middleware, offering a straightforward API for managing messages across HTTP requests.
Common errors
error TypeError: req.flash is not a function ↓
express-session and cookie-parser (if used) are loaded before connect-flash. Example: app.use(cookieParser('secret')); app.use(session({ secret: '...', resave: false, saveUninitialized: true })); app.use(flash()); error Flash messages do not appear or are empty in the view. ↓
req.flash() is called exactly once to retrieve messages for display, typically in a middleware that populates res.locals before rendering. Verify that your template correctly accesses the res.locals variables. Also check if a redirect is happening before res.locals are set or if the session is correctly configured. error ReferenceError: app.configure is not defined ↓
app.configure blocks. Apply middleware directly to the app object without conditional configuration blocks, as Express 4.x+ supports a unified middleware chain. E.g., replace app.configure(function() { app.use(...) }); with app.use(...); Warnings
breaking The original usage examples with `app.configure`, `express.cookieParser`, and `express.session` are deprecated and removed in Express 4.x and later. These must be replaced with separate `cookie-parser` and `express-session` middleware. ↓
gotcha connect-flash does not officially support ES Modules (ESM). Attempting to use `import flash from 'connect-flash';` directly in an ESM project may lead to runtime errors or `req.flash` being undefined, especially if `type: "module"` is set in `package.json`. ↓
gotcha Flash messages are stored in the session. If `express-session` middleware is not correctly configured or is placed *after* `connect-flash` middleware, `req.flash` will not be available, leading to runtime errors. ↓
deprecated The `connect-flash` package is effectively abandoned, with its last update 13 years ago. While still functional, it receives no security updates or new features. ↓
Install
npm install connect-flash yarn add connect-flash pnpm add connect-flash Imports
- flash wrong
const flash = require('connect-flash');correctimport flash from 'connect-flash'; - req.flash()
req.flash('success', 'Operation successful!'); const messages = req.flash('info');
Quickstart
import express from 'express';
import session from 'express-session';
import cookieParser from 'cookie-parser';
import flash from 'connect-flash';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// Session setup must come BEFORE connect-flash
app.use(cookieParser('keyboard cat')); // Use a strong secret in production
app.use(session({
secret: 'another secret string',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 * 10 } // 10 minutes
}));
// Initialize connect-flash
app.use(flash());
// Make flash messages available in res.locals for templates
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success');
res.locals.error_msg = req.flash('error');
res.locals.info_msg = req.flash('info');
next();
});
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); // Example with EJS
app.get('/', (req, res) => {
res.render('index', { title: 'Home' });
});
app.get('/set-flash', (req, res) => {
req.flash('success', 'This is a success message!');
req.flash('info', 'Information to note.');
res.redirect('/show-flash');
});
app.get('/show-flash', (req, res) => {
// Messages are automatically available in res.locals due to middleware above
res.render('show', { title: 'Flash Messages' });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
// You would also need 'views/index.ejs' and 'views/show.ejs' templates:
/* views/index.ejs */
// <h1><%= title %></h1>
// <a href="/set-flash">Set Flash Messages</a>
/* views/show.ejs */
// <h1><%= title %></h1>
// <% if (success_msg.length) { %>
// <div class="alert alert-success"><%= success_msg %></div>
// <% } %>
// <% if (info_msg.length) { %>
// <div class="alert alert-info"><%= info_msg %></div>
// <% } %>
// <% if (error_msg.length) { %>
// <div class="alert alert-danger"><%= error_msg %></div>
// <% } %>
// <a href="/">Go Home</a>