Skip to content
RankCore.AI
← All posts

Sessions vs JWTs: A Technical Guide to Login, Logout, and Token Design

· Authentication, JWT, Sessions, Security, OAuth

After a user proves who they are, how does your system remember them on the next request? HTTP is stateless, so something has to carry identity forward. There are two dominant answers: server-side sessions and JSON Web Tokens (JWTs). The short video above gives the headline in about two minutes. This guide is the study version: how each mechanism works on the wire, where each one breaks, what the video simplified, and how to choose.

I will flag every place the video needs a correction or a nuance, so you do not carry a half-truth into a review. Type out the HTTP traces and the decode exercise, then use the FAQ and the test list as a checklist.

1. The problem both approaches solve

The server verifies a credential once (password, SSO, passkey). From then on you do not want to ask again on every click, so it hands the client something that stands in for that identity. On every request the server must answer three questions quickly:

  1. Authenticity: did we issue this, or was it forged?
  2. Freshness: is it still valid, or expired or revoked?
  3. Meaning: who is this, and what may they do?

Sessions and JWTs differ in where the answers live. With sessions they live on the server and the client holds an opaque pointer. With JWTs they live inside the token and the server verifies it cryptographically. That difference drives every trade-off below: scalability, revocation, size, security surface, and operational cost.

2. Server-side sessions, step by step

  1. The user logs in and the server validates the credentials.
  2. The server creates a session record: a random, unguessable ID mapped to the user ID, creation time, and last activity.
  3. The record is stored server-side: in process memory (fine for a prototype) or a shared store such as Redis or a SQL table (what production needs).
  4. The ID goes to the browser in a Set-Cookie header, and the browser attaches it to every request to that site.
  5. The server looks the ID up, loads the record, and treats the request as that user.
  6. On logout the server deletes the record, and the cookie points to nothing.

On the wire, a hardened login looks like this:

HTTP/1.1 200 OK
Set-Cookie: __Host-sid=9f4c1e2a7b...; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=1800

GET /api/me HTTP/1.1
Host: app.example.com
Cookie: __Host-sid=9f4c1e2a7b...
AttributeWhat it doesDefends against
HttpOnlyHides the cookie from document.cookieCookie theft via XSS
SecureHTTPS onlySniffing on plain HTTP
SameSite=Lax or StrictLimits cross-site sendingMost CSRF attacks
Max-Age or ExpiresBounds lifetimeLong-lived stolen cookies
__Host- prefixForces Secure, Path=/, no DomainCookie injection from subdomains

HttpOnly, Secure, SameSite, and the __Host- prefix are defined in the cookie specification. OWASP recommends SameSite=Strict or Lax as defense in depth, not as a replacement for a CSRF token. Never set SameSite=None without Secure.

Why teams like sessions. Revocation is instant: delete the record and that session is dead, which is the strongest argument for sessions and the one the video highlights. The credential is a tiny opaque value, and you can change what it means mid-flight — bump a role, force step-up authentication, or require a re-login after a password change.

What sessions cost. Every request needs a store lookup. That is rarely the bottleneck, but if the store is down, nobody is logged in. In-memory sessions break as soon as the load balancer sends the user to another instance, and they vanish when autoscaling terminates a machine. Use a shared store, not sticky sessions. Cookies are awkward across origins, and because browsers attach them automatically, you must defend against CSRF.

Nuance on the video: "HttpOnly means page scripts can't read it" is true and blocks the classic steal the cookie payload. It does not stop XSS from using the session: injected script can still make same-origin requests that carry the cookie. You still need output encoding and a Content Security Policy. A second nuance: "delete the session and you're signed out everywhere" is true when you delete all of that user's session records. Deleting only the current row signs out one device. Design both a per-device logout and a global one.

Session IDs, fixation, and timeouts

Treat the session ID as a temporary stand-in for the password. OWASP requires at least 64 bits of entropy from a cryptographically secure random generator, and recommends 128 bits plus a uniqueness check if you roll your own. Prefer the ID your framework already generates, and do not put it in the URL: it leaks into history, logs, the Referer header, and screenshots.

