Sessions and cookies
Overview
After a user logs in, how does the server know who they are on the next request? HTTP doesn’t remember — every request stands alone. Something must travel with each request to identify the user.
There are two main approaches:
- Sessions — the server remembers who is logged in, and the browser holds only a random ticket (a cookie). This topic.
- Tokens (such as JWTs) — the client holds a signed statement of who it is. Next topic.
Both are widely used. Sessions with cookies are the classic, robust choice for websites and web apps served from your own domain.
Cookies
A cookie is a small piece of data the server asks the browser to store, using a response header:
Set-Cookie: sid=7f3a9c…; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=604800From then on, the browser automatically sends it back with every request to that site:
Cookie: sid=7f3a9c…The attributes are what make cookies safe:
| Attribute | What it does |
|---|---|
HttpOnly |
JavaScript in the page can’t read it — stolen-by-script attacks (XSS) can’t take the session |
Secure |
only sent over HTTPS |
SameSite=Lax |
not sent on most cross-site requests — a strong defence against CSRF |
Max-Age / Expires |
how long it lives; without them it’s deleted when the browser closes |
Path / Domain |
which URLs it’s sent to |
Server-side sessions
The cookie holds only a random, unguessable ID. The actual session data — which user, their role, when they logged in — lives on the server, in a store shared by all app instances. Redis is ideal: fast, with built-in expiry.
Building it
You need a cookie parser and Redis:
npm install cookie-parser ioredis// src/auth/sessions.js
import { randomBytes } from 'node:crypto';
import { redis } from '../redis.js';
const TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: TTL_SECONDS * 1000, // Express uses milliseconds
};
export async function createSession(res, user) {
const sid = randomBytes(32).toString('base64url'); // 256 random bits
await redis.set(`sess:${sid}`, JSON.stringify({ userId: user.id, role: user.role }), 'EX', TTL_SECONDS);
res.cookie('sid', sid, cookieOptions);
}
export async function destroySession(req, res) {
const sid = req.cookies?.sid;
if (sid) await redis.del(`sess:${sid}`);
res.clearCookie('sid', { path: '/' });
}
export async function loadSession(req, res, next) {
const sid = req.cookies?.sid;
const data = sid && (await redis.get(`sess:${sid}`));
if (data) req.user = { id: JSON.parse(data).userId, role: JSON.parse(data).role };
next();
}
export function requireLogin(req, res, next) {
if (!req.user) return res.status(401).json({ error: { message: 'Please log in' } });
next();
}// src/app.js
import cookieParser from 'cookie-parser';
import { createSession, destroySession, loadSession, requireLogin } from './auth/sessions.js';
app.use(cookieParser());
app.use(loadSession);
app.post('/auth/login', validate({ body: loginSchema }), async (req, res) => {
const user = await authService.login(req.validated.body);
await createSession(res, user);
res.json({ id: user.id, name: user.name });
});
app.post('/auth/logout', async (req, res) => {
await destroySession(req, res);
res.sendStatus(204);
});
app.get('/me', requireLogin, async (req, res) => {
res.json(await usersRepo.findById(req.user.id));
});Ready-made libraries such as express-session (with a Redis store) handle the same steps — reading the cookie, loading and saving the session, rotating IDs. Building it yourself once shows you exactly what they do.
Session security checklist
- Random, long IDs from
crypto.randomBytes— never sequential numbers or user IDs. - New ID at login (and on privilege changes). Never reuse an ID issued before login; that prevents session fixation attacks.
- Expiry — an idle timeout (TTL in Redis) and, for sensitive apps, an absolute maximum lifetime.
- Logout deletes the server-side session, so the cookie becomes worthless even if copied.
- Revocation is easy — delete a user’s sessions when they change their password, or offer “log out of all devices”.
CSRF
Because browsers send cookies automatically, a malicious website could try to make a logged-in user’s browser submit a request to your API — cross-site request forgery. Defences:
SameSite=Lax(orStrict) cookies — stops most cross-site requests from carrying the cookie.- Only change data with
POST/PUT/PATCH/DELETE, neverGET. - For extra protection, check the
Originheader on state-changing requests, or use CSRF tokens.
Front end on another domain?
If your front end is on app.example.com and the API on api.example.com, cookies still work, but you’ll need CORS with credentials (credentials: true on the server, credentials: 'include' in fetch). If the API is on a completely different site, consider serving both from one domain through a proxy — or use tokens.
Behind a proxy
In production, HTTPS usually ends at a load balancer, so Express sees plain HTTP. Tell Express to trust the proxy’s headers, or Secure cookies won’t be set and req.ip will be wrong:
app.set('trust proxy', 1); // trust the first proxy in front of the appSessions or JWTs? For a browser app on your own domain, sessions are simple, secure and easy to revoke. Tokens shine for mobile apps, third-party API clients and service-to-service calls. Many products use both.
Session middleware
Write loadSession middleware that reads the sid cookie, looks up sess:<sid> in Redis, and sets req.user if found. Write requireLogin that responds 401 when req.user is missing. Then add POST /logout that deletes the session and clears the cookie.
import { redis } from './redis.js';
export async function loadSession(req, res, next) {}
export function requireLogin(req, res, next) {}import { redis } from './redis.js';
export async function loadSession(req, res, next) {
const sid = req.cookies?.sid;
if (sid) {
const data = await redis.get(`sess:${sid}`);
if (data) {
req.session = { id: sid, ...JSON.parse(data) };
req.user = { id: req.session.userId, role: req.session.role };
}
}
next();
}
export function requireLogin(req, res, next) {
if (!req.user) return res.status(401).json({ error: { message: 'Please log in' } });
next();
}
app.post('/logout', async (req, res) => {
if (req.session) await redis.del(`sess:${req.session.id}`);
res.clearCookie('sid', { path: '/' });
res.sendStatus(204);
});Summary
- HTTP is stateless, so a login is remembered with a cookie the browser sends on every request.
- Store a random session ID in the cookie and the session data on the server (e.g. Redis).
- Set cookies as
HttpOnly,SecureandSameSiteto block theft and cross-site requests. - Create a new session ID at login, expire sessions, and delete them on logout.
- Sessions are easy to revoke and ideal for browser apps on your own domain.