Sessions
suggest changeHTTP is stateless: every request arrives on its own, and the server has no built-in way to know that two requests came from the same browser. A session fixes that. The server gives the browser a random, unguessable session id in a cookie, the browser sends the cookie back with every request, and the server uses the id to look up data it keeps for that visitor: who is logged in, what's in the shopping cart, flash messages, CSRF tokens.
| Task | Tool |
|---|---|
| Server-side sessions in Express | express-session |
| Store sessions in Redis | connect-redis + redis |
| Store sessions in SQL | a store package for your database, or your own session.Store subclass |
| Keep all session data in the cookie itself | cookie-session |
| Stateless tokens for APIs | JWT |
The examples are ES modules (save them as .mjs) and were run with Node.js 24, Express 5.3, express-session 1.19, cookie-session 2.1, connect-redis 10.0, redis 6.3 and Redis 8. Install the packages with npm install express express-session cookie-session connect-redis redis.
How sessions work: a session store by hand
Before using a library, here is the whole mechanism with only node:http and node:crypto. The "store" is a Map from session id to data:
import { createServer } from 'node:http';
import { randomBytes } from 'node:crypto';
const sessions = new Map(); // session id -> { data, expires }
const MAX_AGE_MS = 30 * 60 * 1000;
function parseCookies(header = '') {
const cookies = {};
for (const pair of header.split(';')) {
const i = pair.indexOf('=');
if (i > 0) cookies[pair.slice(0, i).trim()] = decodeURIComponent(pair.slice(i + 1).trim());
}
return cookies;
}
function getSession(req, res) {
const id = parseCookies(req.headers.cookie).sid;
const existing = id && sessions.get(id);
if (existing && existing.expires > Date.now()) {
existing.expires = Date.now() + MAX_AGE_MS;
return existing.data;
}
const newId = randomBytes(32).toString('base64url'); // 256 random bits
const entry = { data: {}, expires: Date.now() + MAX_AGE_MS };
sessions.set(newId, entry);
res.setHeader('Set-Cookie',
`sid=${newId}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${MAX_AGE_MS / 1000}`);
return entry.data;
}
const server = createServer((req, res) => {
const session = getSession(req, res);
session.visits = (session.visits ?? 0) + 1;
res.end(`visits: ${session.visits}\n`);
});
server.listen(0, async () => {
const url = `http://localhost:${server.address().port}/`;
let res = await fetch(url);
const setCookie = res.headers.get('set-cookie');
console.log('Set-Cookie:', setCookie.replace(/sid=[^;]+/, 'sid=<id>'));
console.log((await res.text()).trim());
const cookie = setCookie.split(';')[0]; // "sid=..."
for (let i = 0; i < 2; i++) {
res = await fetch(url, { headers: { cookie } });
console.log((await res.text()).trim());
}
res = await fetch(url); // no cookie: a brand new session
console.log('without cookie ->', (await res.text()).trim());
console.log('sessions in store:', sessions.size);
server.close();
});
Set-Cookie: sid=<id>; Path=/; HttpOnly; SameSite=Lax; Max-Age=1800
visits: 1
visits: 2
visits: 3
without cookie -> visits: 1
sessions in store: 2
Everything else is refinement of these few lines:
- The id must be unguessable. Whoever has the id is the user, so generate it with a cryptographically secure generator (
randomBytes, notMath.random(); see Random numbers) and make it long: 128 bits at the very least. - The cookie must be protected.
HttpOnlyhides it from JavaScript (and from XSS attacks),Securekeeps it off plain HTTP,SameSitestops browsers from sending it with most cross-site requests. - Sessions must expire, both in the browser (
Max-Age) and on the server, otherwise the store grows forever. The hand-made version never deletes abandoned entries, the same kind of leakexpress-sessionwarns about for its built-in store. - The store must survive restarts and be shared between processes when you run more than one, so in production it lives in Redis or a database rather than in a
Map.
For the low-level cookie API see Setting cookies with cookie-parser.
express-session basics
express-session is middleware that does all of the above. It reads the cookie, loads the session from the store into req.session, and after the response is sent saves req.session back if it changed:
import express from 'express';
import session from 'express-session';
import { createClient } from './client.mjs';
const app = express();
app.use(session({
name: 'sid', // cookie name; the default is 'connect.sid'
secret: process.env.SESSION_SECRET, // signs the cookie
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', maxAge: 30 * 60 * 1000 },
}));
app.get('/', (req, res) => {
req.session.views = (req.session.views ?? 0) + 1;
res.send(`views: ${req.session.views}, session id: ${req.sessionID.slice(0, 8)}...`);
});
const server = app.listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const request = createClient(`http://localhost:${server.address().port}`);
const first = await request('GET', '/');
console.log(first.text);
console.log(first.cookies[0].replace(/sid=[^;]+/, 'sid=<value>'));
console.log((await request('GET', '/')).text);
console.log((await request('GET', '/')).text);
server.close();
views: 1, session id: btFKDWgj...
sid=<value>; Path=/; Expires=Sat, 17 Oct 2026 20:46:04 GMT; HttpOnly; SameSite=Lax
views: 2, session id: btFKDWgj...
views: 3, session id: btFKDWgj...
client.mjs is a small helper used by the test scripts in this article. It's a fetch wrapper that keeps a cookie jar, the way a browser would:
// client.mjs: a tiny fetch wrapper that remembers cookies, like a browser
export function createClient(base, jar = new Map()) {
const request = async function (method, path, body) {
const headers = {};
if (jar.size) headers.cookie = [...jar].map(([k, v]) => `${k}=${v}`).join('; ');
if (body) headers['content-type'] = 'application/json';
const res = await fetch(base + path, {
method, headers, body: body && JSON.stringify(body), redirect: 'manual',
});
for (const c of res.headers.getSetCookie()) {
const [pair, ...attrs] = c.split(';');
const i = pair.indexOf('=');
const name = pair.slice(0, i), value = pair.slice(i + 1);
const expired = attrs.some((a) => /^\s*expires=Thu, 01 Jan 1970/i.test(a));
if (expired || value === '') jar.delete(name);
else jar.set(name, value);
}
return { status: res.status, text: (await res.text()).trim(), cookies: res.headers.getSetCookie() };
};
request.jar = jar;
return request;
}
The secret is used to sign the cookie, not to encrypt data. Generate it once with node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" and load it from the environment (see Configuration files); never commit it.
The options you should always set explicitly, because the defaults are historical:
| Option | Default | Recommended | Meaning |
|---|---|---|---|
secret |
none (required) | long random string, or an array | signs the session id cookie |
name |
'connect.sid' |
something neutral like 'sid' |
cookie name; the default advertises the stack |
resave |
true (deprecated default) |
false |
save the session on every request even if unchanged |
saveUninitialized |
true (deprecated default) |
false |
store new sessions that were never modified |
store |
MemoryStore |
Redis or a database store | where session data lives |
rolling |
false |
depends | send the cookie on every response, resetting maxAge |
cookie.maxAge |
none (browser-session cookie) | e.g. 1-24 hours | cookie lifetime in milliseconds, also the store TTL |
cookie.httpOnly |
true |
true |
hide the cookie from document.cookie |
cookie.secure |
false |
true in production |
send only over HTTPS |
cookie.sameSite |
not set | 'lax' (or 'strict') |
cross-site sending policy |
With saveUninitialized: false, a visitor who never writes to req.session gets no cookie and no store entry. That keeps bots and health checks from filling your store, and it's needed for cookie-consent laws that forbid setting cookies before the user agrees. With resave: false, unchanged sessions are not written back; stores that implement touch() just extend the expiry instead.
What the cookie contains
The cookie holds only the session id, never the data. The value is s: + id + . + signature, where the signature is an HMAC-SHA256 of the id keyed with your secret:
import express from 'express';
import session from 'express-session';
import { createHmac } from 'node:crypto';
const secret = process.env.SESSION_SECRET;
const app = express();
app.use(session({ name: 'sid', secret, resave: false, saveUninitialized: false }));
app.get('/', (req, res) => {
req.session.views = (req.session.views ?? 0) + 1;
res.send(`views: ${req.session.views}`);
});
const server = app.listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const url = `http://localhost:${server.address().port}/`;
const res = await fetch(url);
const raw = res.headers.get('set-cookie').split(';')[0].slice('sid='.length);
const value = decodeURIComponent(raw);
console.log('cookie value:', value);
const [id, signature] = value.slice(2).split('.'); // strip "s:" prefix
const expected = createHmac('sha256', secret).update(id).digest('base64').replace(/=+$/, '');
console.log('signature valid:', signature === expected);
const get = async (cookie) => (await fetch(url, { headers: { cookie } })).text();
console.log('original cookie ->', await get(`sid=${raw}`));
const forgedId = 'A' + id.slice(1);
console.log('forged id ->', await get(`sid=${encodeURIComponent(`s:${forgedId}.${signature}`)}`));
server.close();
cookie value: s:0gjDaPmnTLxEzdJ-8uJX9XESOfRPwtue.wAJyIjk9oxjcCghsWZ6Ju3fDD1f5eIl8BuAMoVvrU3Y
signature valid: true
original cookie -> views: 2
forged id -> views: 1
A changed id or signature fails verification, and the request simply gets a new, empty session. Because ids are 192 random bits, the signature isn't what makes them unguessable; it lets the server reject forged cookies without a store lookup, and lets you rotate the secret to invalidate every session at once.
Logging in and out
Session-based login comes down to three rules:
- On login, call
req.session.regenerate()to issue a brand-new session id before storing the user id. Otherwise an attacker who planted a known session id in the victim's browser (session fixation) is logged in along with the victim. - Store the user id, not the user. Load the user from the database on each request so role changes and deleted accounts take effect immediately.
- On logout, call
req.session.destroy()to delete the server-side data, and clear the cookie.
regenerate, save and destroy take callbacks; promisify turns them into promises that work with async handlers:
// app.mjs
import express from 'express';
import session from 'express-session';
import { promisify } from 'node:util';
// stand-in for a users table; store real passwords hashed
const users = new Map([
['alice', { id: 1, name: 'alice', password: 'wonderland', role: 'admin' }],
['bob', { id: 2, name: 'bob', password: 'builder', role: 'user' }],
]);
export function createApp(store) {
const app = express();
app.use(express.json());
app.use(session({
name: 'sid',
secret: process.env.SESSION_SECRET,
store, // undefined -> MemoryStore (development only)
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', maxAge: 60 * 60 * 1000 },
}));
app.post('/login', async (req, res) => {
const { name, password } = req.body ?? {};
const user = users.get(name);
if (!user || user.password !== password) {
return res.status(401).json({ error: 'invalid credentials' });
}
const cart = req.session.cart; // keep anonymous data across login
await promisify(req.session.regenerate).call(req.session); // new id: no session fixation
req.session.userId = user.id;
req.session.cart = cart;
await promisify(req.session.save).call(req.session);
res.json({ ok: true, user: user.name });
});
app.post('/logout', async (req, res) => {
await promisify(req.session.destroy).call(req.session);
res.clearCookie('sid', { httpOnly: true, sameSite: 'lax' });
res.json({ ok: true });
});
app.post('/cart', (req, res) => {
(req.session.cart ??= []).push(req.body.item);
res.json({ cart: req.session.cart });
});
function requireLogin(req, res, next) {
const user = [...users.values()].find((u) => u.id === req.session.userId);
if (!user) return res.status(401).json({ error: 'not logged in' });
req.user = user;
next();
}
app.get('/me', requireLogin, (req, res) =>
res.json({ name: req.user.name, role: req.user.role, cart: req.session.cart ?? [] }));
return app;
}
The app is exported from a function so the following sections can plug in different stores. A test that walks through an anonymous visit, a failed and a successful login, and a logout:
import { createApp } from './app.mjs';
import { createClient } from './client.mjs';
const server = createApp().listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const request = createClient(`http://localhost:${server.address().port}`);
const sid = (r) => r.cookies[0]?.match(/sid=s%3A(.{6})/)?.[1] ?? '-';
async function step(method, path, body) {
const r = await request(method, path, body);
console.log(`${method} ${path} ${r.status} ${r.text} cookie id: ${sid(r)}`);
}
await step('GET', '/me');
await step('POST', '/cart', { item: 'book' });
await step('POST', '/login', { name: 'bob', password: 'nope' });
await step('POST', '/login', { name: 'bob', password: 'builder' });
await step('GET', '/me');
await step('POST', '/logout');
await step('GET', '/me');
server.close();
GET /me 401 {"error":"not logged in"} cookie id: -
POST /cart 200 {"cart":["book"]} cookie id: W8WB3H
POST /login 401 {"error":"invalid credentials"} cookie id: -
POST /login 200 {"ok":true,"user":"bob"} cookie id: 0c5xSj
GET /me 200 {"name":"bob","role":"user","cart":["book"]} cookie id: -
POST /logout 200 {"ok":true} cookie id: -
GET /me 401 {"error":"not logged in"} cookie id: -
The first GET /me sets no cookie (thanks to saveUninitialized: false), the anonymous cart creates a session, and the successful login replaces it with a session that has a different id while keeping the cart. After logout the old cookie is useless even if someone copied it, because the data behind it is gone.
Call req.session.save() explicitly before a redirect or before sending a response early: the automatic save happens when the response ends, and with a slow store the browser can request the next page before the write has finished. The plain-text passwords keep the example short; store passwords with Password hashing. Libraries such as Passport are built on top of express-session and do the regenerate/save dance for you in req.login() and req.logout().
Two related protections belong with session logins: CSRF protection for state-changing requests (SameSite=Lax covers most cases in modern browsers, a CSRF token covers the rest), and an absolute session lifetime for sensitive apps, e.g. storing req.session.loginAt = Date.now() and forcing a new login after 12 hours regardless of activity.
Session stores
The default MemoryStore keeps sessions in a JavaScript object inside the process. It deletes an expired session only when that id is requested again, so abandoned sessions pile up, it loses every session when the process restarts (so every deploy logs everyone out), and it can't be shared between cluster workers or servers behind a load balancer. express-session prints a warning when you use it with NODE_ENV=production. A store is any object with a few methods:
| Method | Required | Called when |
|---|---|---|
get(sid, cb) |
yes | a request comes in with a session cookie |
set(sid, session, cb) |
yes | a new or modified session is saved |
destroy(sid, cb) |
yes | req.session.destroy() or regenerate() |
touch(sid, session, cb) |
recommended | an unmodified session is used and resave is false |
length, clear, all |
optional | admin tasks |
A store on top of node:sqlite
Node.js 24 ships a synchronous SQLite driver, node:sqlite, which makes a complete, persistent store fit in one file. It extends session.Store, keeps the session as JSON along with its expiry time, and periodically deletes expired rows:
// sqlite-store.mjs
import session from 'express-session';
import { DatabaseSync } from 'node:sqlite';
const DAY_MS = 24 * 60 * 60 * 1000;
export class SQLiteStore extends session.Store {
constructor({ path = 'sessions.db', cleanupIntervalMs = 15 * 60 * 1000 } = {}) {
super();
this.db = new DatabaseSync(path);
this.db.exec(`CREATE TABLE IF NOT EXISTS sessions (
sid TEXT PRIMARY KEY, sess TEXT NOT NULL, expires INTEGER NOT NULL)`);
this.stmts = {
get: this.db.prepare('SELECT sess FROM sessions WHERE sid = ? AND expires > ?'),
set: this.db.prepare(`INSERT INTO sessions (sid, sess, expires) VALUES (?, ?, ?)
ON CONFLICT(sid) DO UPDATE SET sess = excluded.sess, expires = excluded.expires`),
destroy: this.db.prepare('DELETE FROM sessions WHERE sid = ?'),
touch: this.db.prepare('UPDATE sessions SET expires = ? WHERE sid = ?'),
prune: this.db.prepare('DELETE FROM sessions WHERE expires <= ?'),
length: this.db.prepare('SELECT COUNT(*) AS n FROM sessions WHERE expires > ?'),
};
this.timer = setInterval(() => this.prune(), cleanupIntervalMs).unref();
}
#expires(sess) {
return sess.cookie?.expires ? new Date(sess.cookie.expires).getTime() : Date.now() + DAY_MS;
}
get(sid, cb) {
try {
const row = this.stmts.get.get(sid, Date.now());
cb(null, row ? JSON.parse(row.sess) : null);
} catch (err) { cb(err); }
}
set(sid, sess, cb = () => {}) {
try {
this.stmts.set.run(sid, JSON.stringify(sess), this.#expires(sess));
cb(null);
} catch (err) { cb(err); }
}
destroy(sid, cb = () => {}) {
try { this.stmts.destroy.run(sid); cb(null); } catch (err) { cb(err); }
}
touch(sid, sess, cb = () => {}) {
try { this.stmts.touch.run(this.#expires(sess), sid); cb(null); } catch (err) { cb(err); }
}
length(cb) {
try { cb(null, this.stmts.length.get(Date.now()).n); } catch (err) { cb(err); }
}
prune() {
return this.stmts.prune.run(Date.now()).changes;
}
close() {
clearInterval(this.timer);
this.db.close();
}
}
Sessions now survive a restart:
import { createApp } from './app.mjs';
import { createClient } from './client.mjs';
import { SQLiteStore } from './sqlite-store.mjs';
const store = new SQLiteStore({ path: 'sessions.db' });
let server = createApp(store).listen(0);
await new Promise((resolve) => server.once('listening', resolve));
let request = createClient(`http://localhost:${server.address().port}`);
console.log((await request('POST', '/login', { name: 'alice', password: 'wonderland' })).text);
console.log((await request('GET', '/me')).text);
// simulate a restart: close the server and the store, start a fresh app on the same file
server.close();
store.close();
const store2 = new SQLiteStore({ path: 'sessions.db' });
server = createApp(store2).listen(0);
await new Promise((resolve) => server.once('listening', resolve));
request = createClient(`http://localhost:${server.address().port}`, request.jar); // same cookies
console.log('after restart:', (await request('GET', '/me')).text);
const row = store2.db.prepare('SELECT sid, sess, expires FROM sessions').get();
console.log(row.sid.slice(0, 8) + '...', row.sess);
server.close();
store2.close();
{"ok":true,"user":"alice"}
{"name":"alice","role":"admin","cart":[]}
after restart: {"name":"alice","role":"admin","cart":[]}
I_XkOue-... {"cookie":{"originalMaxAge":3600000,"expires":"2026-10-17T21:16:06.355Z","httpOnly":true,"path":"/","sameSite":"lax"},"userId":1}
The stored session is plain JSON with a cookie object that express-session adds. Whatever you put into req.session must survive JSON.stringify(): Date objects come back as strings, Map, Set and class instances lose their type, and functions disappear. Keep sessions small (ids and flags, not whole database records), because the session is loaded and parsed on every request. A store with SQLite works well for a single server; for a several-servers setup use a shared database or Redis.
Redis
Redis is the most common session store: it's fast, it's shared by all your processes, and its key expiry deletes old sessions automatically. connect-redis works with the official redis client:
import { createClient as createRedisClient } from 'redis';
import { RedisStore } from 'connect-redis';
import { createApp } from './app.mjs';
import { createClient } from './client.mjs';
const redis = createRedisClient({ url: process.env.REDIS_URL ?? 'redis://localhost:6379' });
redis.on('error', (err) => console.error('redis error:', err.message));
await redis.connect();
const store = new RedisStore({ client: redis, prefix: 'myapp:sess:' });
const server = createApp(store).listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const request = createClient(`http://localhost:${server.address().port}`);
console.log((await request('POST', '/login', { name: 'bob', password: 'builder' })).text);
console.log((await request('GET', '/me')).text);
const [key] = await redis.keys('myapp:sess:*');
console.log('key:', key.slice(0, 20) + '...');
console.log('ttl (seconds):', await redis.ttl(key));
console.log('value:', await redis.get(key));
await request('POST', '/logout');
console.log('keys after logout:', (await redis.keys('myapp:sess:*')).length);
server.close();
await redis.quit();
{"ok":true,"user":"bob"}
{"name":"bob","role":"user","cart":[]}
key: myapp:sess:zLA-U4Io9...
ttl (seconds): 3600
value: {"cookie":{"originalMaxAge":3600000,"expires":"2026-10-17T21:16:07.390Z","httpOnly":true,"path":"/","sameSite":"lax"},"userId":2}
keys after logout: 0
connect-redis derives each key's TTL from the cookie's maxAge (3600 seconds here), so expired sessions disappear from Redis on their own. A distinct prefix lets several apps share one Redis instance. If Redis is down, req.session can't be loaded and requests fail with an error, so monitor it like the database it is. See NodeJS with Redis for more about the client.
Cookie-based sessions with cookie-session
cookie-session takes the opposite approach: the whole session is serialized into the cookie, so there's no store at all. That suits small amounts of data (a user id, a theme, a flash message) and makes horizontal scaling trivial:
import express from 'express';
import cookieSession from 'cookie-session';
import { createClient } from './client.mjs';
const app = express();
app.use(cookieSession({
name: 'session',
keys: [process.env.SESSION_KEY_NEW, process.env.SESSION_KEY_OLD], // first signs, all verify
maxAge: 24 * 60 * 60 * 1000,
httpOnly: true,
sameSite: 'lax',
}));
app.get('/', (req, res) => {
req.session.views = (req.session.views ?? 0) + 1;
res.send(`views: ${req.session.views}`);
});
app.post('/logout', (req, res) => {
req.session = null; // deletes the cookie
res.send('bye');
});
const server = app.listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const request = createClient(`http://localhost:${server.address().port}`);
const r = await request('GET', '/');
console.log(r.text);
for (const c of r.cookies) console.log(c);
console.log((await request('GET', '/')).text);
const data = request.jar.get('session');
console.log('decoded:', Buffer.from(data, 'base64').toString());
request.jar.set('session', Buffer.from('{"views":1000}').toString('base64'));
console.log('tampered ->', (await request('GET', '/')).text);
console.log((await request('POST', '/logout')).text, [...request.jar.keys()]);
server.close();
views: 1
session=eyJ2aWV3cyI6MX0=; path=/; expires=Sun, 18 Oct 2026 20:16:07 GMT; samesite=lax; httponly
session.sig=MG8mQAHPxolNmCDMfze-_ZI_jfs; path=/; expires=Sun, 18 Oct 2026 20:16:07 GMT; samesite=lax; httponly
views: 2
decoded: {"views":2}
tampered -> views: 1
bye []
Notice what this shows:
- The data is only base64-encoded, not encrypted: anyone holding the cookie can read it. Don't put anything secret in it.
- A second cookie,
session.sig, carries the signature. A modified value fails verification and the app sees an empty session (views: 1after tampering). keysis an array: the first key signs new cookies and all of them are accepted, so you can rotate keys without logging everyone out.- Setting
req.session = nulldeletes the cookie.
The trade-offs compared to server-side sessions: browsers limit a cookie to about 4 KB, the data travels with every request, and you can't revoke a session from the server because there's nothing on the server to delete. A copied cookie stays valid until it expires. That's the same trade-off as a JWT, and the same mitigations apply (short lifetimes, a version number checked against the database).
Production configuration
In production the app usually sits behind a reverse proxy or load balancer that terminates TLS and forwards plain HTTP to Node.js. With cookie.secure: true, express-session only sends the cookie when the request is secure, and without trust proxy Express doesn't believe the proxy's X-Forwarded-Proto: https header:
import express from 'express';
import session from 'express-session';
const isProd = process.env.NODE_ENV === 'production';
function makeApp(trustProxy) {
const app = express();
if (trustProxy) app.set('trust proxy', 1); // trust X-Forwarded-* from one proxy hop
app.use(session({
name: '__Host-sid', // __Host- prefix: Secure, Path=/, no Domain
secret: process.env.SESSION_SECRETS.split(','), // newest first; old ones still verify
resave: false,
saveUninitialized: false,
rolling: true, // re-send the cookie, extending maxAge, on every response
cookie: {
secure: isProd, // only send over HTTPS
httpOnly: true,
sameSite: 'lax',
maxAge: 2 * 60 * 60 * 1000, // 2 hours of inactivity
},
}));
app.get('/', (req, res) => {
req.session.user = 'alice';
res.send(`req.secure=${req.secure}`);
});
return app;
}
for (const trustProxy of [false, true]) {
const server = makeApp(trustProxy).listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const res = await fetch(`http://localhost:${server.address().port}/`, {
headers: { 'x-forwarded-proto': 'https' }, // what a TLS-terminating proxy adds
});
console.log(`trust proxy=${trustProxy}:`, await res.text(),
'->', res.headers.get('set-cookie')?.replace(/=s%3A[^;]+/, '=<value>') ?? 'no cookie');
server.close();
}
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
trust proxy=false: req.secure=false -> no cookie
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
trust proxy=true: req.secure=true -> __Host-sid=<value>; Path=/; Expires=Sat, 17 Oct 2026 22:16:08 GMT; HttpOnly; Secure; SameSite=Lax
Without trust proxy the session is silently never established: no error, users just can't stay logged in. That's the most common "sessions don't work in production" bug. Set trust proxy to the number of proxies in front of the app (or their addresses), not to true, so clients can't spoof the header when they reach the app directly. The run also shows the MemoryStore warning that appears whenever NODE_ENV=production and no store is configured.
Other details in this configuration:
- The
__Host-cookie name prefix makes browsers reject the cookie unless it hasSecure,Path=/and noDomain, so a compromised subdomain can't overwrite it. Because it requiresSecure, use such a name only wheresecureis on (browsers drop the cookie on plain-HTTP localhost). secretas an array enables rotation: put the new secret first, keep the old one until existing sessions expire, then remove it.rolling: truegives an inactivity timeout: each response re-sends the cookie with a freshmaxAge, so the session ends 2 hours after the last request. With the defaultrolling: falsethe cookie is only re-sent when the session is new or modified.
Common pitfalls
- Using
MemoryStorein production. Sessions vanish on every deploy, memory grows without bound, and with several processes users are randomly logged out depending on which process gets the request. - Forgetting
regenerate()on login, which enables session fixation. Also regenerate when privileges change (e.g. after entering a second factor). - Logging out by deleting only
req.session.userIdor only the cookie. Destroy the server-side session. - Concurrent requests overwriting each other. Each request loads the session, modifies its copy and saves the whole object at the end; two parallel requests that both change the session lose one of the changes. Keep frequently changing data (counters, carts that are updated in parallel) in the database, keyed by user id.
- Missing
trust proxybehind a TLS-terminating proxy withsecure: true: no cookie is ever set. - Expecting
maxAgein seconds.cookie.maxAgeis in milliseconds; theMax-Ageattribute in the header and Redis TTLs are in seconds. - Storing sessions for every visitor. Keep
saveUninitialized: falseso crawlers and monitoring don't create millions of empty sessions. - Cross-site cookies. If your frontend and API are on different sites,
SameSite=Laxcookies aren't sent withfetchfrom the frontend. You needsameSite: 'none'withsecure: true,credentials: 'include'on the client and a matching CORS setup, plus CSRF protection, or better, serve both from the same site.
Summary
- A session is a random id in an
HttpOnly,Secure,SameSitecookie plus data the server keeps for that id. - Use
express-sessionwithresave: false,saveUninitialized: false, a customname, a secret from the environment, and an explicitcookie.maxAge. - Call
regenerate()on login, store only the user id, calldestroy()andclearCookie()on logout, andsave()before redirects. - Replace
MemoryStorewith Redis (connect-redis), a database store, or your ownsession.Storesubclass; session data must be small and JSON-serializable. cookie-sessionkeeps the data in a signed (not encrypted) cookie: no store, but a 4 KB limit and no server-side revocation.- Behind a TLS-terminating proxy, set
app.set('trust proxy', 1)or secure cookies are never sent.