Flash Message Middleware for Connect and Express

raw JSON →
0.1.1 verified Thu Apr 23 auth: no javascript abandoned

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.

error TypeError: req.flash is not a function
cause `connect-flash` middleware has not been applied, or `express-session` middleware (which `connect-flash` depends on) was not initialized or was placed after `connect-flash` in the middleware chain.
fix
Ensure 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.
cause Flash messages are cleared after being retrieved. If `req.flash()` is called multiple times for the same key, or if `res.locals` assignment is done incorrectly, messages might be consumed before the view can render them.
fix
Ensure 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
cause `app.configure` was deprecated in Express 3.x and completely removed in Express 4.x. `connect-flash` examples from its original README use this syntax.
fix
Remove 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(...);
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.
fix Migrate to `cookie-parser` and `express-session` npm packages. Install them (`npm install cookie-parser express-session`) and use them as separate middleware: `app.use(cookieParser('secret')); app.use(session({ ... }));`
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`.
fix For projects using ESM, it is generally safer to transpile connect-flash or ensure compatibility through tools like Babel. If possible, consider alternative, actively maintained flash message libraries with explicit ESM support or stick to CommonJS for connect-flash integration.
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.
fix Ensure `express-session` (and `cookie-parser` if used separately) is initialized and placed in the middleware chain *before* `connect-flash`. For example: `app.use(cookieParser(...)); app.use(session(...)); app.use(flash());`
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.
fix For new projects, consider using a more modern and actively maintained flash message solution or implementing a custom, simple session-based message system. For existing projects, be aware of potential vulnerabilities or compatibility issues with newer Node.js or Express versions.
npm install connect-flash
yarn add connect-flash
pnpm add connect-flash

This quickstart demonstrates setting up connect-flash with modern Express (4.x+), including `cookie-parser` and `express-session`, and then setting and retrieving flash messages which are made available to EJS templates via `res.locals`.

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>