Sessions Explained
How session-based login works: the random id, the cookie that carries it, the server-side lookup, and how to build it safely in TypeScript.

Sessions are the oldest way for a website to remember who you are, and they're still the default in most frameworks. They're also simpler than they sound: the server hands you a random number, writes down whose number it is, and checks its notes every time you come back.
This post covers how a session works from login to logout, how the browser carries the id for you, and how to build it safely in TypeScript. It's the companion to JWT Explained, which covers the other common approach.
What a session is for
When you log in, the server checks your password once. After that, it needs a way to remember who you are on every following request, without asking for your password again.
With a session, the server:
- Makes a long random id, like
a8f3c9…. - Stores "
a8f3c9belongs to alice" in its database. - Gives you the id.
On every request after that, you show the id, and the server looks it up.
How the id travels: cookies
You never copy the id or paste it anywhere. The browser does all of it with a cookie. Here's the whole flow, from login to logout:
1 · Log in The password is checked once.
- Browser to Server: POST /login email + password
2 · Create the session A random id goes into the sessions table and into a cookie.
- Server to Database: save a8f3c9 → alice
- Server to Browser: Set-Cookie: sid=a8f3c9; HttpOnly
3 · Every request after that The cookie rides along, and the server looks it up.
- Browser to Server: GET /profile Cookie: sid=a8f3c9
- Server to Database: find a8f3c9
- Database to Server: alice
- Server to Browser: 200 alice’s profile
4 · Log out Deleting the id from the table is what logs you out.
- Browser to Server: POST /logout Cookie: sid=a8f3c9
- Server to Database: delete a8f3c9
- Server to Browser: clear the cookie
5 · A copied id is useless An attacker replays the old id. It isn’t in the table, so the answer is no.
- Attacker to Server: GET /profile Cookie: sid=a8f3c9
- Server to Database: find a8f3c9
- Database to Server: not found
- Server to Attacker: 401 Unauthorized
Two lines in that flow do all the work.
The server saves the id in your browser. When login succeeds, the server's reply includes this line:
Set-Cookie: sid=a8f3c9...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=604800It tells the browser: "save a cookie called sid with the value a8f3c9…".
Everything after the first semicolon is a setting for that cookie, explained
below.
The browser sends it back by itself. From then on, every request the browser makes to that site includes this line, without your code doing anything:
Cookie: sid=a8f3c9...That's the id the server looks up.
What the cookie flags do
HttpOnly: JavaScript on the page can't read the cookie. The browser still sends it, so your own code never needs it, and an XSS bug can't steal it. (Injected script can still send requests from the page, with the cookie attached, soHttpOnlylimits XSS but doesn't stop it.)Secure: the cookie is only sent over HTTPS, so nobody on the network can read it.SameSite=Lax: the cookie isn't sent when another site sends a form or request to yours in the background. This blocks most cross-site request forgery (CSRF). UseStrictif your site never needs the cookie on links from other sites. SameSite Cookies Explained walks through an example.Path=/: the cookie is sent on every page of the site.Path=/adminwould send it only to pages under/admin.Max-Age: how long the browser keeps it, in seconds.604800is 7 days.
Building it in TypeScript
The examples use Express, the cookie
package to read cookies, and a db object standing in for your database
client. Express can already set and clear cookies with res.cookie() and
res.clearCookie(), so reading them is the only part that needs a package.
The sessions table
Each session is one row:
type Session = { id: string; // a hash of the random id in the cookie userId: string; // who it belongs to expiresAt: Date; // when it stops working};Creating a user at signup
Sessions start after a password check, so the user needs a password first. Store only a bcrypt hash of it, never the password itself:
import bcrypt from "bcrypt";
app.post("/signup", async (req, res) => { // 12 is the cost (2¹² rounds). bcrypt makes a random salt and stores it in // the hash, so `passwordHash` holds everything needed to check it later. const passwordHash = await bcrypt.hash(req.body.password, 12);
await db.user.create({ data: { email: req.body.email, passwordHash } }); res.sendStatus(201);});A bcrypt hash can't be turned back into the password, not even by you. A real signup route would also check that the email isn't taken and that the password is long enough.
Creating a session at login
import { createHash, randomBytes } from "node:crypto";import bcrypt from "bcrypt";
const SESSION_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days, in milliseconds
// The database stores this hash, never the id itself.function hashId(sessionId: string) { return createHash("sha256").update(sessionId).digest("hex");}
app.post("/login", async (req, res) => { const user = await db.user.findUnique({ where: { email: req.body.email } });
// Hashes the typed password with the salt and cost stored in passwordHash, // then checks the two match. No secret key needed. const ok = user && (await bcrypt.compare(req.body.password, user.passwordHash)); if (!ok) return res.sendStatus(401);
// 32 random bytes (256 bits), turned into URL-safe text for the cookie. const sessionId = randomBytes(32).toString("base64url"); await db.session.create({ data: { id: hashId(sessionId), userId: user.id, expiresAt: new Date(Date.now() + SESSION_TTL), }, });
res.cookie("sid", sessionId, { httpOnly: true, secure: true, sameSite: "lax", maxAge: SESSION_TTL, }); res.sendStatus(204);});The id must come from crypto.randomBytes (or crypto.randomUUID), never
Math.random, a counter, or the user's id. If an attacker can guess the next
id, they can be the next user.
The cookie gets the real id, but the database only gets hashId(sessionId). If
someone steals a copy of the database, they can't use its rows to log in, for
two reasons:
- The hash can't be reversed. There's no way to get
a8f3c9back from its hash. - The id can't be guessed. An attacker could try hashing possible ids and
looking for a match. With a counter (
1,2,3…) that would take seconds. With 256 random bits, there are too many possibilities to ever find one.
You need both. That's also why a fast hash like SHA-256 is fine here, while passwords need slow bcrypt: passwords are guessable, and random ids aren't.
Reading the session id
The browser sends every cookie for your site in one Cookie header, like
sid=a8f3c9...; theme=dark. parseCookie turns that into an object:
import { parseCookie } from "cookie";
function getSessionId(req: Request): string | undefined { return parseCookie(req.headers.cookie ?? "").sid;}Checking the session on every request
async function requireAuth(req: Request, res: Response, next: NextFunction) { const sessionId = getSessionId(req); if (!sessionId) return res.sendStatus(401);
const session = await db.session.findUnique({ where: { id: hashId(sessionId) }, include: { user: true }, }); if (!session || session.expiresAt < new Date()) return res.sendStatus(401);
req.user = session.user; next();}
app.get("/profile", requireAuth, (req, res) => { res.json({ email: req.user.email });});Notice the difference from a JWT: there's no signature to check. The id means nothing by itself, so the only way to trust it is to find its hash in the database.
Logging out
app.post("/logout", async (req, res) => { const sessionId = getSessionId(req); // No cookie means there's no session to delete. if (sessionId) await db.session.deleteMany({ where: { id: hashId(sessionId) } }); res.clearCookie("sid"); res.sendStatus(204);});Deleting the row is what actually logs the user out. Clearing the cookie is just tidying up; if someone had copied the id, it's already useless.
Keeping sessions safe
- Make a new id at every login. Never keep an id the browser had before logging in. Otherwise an attacker can plant a known id in someone's browser, wait for them to log in, and then use the same id (this is called session fixation). The login handler above always creates a fresh id, so it's safe.
- Expire sessions. Set an absolute limit (like 7 days), and consider an idle limit too: if a session hasn't been used for 30 minutes, delete it.
- Log out everywhere on a password change. Delete every session for that
user:
db.session.deleteMany({ where: { userId } }). Whoever stole the old password loses access immediately. - Clean up old rows. Expired sessions still sit in the table until you
delete them. Run a small job that removes rows where
expiresAthas passed. - Store a hash of the id, not the id. The code above already does this
with
hashId, so a leaked database backup doesn't contain working ids.
You don't have to build all of this by hand. There are two common options:
- Better Auth is a library that runs inside your app. It handles the login, the session id, the cookie and the sessions table, much like this post does, and keeps sessions in your own database (PostgreSQL, MySQL and SQLite are common).
- Clerk is a hosted service. It runs the login and keeps sessions on its own servers, then gives your app a short-lived JWT for each request. That's a mix of sessions and the tokens from JWT Explained.
Sessions or JWTs?
Both start the same way, with a password check at login. They only differ in how the server remembers you afterwards.
- What you get: a session gives you a random id that means nothing by itself. A JWT gives you a signed token that says "this is alice".
- Where "this is alice" lives: for a session, in the server's database. For a JWT, inside the token.
- On each request: a session needs a database lookup. A JWT needs only a signature check.
- Logging out: a session is deleted and stops working instantly. A JWT
keeps working until
exp. - Many servers or services: with sessions, they all need the same session store. With JWTs, each one can check the signature alone.
Use sessions when you have one web app talking to its own backend. It's the simplest setup, and you can cancel any session instantly.
Use JWTs when many separate services need to know who the user is without all sharing one database, or for APIs used outside a browser. The trade-off, covered in JWT Explained, is that you can't take a token back, so you need short expiry times and refresh tokens.
Many apps end up mixing the two: a long-lived refresh token stored in the database (which works like a session) and a short-lived JWT for each request.
The short version
- A session is a random id in a cookie plus a row in the server's database.
- The browser sends the cookie on every request automatically.
- Make the id with
crypto.randomBytes, and make a new one at every login. - Store a SHA-256 hash of the id, and a bcrypt hash of the password, never the real values.
- Set the cookie as
HttpOnly,SecureandSameSite. - Logging out means deleting the row, which takes effect immediately.
- To compare with the token approach, read JWT Explained.