Lesson 200 of 296
Sessions vs JWT, refresh tokens and safe storage
What you will learn
- Authentication vs authorisation
- Server-side sessions
- JSON Web Tokens: structure, signing and verification
- Comparing sessions and JWTs
- Access tokens and refresh tokens, with rotation
- Where to store tokens in the browser, and cookie flags
- Logout and revocation
On this page
Two words
- Authentication (AuthN): proving who you are (login).
- Authorisation (AuthZ): deciding what you may do (Lesson 203).
HTTP is stateless (Lesson 196), so after login, every request must prove who the user is. Two main approaches: sessions and tokens.
Server-side sessions
- The user logs in with email and password.
- The server creates a session record in a store (Redis or a database):
{ sessionId: "random", userId: 42, expiresAt }. - It sends the session ID in a cookie:
Set-Cookie: sid=8f2a...; HttpOnly; Secure; SameSite=Lax; Path=/. - The browser sends the cookie automatically with every request; the server looks up the session.
The session ID must be long and random (at least 128 bits from a secure random generator), and a new one must be issued at login (to prevent session fixation).
JSON Web Tokens (JWT)
A JWT is a token that contains the data itself, signed so it cannot be changed. Three Base64URL parts separated by dots:
eyJhbGciOiJIUzI1NiJ9 . eyJzdWIiOiI0MiIsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0MDAwMDAwfQ . 4pXk...signature
header payload (claims) signature- Header: the algorithm, e.g.
{"alg":"HS256"}. - Payload (claims):
sub(subject, the user ID),exp(expiry time),iat(issued at),iss(issuer),aud(audience), plus custom claims likerole. - Signature: made from the header and payload with a secret key (HS256) or a private key (RS256, ES256). Anyone can read a JWT; only the key holder can create a valid one.
A JWT is encoded, not encrypted. Never put secrets or personal data in it.
Signing and verifying with the jose library:
import { SignJWT, jwtVerify } from "jose";
const secret = new TextEncoder().encode("replace-with-at-least-32-random-bytes!!");
export async function createAccessToken(userId: string, role: "user" | "admin"): Promise<string> {
return new SignJWT({ role })
.setProtectedHeader({ alg: "HS256" })
.setSubject(userId)
.setIssuer("https://api.jobprep.example")
.setAudience("jobprep-web")
.setIssuedAt()
.setExpirationTime("15m")
.sign(secret);
}
export async function verifyAccessToken(token: string): Promise<{ userId: string; role: string }> {
const { payload } = await jwtVerify(token, secret, {
issuer: "https://api.jobprep.example",
audience: "jobprep-web",
algorithms: ["HS256"]
});
if (typeof payload.sub !== "string" || typeof payload.role !== "string") throw new Error("Invalid token claims");
return { userId: payload.sub, role: payload.role };
}Verification checks the signature and the expiry, issuer, audience and the allowed algorithm list. Fixing the algorithm prevents classic attacks (accepting alg: none, or confusing a public key with an HMAC secret).
Sessions vs JWTs
| Server-side session | JWT (stateless token) | |
|---|---|---|
| Where the state lives | Server store | Inside the token |
| Each request | One lookup in Redis or the database | Verify signature only, no lookup |
| Revocation (logout, ban) | Easy: delete the session | Hard: the token stays valid until it expires |
| Size | Small cookie | Larger (every claim, every request) |
| Scaling across services | Every service needs the session store | Any service with the key can verify |
| Good for | Classic web apps with one back end | APIs used by mobile apps, many services, third parties |
Honest answer: for a normal web app with one back end, sessions in an HttpOnly cookie are simpler and safer. JWTs shine when many services or clients must verify identity without a shared store. Many systems combine them: short-lived JWT access tokens plus a server-side record for refresh tokens.
Access tokens and refresh tokens
Because JWTs are hard to revoke, keep them short-lived:
| Token | Lifetime | Used for | Stored where |
|---|---|---|---|
| Access token | Short (5 to 15 minutes) | Sent with each API request | Memory or an HttpOnly cookie |
| Refresh token | Long (days or weeks) | Only to get a new access token | HttpOnly, Secure cookie scoped to the refresh endpoint, and recorded server-side |
Flow: the access token expires → the client calls POST /auth/refresh with the refresh token → the server checks it against its database → issues a new access token.
Refresh token rotation: every refresh issues a new refresh token and invalidates the old one. If an old refresh token is ever used again, that means it was stolen (both the thief and the user have used it), so the server revokes the whole token family and forces a new login. This is the recommended practice.
Where to store tokens in the browser
| Storage | XSS risk | CSRF risk | Verdict |
|---|---|---|---|
localStorage / sessionStorage | Any injected script can read and steal the token | None | Avoid for long-lived tokens |
| JavaScript memory (a variable) | Lost on refresh; scripts can still use it while the page is open | None | OK for short access tokens, combined with a refresh cookie |
| HttpOnly cookie | JavaScript cannot read it | Sent automatically, so CSRF must be handled | Recommended |
Cookie flags
Set-Cookie: sid=8f2a...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=604800| Flag | Effect |
|---|---|
HttpOnly | JavaScript cannot read the cookie (protects against token theft by XSS) |
Secure | Only sent over HTTPS |
SameSite=Lax | Not sent on cross-site sub-requests (images, fetch, form POSTs from other sites), but sent when the user follows a link to your site. A strong CSRF defence (Lesson 261) |
SameSite=Strict | Never sent cross-site, even on links (users arriving from email links appear logged out) |
SameSite=None; Secure | Sent cross-site; needed when front end and API are on different sites. Then add CSRF protection |
Max-Age / Expires | Lifetime; without them it is a session cookie removed when the browser closes |
Domain, Path | Where the cookie is sent; keep them as narrow as possible |
__Host- name prefix | Forces Secure, Path=/ and no Domain: a hardened cookie |
Logout and revocation
- Sessions: delete the session record and clear the cookie.
- JWTs: delete the refresh token record, clear cookies, and let the short access token expire. For instant revocation (a compromised account), keep a small deny-list of token IDs (
jticlaim) or a per-user "tokens valid after" timestamp checked on each request. - "Log out everywhere": delete all of the user's sessions or refresh tokens.
How to say it in an interview
"Authentication proves who you are and authorisation decides what you can do. With sessions the server stores state and the browser holds a random ID in an HttpOnly, Secure, SameSite cookie; revocation is easy. A JWT carries signed claims, so any service with the key can verify it without a lookup, but it is readable and hard to revoke, so I keep access tokens to about 15 minutes and verify algorithm, expiry, issuer and audience. Refresh tokens are long-lived, stored server-side and in an HttpOnly cookie, and rotated on every use with reuse detection revoking the family. I avoid localStorage for tokens because XSS can steal them, and for a single web back end I usually prefer plain sessions."
Key words
| Word | Meaning |
|---|---|
| Authentication | Proving who you are |
| Authorisation | Deciding what you may do |
| Session | Server-side login state referenced by a cookie |
| JWT | A signed token containing claims |
| Claim | A piece of information in a JWT (sub, exp, role) |
| Access token | A short-lived token sent with API requests |
| Refresh token | A long-lived token used only to get new access tokens |
| Token rotation | Issuing a new refresh token on each use |
| HttpOnly / Secure / SameSite | Cookie flags for safety |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.