Sessions and cookies
🏠The everyday picture
At a concert, your ticket is checked once at the gate, and you get a wristband. For the rest of the night, staff look at the wristband, not your ticket. A session is the wristband.
📘What it really is
-
HTTP doesn't remember anything between requests (Module 42), so after signing in, the server issues a session: a long, random session id, stored on the server with the user's id.
-
The id is sent to the browser in a cookie, and the browser sends it back automatically with every request:
res.cookie("sid", sessionId, {
httpOnly: true, // JavaScript can't read it (protects against XSS theft)
secure: true, // only sent over HTTPS
sameSite: "lax", // not sent with most cross-site requests (helps against CSRF)
maxAge: 1000 * 60 * 60 * 8,
});
- Middleware reads the cookie on each request, looks up the session, and sets
req.user(or leaves it empty). - Signing out deletes the session on the server, so the cookie is useless even if copied.
- After sign-in, create a new session id (never reuse one from before sign-in).
-
Sessions are stored in a database or a fast store like Redis in production, so they survive restarts and work with several servers.
-
Libraries like
express-sessionhandle much of this. - When frontend and API are on different domains, cookies need care: CORS with credentials (Module 48), and the
frontend sending
credentials: "include"withfetch.
🖱️Try it
Add sign-in and sign-out routes. On sign-in, verify the password, create a random session id
(crypto.randomUUID()), store it with the user id, and set it as an httpOnly cookie. Add middleware that sets
req.user from the cookie, and a GET /me route returning the signed-in user (or 401). In developer tools, find the
cookie under Application → Cookies, and confirm document.cookie in the console can't see it.
✅Quick check
What does httpOnly protect against?
Show the answer
JavaScript (including malicious injected scripts) reading the cookie and stealing the session.
Why delete the session on the server when signing out, not just the cookie?
Show the answer
If the cookie was copied, it would still work; deleting the session makes it useless everywhere.