Session fixation is the attack where an attacker plants a known session ID on the victim, waits for them to log in, and reuses that same ID. The fix is easy to forget: issue a new session ID at login and invalidate the pre-login ID. Set both an idle timeout and an absolute timeout. The server must enforce expiry; a browser beforeunload handler is not a logout mechanism.

3. JWTs, step by step

A JWT (RFC 7519) is a compact way to carry claims. The usual login token is a signed JWT in JWS compact form (RFC 7515): three Base64URL parts joined by dots, header.payload.signature. Decoded, a typical one looks like this:

// header
{ "alg": "RS256", "typ": "JWT", "kid": "2026-11-key-1" }

// payload
{ "iss": "https://auth.example.com", "sub": "user_8c1f",
  "aud": "https://api.example.com", "role": "editor",
  "iat": 1790000000, "exp": 1790000900, "jti": "b1f0c6a2-..." }
  • Header: the signing algorithm (alg) and usually a key ID (kid).
  • Payload: the claims. RFC 7519 registers iss (issuer), sub (subject), aud (audience), exp (expiry), nbf (not-before), iat (issued-at), and jti (unique ID). None is mandatory in the RFC; your application decides which are required.
  • Signature: computed over base64url(header) + "." + base64url(payload). Change one character of the payload and it no longer matches.

The token typically travels as Authorization: Bearer <token> (RFC 6750). The server verifies the signature, checks exp, iss, and aud, and trusts the claims. That is the video's "server remembers nothing."

Exercise: decode a JWT yourself

You do not need a library to read a signed JWT, and that is the point of the warning in the video. Split on the dots, then Base64URL-decode the first two parts (- and _ instead of + and /; padding is often omitted):

import base64, json
token = "paste.token.here"  # use a demo token, never a production one
def dec(part):
    pad = "=" * (-len(part) % 4)
    return json.loads(base64.urlsafe_b64decode(part + pad))
header, payload, *_ = token.split(".")
print(dec(header))
print(dec(payload))

You will see the claims in plain text. Decoding is not verification. Verification means checking the signature with a key you already trust, then checking exp, iss, and aud.

Why teams like JWTs. Any service holding the verification key can validate a token on its own: no shared store, no sticky routing. That suits gateways and microservices behind one identity provider, and it works in mobile apps and CLIs that have no cookie jar.

What JWTs cost. A signed token is valid until exp no matter what the server does, so revocation is hard and claims go stale: remove admin at 10:00 and a token that still says role: admin until 10:15 keeps that user an admin. Tokens are large and ride on every request; many HTTP servers default to a total header limit around 8 KB. Verification has crypto footguns (section 4), and browser storage is a real design problem (section 5).

Correction on the video: It says the signature uses "a secret key that only the server holds" and that "any server with the key can verify any request." That describes symmetric signing (HS256), where the same secret signs and verifies. For microservices that is the weakest fit: every verifying service could also mint tokens. Multi-service systems normally use asymmetric signing (RS256, ES256, or EdDSA). The identity provider signs with a private key it never shares; every other service verifies with the public key, usually from a JWKS endpoint.

Nuance on "the server remembers nothing": The access-token hot path can be stateless. Logout, refresh, key rotation, and reuse detection all reintroduce server-side state. The useful question is not "stateful or stateless?" It is where we keep the state we cannot avoid.

Nuance on "encoded, not encrypted": The video is exactly right for ordinary login tokens. A standard signed JWT is a JWS (RFC 7515): readable by anyone, tamper-evident only. An encrypted form, JWE (RFC 7516), exists but is rare for access tokens. Never put passwords, API secrets, or sensitive personal data in the payload.

4. JWT pitfalls to check for

