Session authentication stores login state on the server and gives the browser a random session ID in a secure cookie; JWT authentication gives the client a signed token containing its claims, which the server verifies on each request without a database lookup. Sessions are simpler to revoke and a great default for web apps with their own backend; JWTs suit stateless APIs, mobile apps and service-to-service calls, but need short expiry times, refresh tokens and careful storage.

Why does this choice matter?

Authentication sits in front of everything else in your app. The choice affects how you log users out, how you handle a stolen credential, how your app scales across servers, and which attacks you must defend against. Many security problems in real apps come from misusing one of these approaches, not from the approach itself, so understanding the mechanics matters more than picking the fashionable option.

How does session authentication work?

  1. The user logs in with a password (checked against a bcrypt or Argon2 hash).
  2. The server creates a session record (user ID, expiry, metadata) in a store such as a database or Redis, keyed by a long random ID.
  3. The server sends the ID in a cookie marked HttpOnly, Secure and SameSite.
  4. On each request, the browser sends the cookie automatically; the server looks up the session and knows who the user is.
  5. Logging out deletes the session record, which immediately invalidates the cookie.

How does JWT authentication work?

A JSON Web Token has three parts: a header, a payload of claims (user ID, roles, expiry) and a signature. The server signs it with a secret (HMAC) or a private key (RSA, ECDSA) and gives it to the client. On each request the client sends the token, usually in an Authorization: Bearer header or a cookie, and the server verifies the signature and expiry. No lookup is needed, which is why JWTs are called stateless. The payload is only encoded, not encrypted: anyone holding the token can read it, so never put secrets in it.

How do they compare?

AspectServer-side sessionsJWT
StateStored on the serverCarried in the token
Revocation (logout, ban)Immediate: delete the sessionHard until expiry; needs short lifetimes or a denylist
Scaling across serversNeeds a shared store (database or Redis)Any server with the key can verify
Per-request costA fast store lookupSignature verification
SizeSmall random IDLarger; grows with claims
Best forWeb apps with their own backendAPIs, mobile apps, microservices, single sign-on

What are the main security risks?

RiskAffectsMitigation
XSS stealing tokensTokens stored in localStorageStore in HttpOnly cookies; prevent XSS with output encoding and a Content Security Policy
CSRFAny cookie-based authSameSite cookies plus CSRF tokens for state-changing requests
Session fixationSessionsRegenerate the session ID at login
Weak or leaked signing keyJWTStrong keys in a secrets manager; rotate keys
Algorithm confusion ("alg: none")JWTAllow only expected algorithms in verification
Stolen long-lived tokenJWTShort access-token lifetime; refresh-token rotation

What are refresh tokens?

To get JWT convenience without long-lived risk, apps issue a short-lived access token (for example 15 minutes) and a longer-lived refresh token stored securely (ideally an HttpOnly cookie). When the access token expires, the client uses the refresh token to get a new one. Rotation issues a new refresh token each time and invalidates the old; if an old one is reused, that signals theft and the whole family can be revoked. Notice that refresh tokens are usually stored and checked on the server, so a "stateless" design quietly becomes partly stateful again.

Maximum window a stolen access token stays usable, by lifetime
15 minutes0.25 h
1 hour1 h
24 hours24 h
7 days168 h

Arithmetic: without a denylist, a stolen JWT works until it expires.

Which should you choose?

  • Server-rendered web app or a single frontend with its own backend: sessions in a shared store, with secure cookies and CSRF protection. Simple, revocable, battle-tested.
  • Mobile apps calling your API: short-lived access tokens (often JWTs) with refresh-token rotation, stored in the platform's secure storage.
  • Microservices: JWTs or signed tokens for service-to-service identity, often issued by a central identity provider.
  • "Log in with Google" or enterprise single sign-on: OAuth 2.0 and OpenID Connect, which use tokens (ID tokens are JWTs); your app often then creates its own session.

What does good password and account handling include?

Whichever approach you choose: hash passwords with bcrypt or Argon2, rate-limit and temporarily lock accounts after repeated failed logins, require strong passwords, verify email addresses, offer two-factor authentication for sensitive accounts, sign users out of other devices after a password change, and log authentication events for investigation. These matter as much as the session-versus-token decision.

How does authorisation fit in?

Authentication answers "who are you?"; authorisation answers "what may you do?". Both sessions and JWTs only establish identity (and perhaps roles). Every request must still check permissions on the server: can this user read this order, edit this course, see this admin page? Broken access control, where authenticated users reach data that isn't theirs, is one of the most common serious web vulnerabilities, regardless of the auth mechanism.

  • HttpOnly: JavaScript can't read the cookie, which limits damage from XSS.
  • Secure: the cookie is only sent over HTTPS.
  • SameSite=Lax or Strict: the browser doesn't send it on most cross-site requests, which reduces CSRF risk.
  • A sensible expiry plus server-side idle and absolute timeouts.
  • A narrow path and domain, so the cookie isn't sent where it isn't needed.

Behind a proxy or load balancer, make sure your framework knows the original request was HTTPS, or Secure cookies won't be set; this is a common deployment mistake that silently breaks logins.

What mistakes do developers make with JWTs?

  • Long expiry times with no revocation plan.
  • Putting sensitive data in the payload, which anyone can decode.
  • Not validating the algorithm, issuer, audience and expiry.
  • Using JWTs as a session replacement in a simple web app, then rebuilding sessions badly to support logout.

What about passkeys?

Passkeys, based on the WebAuthn standard, let users sign in with their device's fingerprint, face unlock or PIN instead of a password. The private key never leaves the device and can't be phished, which removes the most common way accounts are stolen. Passkeys replace the password check, not the session: after a passkey login, your app still creates a session or issues tokens exactly as described above. Supporting them alongside passwords is increasingly common in modern apps, and major browsers and phone platforms already support them.

How is this asked in interviews?

Expect "how would you implement logout with JWTs?", "where would you store tokens in a browser and why?" and "how do you prevent CSRF with cookie-based auth?". Good answers discuss trade-offs instead of declaring one approach always better.

How do you practise?

Build the same small app twice: once with server-side sessions in Redis or a database, once with access and refresh tokens. Then try to break each: steal a token via a simulated XSS bug, attempt CSRF, and test logout and password-change behaviour. Authentication with JWT, OAuth2 and bcrypt is part of Program Zero's full-stack development course, and web security is covered again in the security course. Read building a REST API with Node.js for where authentication fits in an API.