---
topic: dev-practices
author: Crashtech Editorial
published: Nov 15, 2026 · read: 4 min
---

Cookies vs Sessions vs JWTs: Where Login State Lives and How It Fails

A comprehensive breakdown of client-side cookies, server-side sessions, and signed JWT tokens, including CSRF defenses and token revocation.

– –

HTTP is natively stateless. Once a user logs in, every subsequent request must present proof of identity. How that proof is generated, where it resides, and how it is validated dictates your system’s susceptibility to Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and horizontal scaling bottlenecks.

The Authentication Spectrum: Sessions vs Tokens

Web applications manage authenticated state through three primary mechanisms:

DimensionServer-Side SessionsStateless JWTsHybrid (Access + Refresh)
State LocationServer memory or RedisEncoded inside client tokenShort-lived token + DB refresh token
Client TransportCookie containing Session IDHTTP Authorization Header or CookieHttpOnly Secure Cookie
Server ValidationQuery Redis/DB on every request ($O(1)$)Fast cryptographic signature checkSignature check, DB lookup on refresh
Instant RevocationInstant: delete key in RedisImpossible until exp window expiresInstant on next refresh boundary
Payload Storage CostMinimal: 32-byte opaque UUIDHigh: hundreds of bytes per HTTP headerModerate
Failure Blast RadiusRedis outage logs out all usersZero database dependency for readsDegrades only during token refresh

1. Server-Side Sessions: Simplicity and Control

In a classic session-based architecture:

  1. The client sends login credentials to /login.
  2. The server authenticates the user and generates a cryptographically random 128-bit string (sessionId).
  3. The server writes the session record into a centralized datastore (such as Redis):
    "sess:9f8e7d6c": { "user_id": 402, "role": "admin", "created_at": 1731604500 }
  4. The server returns an HTTP response with a Set-Cookie header:
    Set-Cookie: sid=9f8e7d6c; Path=/; HttpOnly; Secure; SameSite=Lax
  5. On every subsequent request, the browser automatically attaches the sid cookie. The application performs a fast GET sess:9f8e7d6c lookup in Redis.
[Browser]                                    [API Server]                    [Redis Cache]
    |                                             |                                |
    +--- POST /login (username/password) -------->|                                |
    |                                             +--- SETEX sess:xyz 3600 {...} ->|
    |<-- 200 OK (Set-Cookie: sid=xyz) ------------+                                |
    |                                             |                                |
    +--- GET /api/dashboard (Cookie: sid=xyz) ---->|                                |
    |                                             +--- GET sess:xyz -------------->|
    |                                             |<-- Return session data --------+
    |<-- 200 OK (User Data) ----------------------+                                |

The Invalidation Advantage

If an employee is terminated or a credential is compromised, an administrator triggers a single command: DEL sess:9f8e7d6c. The very next request from that client immediately receives an HTTP 401 Unauthorized.

2. Stateless JWTs: Scaling Without Shared Databases

To eliminate Redis round trips, architectures adopted JSON Web Tokens (JWTs). A JWT encodes claims directly into a Base64URL string containing three parts:

  • Header: Algorithm and token type ({"alg": "RS256", "typ": "JWT"}).
  • Payload: User claims ({"sub": "402", "role": "admin", "exp": 1731608100}).
  • Signature: Digital cryptographic signature computed over the header and payload.

The Revocation Dilemma

Because the token contains its own verification proof, API servers validate requests locally using the public key. No database is queried.

However, if an attacker steals a JWT valid for 24 hours, you cannot revoke it. Changing the signing key invalidates all active users across the entire platform. Maintaining a database of revoked tokens re-introduces the centralized database lookup, destroying the stateless benefit.

3. The Security Fortress: Securing Storage Against Attacks

The most dangerous security vulnerability in modern single-page applications is storing authentication tokens in localStorage or sessionStorage:

Do

  • Store session IDs and JWT tokens exclusively in HttpOnly; Secure; SameSite=Lax cookies.
  • Set explicit expiration windows (max-age) and renew sessions periodically.
  • Implement CSRF protection tokens or rely on strict modern SameSite browser policies.

Don't

  • Never store tokens in browser localStorage or sessionStorage where XSS can steal them.
  • Do not transmit sensitive authentication cookies over unencrypted HTTP connections.
  • Avoid setting long-lived stateless JWT expirations without a refresh rotation strategy.
Set-Cookie: auth_token=eyJhbGci...; HttpOnly; Secure; SameSite=Lax; Max-Age=900; Path=/
  1. HttpOnly: Blocks client-side JavaScript (document.cookie) from reading the cookie. If an attacker injects a malicious XSS script via a comment form, they cannot extract the session token.
  2. Secure: Guarantees the browser only transmits the cookie over encrypted TLS/HTTPS connections.
  3. SameSite=Lax: Prevents the browser from sending the cookie on cross-site requests (such as form submissions originating from third-party phishing domains), providing built-in defense against CSRF attacks.

The Production Gold Standard: Dual-Token Rotation

Enterprise SaaS platforms combine the speed of stateless tokens with the security of server-side sessions:

  • Access Token: Short-lived (5 to 15 minutes) JWT. Handled by API gateways locally with zero database overhead.
  • Refresh Token: Long-lived (7 to 30 days) opaque UUID stored in Redis with automatic rotation on each use.

When the access token expires, the client silently calls /auth/refresh with its HttpOnly refresh cookie. The server validates the refresh token in Redis, verifies it has not been used or revoked, and issues a fresh 15-minute access token.

This pattern isolates database load strictly to periodic refresh cycles while keeping real-time revocation guarantees intact.

Advertisement

Frequently asked questions

What is the primary security vulnerability of storing JWTs in localStorage?

Any Cross-Site Scripting (XSS) vulnerability in your frontend or third-party dependencies allows malicious scripts to read localStorage and extract tokens. Storing tokens in HttpOnly, Secure, SameSite cookies prevents JavaScript from ever reading the token.

How do server-side sessions scale horizontally across multiple instances?

Server instances cannot store sessions in local process memory without sticky sessions. Horizontal scaling requires an external distributed cache like Redis to store session records, allowing any application instance to validate incoming session IDs.

Why is immediate revocation nearly impossible with stateless JWTs?

Stateless JWTs are self-contained and cryptographically verified using a public key without querying a database. To revoke a leaked token before its expiration (exp), systems must maintain a centralized revocation blacklist, turning stateless tokens back into stateful sessions.

What is the recommended modern authentication architecture for SaaS apps?

Use short-lived stateless access tokens (e.g., 5-15 minute JWTs) paired with long-lived opaque refresh tokens stored in Redis. Transmit both via HttpOnly, Secure, SameSite=Lax cookies to defend against both XSS and CSRF attacks.

Sources & further reading

/* Comments */