Most real-world JWT breaches are implementation errors, not broken cryptography. These are the pitfalls I check in every review, following the IETF's JSON Web Token Best Current Practices (RFC 8725):

  1. alg: none and algorithm confusion. Early libraries accepted "alg": "none" or let an attacker flip RS256 to HS256 and sign with the public key as an HMAC secret. Fix: pin allowed algorithms in server configuration and never let the header choose.
  2. Skipping claim checks. A valid signature is not enough. Check exp, iss, and aud. Skipping aud lets a token issued for service A be replayed against service B.
  3. Weak HMAC secrets. A short or predictable secret can be brute-forced offline from any captured token. Use 256 bits of random key material, or asymmetric keys.
  4. Long-lived access tokens. The video's "around 15 minutes" is a common practice, not a number required by RFC 7519 or OAuth 2.0. Prefer minutes, not days, for bearer access tokens.
  5. No key rotation. Use kid, publish a JWKS, and keep the old key in the set until every in-flight token signed with it has expired.
  6. Trusting jku, x5u, or an embedded jwk in the header. Fetch keys only from your configured issuer. Treat kid as a selector among keys you already trust, never as the source of trust.

A correct verification with the widely used jose library:

import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));

export async function authenticate(token) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: "https://auth.example.com",
    audience: "https://api.example.com",
    algorithms: ["RS256"], // pinned, never taken from the header
    clockTolerance: 30
  });
  return payload;
}

5. Where the browser keeps a JWT

StorageXSS impactCSRF impact
localStorageAny injected script can read and exfiltrate itNot affected
In-memory variableNothing persists to steal later; script can still call your API while the page is openNot affected
HttpOnly cookieScript cannot read itAffected, so use SameSite and CSRF defenses

A solid pattern for a single-page app: access token in memory, refresh token in an HttpOnly; Secure; SameSite cookie scoped to the refresh endpoint. A page reload silently calls /auth/refresh. Note the irony: once the JWT sits in an HttpOnly cookie, you have rebuilt most of a session with a bigger cookie. That is a legitimate hybrid, and a sign that the real decision is about revocation and architecture, not the acronym.

6. Short access tokens plus a tracked refresh token

The video's recommendation is the industry-standard compromise:

  • Access token: a JWT valid for a short time (a common choice is 5 to 15 minutes), verified statelessly.
  • Refresh token: long-lived (hours to weeks), tracked by the server, used only at the token endpoint to get a new access token.
  • Logout = revoke the refresh token. The current access token still works until it expires, at most minutes, but no new one can be minted.

You accept up to N minutes of delayed revocation in exchange for stateless checks on the hot path.

Nuance on "the server does track the refresh token": That is what you should do. RFC 9700 (OAuth 2.0 Security Best Current Practice, January 2025) says refresh tokens for public clients — a mobile app or SPA that cannot keep a client secret — must be sender-constrained (mTLS, RFC 8705, or DPoP, RFC 9449) or rotated, with reuse detection. A "stateless refresh JWT" the server cannot revoke is a long-lived bearer secret.

Rotation and reuse detection. Each use issues a new refresh token and invalidates the old one. If a used token is presented again, the server assumes theft and revokes the family:

1. Client A holds RT1. An attacker steals RT1.
2. The attacker redeems RT1; the server issues RT2 to the attacker and marks RT1 used.
3. Client A redeems RT1; the server sees a used token presented again.
4. The server revokes the whole family. Both must log in again; the attacker is locked out.

Two browser tabs, or a retry after a lost response, can present the same refresh token twice legitimately. Serialize refreshes so only one is in flight, and keep any grace window tight. Store refresh tokens hashed (SHA-256 is fine for high-entropy random values) with user, device, family ID, expiry, and used or revoked flags.

If minutes of delay are unacceptable, add a jti denylist with a TTL equal to the token's remaining life, a per-user min_iat after a password change or global logout, or token introspection (RFC 7662) on high-risk endpoints. Every revocation fix adds state back: purely stateless authentication and instant revocation are mutually exclusive.

ID tokens are not access tokens

If you adopt OpenID Connect, you will see two JWTs. The ID token is for the client, so it can know who authenticated. The access token is for the API. Do not send an ID token as Authorization: Bearer to your API. They have different audiences, lifetimes, and claims, and mixing them up is a common mistake.

