How to set up express-session in Node.js
express-session package, session options, secret, resave, saveUninitialized, cookie options, HttpOnly, Secure, SameSite
Installing and Configuring express-session
npm install express-session
const session = require('express-session');
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 1000 * 60 * 60 * 24 // 24 hours
}
}));
Option Breakdown
secret — used to sign the session ID cookie. Must be a long random string from environment variables. If an attacker knows the secret they can forge session IDs.
resave: false — do not re-save a session to the store if nothing changed. Reduces writes and prevents race conditions.
saveUninitialized: false — do not save empty sessions. Better for privacy and storage efficiency. Required for GDPR compliance in some regions.
httpOnly: true — JavaScript in the page cannot read the cookie. This blocks XSS-based session theft.
secure: true in production — cookie is only sent over HTTPS. Never send session cookies over HTTP in production.
sameSite: 'lax' — cookie is not sent on cross-site requests, blocking most CSRF attacks without needing a separate CSRF token for GET-safe navigations.
