Skip to the content

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

  1. The user logs in with email and password.
  2. The server creates a session record in a store (Redis or a database): { sessionId: "random", userId: 42, expiresAt }.
  3. It sends the session ID in a cookie: Set-Cookie: sid=8f2a...; HttpOnly; Secure; SameSite=Lax; Path=/.
  4. 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 like role.
  • 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:

TypeScript
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 sessionJWT (stateless token)
Where the state livesServer storeInside the token
Each requestOne lookup in Redis or the databaseVerify signature only, no lookup
Revocation (logout, ban)Easy: delete the sessionHard: the token stays valid until it expires
SizeSmall cookieLarger (every claim, every request)
Scaling across servicesEvery service needs the session storeAny service with the key can verify
Good forClassic web apps with one back endAPIs 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:

TokenLifetimeUsed forStored where
Access tokenShort (5 to 15 minutes)Sent with each API requestMemory or an HttpOnly cookie
Refresh tokenLong (days or weeks)Only to get a new access tokenHttpOnly, 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

StorageXSS riskCSRF riskVerdict
localStorage / sessionStorageAny injected script can read and steal the tokenNoneAvoid for long-lived tokens
JavaScript memory (a variable)Lost on refresh; scripts can still use it while the page is openNoneOK for short access tokens, combined with a refresh cookie
HttpOnly cookieJavaScript cannot read itSent automatically, so CSRF must be handledRecommended
Set-Cookie: sid=8f2a...; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=604800
FlagEffect
HttpOnlyJavaScript cannot read the cookie (protects against token theft by XSS)
SecureOnly sent over HTTPS
SameSite=LaxNot 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=StrictNever sent cross-site, even on links (users arriving from email links appear logged out)
SameSite=None; SecureSent cross-site; needed when front end and API are on different sites. Then add CSRF protection
Max-Age / ExpiresLifetime; without them it is a session cookie removed when the browser closes
Domain, PathWhere the cookie is sent; keep them as narrow as possible
__Host- name prefixForces 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 (jti claim) 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

WordMeaning
AuthenticationProving who you are
AuthorisationDeciding what you may do
SessionServer-side login state referenced by a cookie
JWTA signed token containing claims
ClaimA piece of information in a JWT (sub, exp, role)
Access tokenA short-lived token sent with API requests
Refresh tokenA long-lived token used only to get new access tokens
Token rotationIssuing a new refresh token on each use
HttpOnly / Secure / SameSiteCookie flags for safety

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.