express-session
Session middleware for Express — server-side sessions with configurable storage backends and cookie options.
express-session
ExpressSession middleware for Express — server-side sessions with configurable storage backends and cookie options.
Fit
Bundle (gzip)
7.6 kB
21.5 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
HTTP is stateless, so tracking logged-in users across requests requires either JWTs (client-side state) or server-side sessions. Implementing session storage, regeneration, and secure cookie handling from scratch is error-prone.
What It Does
express-session attaches a req.session object to each request that persists between requests for the same browser session. Data is stored server-side (in-memory by default, Redis/PostgreSQL via store adapters). Cookie options control security (httpOnly, secure, sameSite) and expiry.
Installation
npm install express-session
npm install -D @types/express-sessionUsage Example
import session from 'express-session';
import RedisStore from 'connect-redis';
import { redis } from './redis';
app.use(session({
store: new RedisStore({ client: redis }),
secret: process.env.SESSION_SECRET!,
resave: false,
saveUninitialized: false,
cookie: { secure: true, httpOnly: true, maxAge: 7 * 24 * 60 * 60 * 1000 },
}));
// Login
app.post('/login', async (req, res) => {
const user = await authenticate(req.body);
req.session.userId = user.id; // persisted to Redis
res.json({ ok: true });
});Related packages
Node.js body parsing middleware — populate `req.body` from JSON, urlencoded, text, and raw payloads.
compressionExpressHTTP response compression middleware for Express — gzip/deflate responses to reduce bandwidth and improve load times.
cookie-parserExpressCookie parsing middleware for Express — parse Cookie headers into `req.cookies` and support signed cookies for tamper detection.
corsExpressCORS middleware for Express — configure cross-origin resource sharing with a single line of code.
express-async-errorsExpressSimplify Express error handling by automatically passing thrown errors to `next()`.