Express Session Middleware

1.19.0 · active · verified Wed Apr 22

express-session is a robust and widely-used session middleware for Express.js applications, currently stable at version 1.19.0. It provides server-side session storage, managing session IDs via cookies while keeping the actual session data on the server, which is a key security differentiator compared to client-side cookie storage. While the core package offers a default `MemoryStore` for development and debugging, it explicitly warns against its use in production due to memory leak risks and lack of scalability, promoting a rich ecosystem of compatible external session stores. The project maintains a steady release cadence, with recent updates focusing on features like dynamic cookie options, improved security tooling, and dependency updates, ensuring ongoing compatibility and enhancements for Node.js environments (supporting Node.js >= 0.8.0). It has evolved to directly manage session cookies, making the `cookie-parser` middleware optional and recommending careful use if both are present to avoid secret mismatches.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up `express-session` with basic configuration for a view counter. It highlights essential cookie options like `secure`, `httpOnly`, and `maxAge`, and includes a critical warning about not using the default `MemoryStore` in production, emphasizing the use of environment variables for secrets.

const express = require('express');
const session = require('express-session');
const app = express();
const port = 3000;

// WARNING: The default MemoryStore is NOT production-ready.
// For production, use a compatible session store like connect-redis, connect-mongo, or memorystore.
// For a list of stores, see compatible session stores section in the README.
app.use(session({
  secret: process.env.SESSION_SECRET ?? 'a very strong secret key that should be in an environment variable', // ALWAYS use a strong, environment-variable-backed secret
  resave: false, // Don't save session if unmodified
  saveUninitialized: true, // Save new but uninitialized sessions (e.g., before user logs in)
  cookie: {
    secure: process.env.NODE_ENV === 'production', // Use secure cookies in production (requires HTTPS)
    httpOnly: true, // Prevent client-side JavaScript access to cookie (mitigates XSS)
    maxAge: 24 * 60 * 60 * 1000 // Session expires after 24 hours (in milliseconds)
  }
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`<h1>Welcome back!</h1><p>You have visited this page ${req.session.views} times.</p><p>Your session ID is: ${req.sessionID}</p>`);
  } else {
    req.session.views = 1;
    res.send(`<h1>Hello, New User!</h1><p>You have visited this page ${req.session.views} time.</p><p>Your session ID is: ${req.sessionID}</p>`);
  }
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
  console.log('Try visiting a few times and then refresh after some time to see the session count.');
  console.log('For production, ensure `secure: true` for cookies and that your app runs over HTTPS.');
});

view raw JSON →