JWT vs session is really a choice between two kinds of credential. A session is an opaque random ID whose meaning lives in your server-side store. A JWT is a signed, self-contained set of claims that any service holding the key can verify without a lookup. For a typical first-party web app (your frontend, your backend, one domain), server-side sessions in an HttpOnly, Secure, SameSite cookie are the better default, because logout and revocation are instant and nothing secret is ever readable by JavaScript. JWTs earn their place when separate services or third parties must verify identity without calling your session store, and even then they work best short-lived and paired with rotating refresh tokens.

Most "JWT vs cookies" arguments mix up two separate questions: what the token is (opaque ID or self-contained JWT) and where the browser keeps it (cookie or localStorage). You can put a JWT in an HttpOnly cookie, and you can put a session ID in localStorage (please don't). This guide separates the two, then compares them on revocation, logout, XSS, CSRF, size, scaling and refresh-token rotation, with short Node.js examples I ran on Node 24 with jose 6.2.

What each approach actually is

Server-side session. On login, the server generates a random identifier, stores {userId, createdAt, ...} under it in Redis, Postgres or memory, and sends the identifier in a cookie. Every request looks the ID up. The OWASP Session Management Cheat Sheet requires at least 64 bits of entropy from a CSPRNG and recommends 128 bits if you generate IDs yourself.

JWT. On login, the server signs a JSON payload (sub, exp, roles, tenant, whatever you need) with an HMAC secret or a private key. Anyone with the secret or public key can verify it offline. The token is the session state; the server does not need to remember it.

Here are both, minimally, in the same script:

import { randomBytes, createHash } from 'node:crypto'
import { SignJWT, jwtVerify } from 'jose'

// Opaque session: random ID in a cookie, state on the server
const sessions = new Map() // stand-in for Redis/Postgres
const hash = (s) => createHash('sha256').update(s).digest('hex')

function createSession(userId) {
  const id = randomBytes(32).toString('base64url')   // 256 bits
  sessions.set(hash(id), { userId, createdAt: Date.now() }) // store only a hash
  return `__Host-sid=${id}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=28800`
}

// JWT: claims signed into the token itself
const secret = new TextEncoder().encode(process.env.JWT_SECRET)
const jwt = await new SignJWT({ role: 'admin', org: 'acme' })
  .setProtectedHeader({ alg: 'HS256' })
  .setSubject('user_42').setIssuer('https://auth.example.com').setAudience('api')
  .setIssuedAt().setExpirationTime('10m').setJti(randomBytes(16).toString('hex'))
  .sign(secret)

const { payload } = await jwtVerify(jwt, secret, {
  algorithms: ['HS256'],               // pin the algorithm
  issuer: 'https://auth.example.com',
  audience: 'api',
})

Storing only a hash of the session ID means a leaked database dump does not hand out live sessions. Pinning algorithms in jwtVerify is the defence against the "key confusion" or "algorithm confusion" attacks the OWASP JWT Cheat Sheet describes, along with making sure "alg":"none" is never accepted.

JWT vs session: the comparison table

Criterion Server-side session (opaque ID) JWT (self-contained)
Revocation Delete the row; effective on the next request Valid until exp unless you add a denylist or version check
Logout Real: server forgets the session Client discards the token; server cannot forget what it never stored
Per-request cost One store lookup (Redis/DB) Signature verification, no I/O
Size on the wire ~43 bytes for a 256-bit ID 285 bytes in my minimal example; grows with every claim
Horizontal scaling Needs a shared store all nodes can reach Any node with the key can verify
Cross-service / third-party verification Each service must call the session store Built for it (especially with asymmetric keys and JWKS)
Stale claims (role change, ban) Read fresh from the store each request Old claims live until the token expires
Main failure mode Session store outage logs everyone out Stolen token works until expiry; key leak forges any user

Those size numbers are from the demo above: the base64url session ID was 43 characters, and a JWT with two custom claims plus sub, iss, aud, iat, exp and jti was 285. Real-world tokens carrying permissions arrays or user profiles are frequently over a kilobyte, and a cookie-borne token is sent on every request to that origin, including images and CSS. RFC 6265 only requires browsers to support at least 4,096 bytes per cookie (name, value and attributes together), so oversized JWT cookies are a real way to break login.

Revocation and logout: the deciding factor for most apps

This is where the two models differ most, and it is why I default to sessions. Continuing the demo:

destroySession(sid)
getSession(sid)            // null: the next request is unauthenticated

// The JWT issued earlier still verifies after "logout":
(await jwtVerify(jwt, secret, { algorithms: ['HS256'] })).payload.sub
// 'user_42'

When a user clicks "log out", changes their password, or an admin disables a compromised account, you need the existing credential to stop working. With sessions, that is a DELETE. With JWTs, your options are:

  1. Short expiry. Make access tokens live 5 to 15 minutes and accept that window. Simple, but a disabled user keeps access until the token lapses.
  2. Denylist. Store revoked token identifiers until their exp. OWASP's JWT cheat sheet says to key it on jti and iss, and warns that using the raw token or SHA-256(token) as the key "is not safe" because JWT malleability can bypass it.
  3. Per-user version or "valid after" timestamp. Store tokens_valid_after on the user; reject any token with iat earlier than that. One field kills every token for a user at once.

Options 2 and 3 both put a lookup back on every request, which means you have rebuilt a session store with extra steps. That is fine when the JWT's other properties (offline verification by other services) are what you actually need, but it removes the "stateless" argument for a single web app.

Where the credential lives in the browser matters more for XSS than which format it is. Either way, a strict nonce-based Content Security Policy makes XSS harder to exploit in the first place.

  • localStorage / sessionStorage: readable by any JavaScript on the origin. One XSS bug, one compromised npm dependency, or one malicious third-party script can read the token and send it to an attacker, who then uses it from their own machine until it expires. The OWASP session cheat sheet says plainly not to store authentication tokens, session IDs, JWTs or refresh tokens in web storage.
  • HttpOnly cookie: per MDN's Set-Cookie reference, it "Forbids JavaScript from accessing the cookie", while the browser still attaches it to fetch() and XHR requests.

Be honest about what HttpOnly buys you. XSS on your origin can still make authenticated requests as the user while the page is open; it just cannot steal the credential for later or use it from elsewhere. That is a real reduction in blast radius, not immunity, which is why a strict CSP still matters.

The cookie attributes I use for a session cookie, matching OWASP's recommendations:

Set-Cookie: __Host-sid=emkWcm9-IkbGbrqIN1UHKtoAz8aoQf0jLtYdT2dnmlY; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=28800

The __Host- prefix forces Secure, Path=/ and no Domain attribute, so a subdomain cannot set or overwrite the cookie. SameSite=Lax keeps the cookie off cross-site subresource requests and cross-site POSTs while allowing normal top-level navigation into your app; use Strict if your app does not need logged-in state on links arriving from other sites.

CSRF: the cost of cookies

Cookies are sent automatically, which is what makes cross-site request forgery possible. Bearer tokens in an Authorization header are not attached automatically, so a classic CSRF attack does not apply to them. That is the one real security advantage of "JWT in localStorage sent as a header", and it is not worth trading XSS exposure for.

With cookie-based auth (session or JWT), protect state-changing requests with layers:

  • SameSite=Lax or Strict on the auth cookie. OWASP treats this as defence in depth, not a replacement for CSRF tokens.
  • A CSRF token (synchronizer token or signed double-submit) on forms and mutating API calls, which most frameworks provide.
  • Rejecting mutating requests whose Origin (or Sec-Fetch-Site) header shows a cross-site source.
  • Never performing state changes on GET.

Frameworks such as Better Auth and Auth.js ship these defaults; if you are choosing between them, our Better Auth vs Auth.js comparison covers how each handles sessions, JWT strategies and CSRF.

Horizontal scaling: less of a problem than it sounds

"Sessions don't scale" was a fair complaint when sessions lived in one app server's memory. With a shared store, every app node can validate any session, and Redis or a primary-key lookup in Postgres is a cheap operation compared with the database work the request does anyway. The real trade-offs are operational: the session store is now a dependency whose outage logs everyone out, and multi-region deployments need replication or region-pinned sessions.

JWTs genuinely shine when the verifier is not your app. An API gateway, a separate microservice owned by another team, a partner integration, or a mobile backend can verify an asymmetric-signed token by fetching your public keys (JWKS) and never touching your session database. That is the use case the format was designed for, and it is why OAuth access tokens and OIDC ID tokens are so often JWTs. It is also why deploy pipelines can authenticate to clouds with short-lived OIDC tokens instead of stored keys, as covered in our GitHub Actions OIDC guide.

Refresh-token rotation, done properly

If you use short-lived JWT access tokens, you need refresh tokens, and refresh tokens are long-lived bearer credentials that deserve more care than the access tokens. RFC 9700 (Best Current Practice for OAuth 2.0 Security, January 2025) states: "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation." Under rotation, each refresh returns a new refresh token and invalidates the previous one, while the server remembers how they are related. If an already-used token is presented, either the client or an attacker has a stolen copy; the server cannot tell which, so it revokes the whole chain.

A compact implementation of that reuse detection:

const refresh = new Map() // tokenHash -> { family, userId, used }
const h = (t) => createHash('sha256').update(t).digest('hex')

function issueRefresh(userId, family = randomBytes(8).toString('hex')) {
  const t = randomBytes(32).toString('base64url')
  refresh.set(h(t), { family, userId, used: false })
  return t
}

function rotate(t) {
  const rec = refresh.get(h(t))
  if (!rec) throw new Error('unknown refresh token')
  if (rec.used) {                       // replay: revoke the whole family
    for (const [k, v] of refresh) if (v.family === rec.family) refresh.delete(k)
    throw new Error('refresh token reuse detected; family revoked')
  }
  rec.used = true
  return issueRefresh(rec.userId, rec.family)
}

Running the scenario where an attacker steals r1 after the real client has already rotated to r2:

attacker replays r1 -> refresh token reuse detected; family revoked
legit client with r2 -> unknown refresh token

The legitimate user is forced to log in again, which is exactly the point: the theft is detected and contained. In production you would add a short grace period for concurrent tabs racing to refresh, store the records in your database with an absolute family lifetime, and keep the refresh token in an HttpOnly cookie scoped to the refresh endpoint (Path=/auth/refresh) so it is not sent with every request.

Notice what this costs: a server-side table of refresh tokens and families. A "stateless" JWT architecture that handles logout and theft properly ends up stateful at the refresh layer. That is fine; just make the decision knowingly.

Hybrid: sessions at the edge, JWTs behind it

The architecture I recommend for most product teams with more than one backend service is the backend-for-frontend (BFF) pattern, which OWASP also points to:

  • The browser only ever holds an opaque __Host- session cookie.
  • Your web backend (the BFF) maps that session to a user and, when calling internal APIs, mints or exchanges a short-lived JWT with exactly the claims that service needs.
  • Internal services verify JWTs offline; the browser never sees them.

You get instant logout and no tokens in JavaScript at the browser edge, and stateless verification between services. If you are adding passkeys to strengthen login, the same split applies: WebAuthn establishes the identity, and a server-side session carries it afterwards.

Decision table: which should you use?

Your situation Use
Server-rendered or same-origin SPA with its own backend Server-side session in __Host- cookie
Need instant logout, password-change invalidation, admin "kill session" Server-side session
Multiple internal services verifying the user Session at the edge, short-lived JWTs internally (BFF)
Public API consumed by third parties OAuth 2.0 access tokens (often JWTs) with scopes
Native mobile app talking to your API Short-lived access token plus rotating or sender-constrained refresh token
Service-to-service or CI-to-cloud auth Short-lived signed tokens (JWT/OIDC)
"We want stateless so we don't need Redis" Reconsider: logout and revocation will add state back

Frequently Asked Questions

Is JWT more secure than session cookies?

No. Neither format is inherently more secure. The security comes from where the credential is stored (HttpOnly cookie beats localStorage), how quickly it can be revoked (sessions win), and how carefully it is validated (JWTs add algorithm and key-handling pitfalls). For a first-party web app, a well-configured session cookie has fewer ways to go wrong.

Yes, and if you use JWTs in a browser it is the better place for them. You then inherit cookie concerns (CSRF protection, the 4 KB size budget) while keeping JWT concerns (revocation). Many frameworks' "JWT session strategy" works exactly this way.

How do I log out a user with JWT?

Delete the token client-side, revoke the refresh token server-side, and either accept access-token validity until exp or check a denylist keyed on jti and iss (or a per-user "valid after" timestamp) on every request. Keep access tokens short so the exposure window is small.

Are sessions bad for microservices and scaling?

Not with a shared store like Redis or your primary database; every node can validate any session. The real issue in microservices is that each service would need to reach the store, which is why the common pattern is a session at the edge and short-lived JWTs between services.

Should I store JWTs in localStorage?

No. Any script on the page can read localStorage, so a single XSS or compromised dependency exposes the token for reuse from anywhere. OWASP's session cheat sheet advises against storing any authentication token in web storage.

What is refresh token rotation?

Each time a refresh token is used, the server issues a new one and invalidates the old one. If an old token is ever presented again, the server treats it as theft and revokes the whole token family. RFC 9700 requires rotation or sender-constrained tokens for public clients.

Bottom Line

For a web app talking to its own backend, choose server-side sessions in a __Host-, HttpOnly, Secure, SameSite cookie: instant logout and revocation, tiny cookies, nothing for XSS to steal. Reach for JWTs where their offline verification pays off, such as other services, third-party APIs, mobile clients and machine identity, and keep them short-lived with rotating refresh tokens. If you need to inspect a token while debugging, remember that a JWT payload is only base64url-encoded, not encrypted; a Base64 decoder shows exactly what you are sending, which is also a good reminder never to put secrets in claims.