7. How to choose

  1. Traditional or same-origin web app? Choose sessions: HttpOnly cookies, instant logout, least client complexity. This is the right default for most products and banking-style apps.
  2. Many independent services trusting one login? Use JWT access tokens from a central identity provider, verified with public keys at the gateway or service.
  3. Native mobile apps or third-party API clients? Use tokens in the Authorization header with refresh rotation, and keep refresh tokens in the OS secure store (Keychain, Keystore).
  4. How costly is a few minutes of stale authorization? If a revoked admin acting for 10 minutes is unacceptable, favour sessions or add a denylist.
  5. Delegating access to third parties? Use a proven identity provider and OpenID Connect; do not hand-roll an authorization protocol.

Many mature systems end up hybrid: a session cookie between the browser and a backend-for-frontend (BFF), and short-lived tokens from the BFF to internal services. The browser never holds a bearer token, so XSS has nothing to steal, while the internal mesh keeps stateless verification.

8. Operational concerns

  • Secrets and keys belong in a secret manager, never in the repo or the front-end bundle.
  • Least privilege. Keep the authorization model small and auditable. Personal access tokens are long-lived bearer credentials with the same revocation trade-offs.
  • Observability. Log auth failures, refresh-reuse events, and odd device or location changes.
  • Logout semantics. Decide whether logout means this device or everywhere. Sessions make "all devices" trivial; tokens need a family revoke plus a min_iat bump.
  • HTTPS everywhere. A Secure cookie on an app that still serves HTTP can be tricked into leaking the session. Use TLS for the whole session and turn on HSTS.

Test before you ship: a tampered payload, alg: none, the wrong key, the wrong aud or iss, and an expired token are all rejected; a reused refresh token revokes its family; the old cookie stops working after logout; cookies carry HttpOnly, Secure, and SameSite; login issues a new session ID.

9. FAQ

Is a JWT more secure than a session? No. Security depends on cookie flags, token lifetime, key management, storage, and revocation — not on the acronym. A JWT in localStorage with a long expiry is usually worse than a boring HttpOnly session cookie.

Can I just put the JWT in an HttpOnly cookie? Yes. You then have to defend against CSRF as you would with a session, and you still have the revocation problem unless you track and rotate refresh tokens. The cookie solved storage; it did not solve logout.

If I revoke the refresh token, why can the access token still work? Because a signed access token is valid until exp. Revoking the refresh token only stops new access tokens. If those leftover minutes are unacceptable, add a denylist or a min_iat check, or use sessions.

Do I need Redis if I use sessions? You need a store every application server can reach. Redis is a common choice, not a requirement. A SQL table works at moderate scale. In-process memory works only on a single server, and a restart logs everyone out.

10. Interview questions

"Sessions or JWTs?" A weak answer picks one. A strong answer starts with requirements — client types, number of services, how fast access must be revocable — and names the trade-off: sessions centralize state to gain control; JWTs distribute state to gain scale and give up easy revocation.

"How do you log out a JWT user?" Be honest: you cannot invalidate the access token itself without adding state. You shorten its life, revoke the refresh token, and where required add a jti denylist or min_iat check.

11. Summary

  • Sessions keep identity on the server and give the client a random ID in an HttpOnly cookie. They win on instant logout and small credentials, and need a shared store and CSRF protection.
  • JWTs put signed claims in the token so any service with the public key can verify without a lookup. They win on cross-service and non-browser use, and lose on revocation, stale claims, size, and implementation pitfalls.
  • The payload of a signed JWT is encoded, not encrypted. Never store secrets in it.
  • Use asymmetric signing when more than one service verifies, and pin the algorithm server-side.
  • Short access token plus a tracked, rotating refresh token is the practical middle path. For public clients, RFC 9700 requires rotation or sender-constrained refresh tokens.
  • Choose from requirements, not fashion. Same-origin web app with instant logout: sessions. Many services and mobile clients: tokens. Large systems: often a hybrid with a BFF.

Follow @rankcore.ai on Instagram, and read more guides on blog.rankcore.ai.

Want to go deeper?

Our step-by-step video courses turn these ideas into results.

See courses

Comments

Sign in or create a free account to join the discussion.

No comments yet — be the first.