Security · Backend · API · Node.js

JWT vs Sessions: Choosing Authentication for Web Applications

The differences between session cookies and JWTs, safe storage, token refresh, revoking access, XSS and CSRF risks, and practical recommendations for web apps.

Sander Yazıcıoğlu Published: 3 min read Türkçe oku

JWT vs Sessions: Choosing Authentication for Web Applications

"Should we use JWTs or sessions?" is often decided like a fashion choice rather than a technical one. A wrong choice means either needless complexity or a security hole. Here is when I use each, and the mistakes I see most.

The two models

Server-side sessions: when a user logs in, the server creates a session record (Redis, a database) and sends the browser a cookie containing only a random session id. On each request the server looks the id up.

JWT (JSON Web Token): the server issues a signed token containing user claims and an expiry. On each request the server verifies the signature; no record is needed.

Comparison

CriterionSessionJWT
Server stateYes (session store)No (stateless)
Instant logout / revocationEasy: delete the recordHard: valid until expiry
ScalingNeeds a shared storeEach service verifies on its own
SizeSmall cookieCan grow, sent on every request
Between microservicesNeeds central lookupNatural fit
Mobile / third-party clientsCookie handling neededEasy

My defaults

  • Classic web app (browser + your own backend): server-side sessions with an HttpOnly cookie. Simple, secure, instantly revocable.
  • Mobile apps, public APIs, service-to-service: short-lived JWT access tokens plus refresh tokens.
  • Enterprise sign-in (SSO): OpenID Connect; leave identity to an identity provider rather than building it yourself.

Where to store the token

The most common mistake: keeping a JWT in localStorage. Any JavaScript running on the page (an XSS bug or a malicious dependency) can read it and send it away.

In the browser, the safer option is to carry the token in a cookie too:

res.cookie('session', token, {
  httpOnly: true,   // JavaScript can't read it
  secure: true,     // HTTPS only
  sameSite: 'lax',  // blocks most CSRF scenarios
  maxAge: 15 * 60 * 1000
});

With cookies, CSRF risk comes back: close it with SameSite=Lax or Strict, plus CSRF tokens on state-changing requests.

Rules if you use JWTs

  1. Short lifetimes: access tokens of 5–15 minutes. Even if stolen, the damage is limited.
  2. Refresh token rotation: issue a new refresh token on every refresh and invalidate the old one, so reuse of a stolen token is detected.
  3. Pin the algorithm: specify the allowed algorithm explicitly when verifying; don't leave the door open to alg: none or algorithm-confusion attacks.
  4. No sensitive data inside: a JWT is signed, not encrypted; anyone can base64-decode and read it.
  5. A revocation plan: for password changes or account closure, keep a per-user "token version" or a short deny list.
import jwt from 'jsonwebtoken';

const payload = jwt.verify(token, publicKey, { algorithms: ['RS256'], audience: 'api', issuer: 'auth.example.com' });

Realtime connections

Browsers can't send custom headers on a WebSocket connection, so you need a short-lived connection token or a cookie. I cover the details in realtime systems with Node.js and WebSocket.

Passwords

Whichever model you pick: store passwords with a slow, salted algorithm such as bcrypt, scrypt or argon2, rate-limit login attempts, and offer two-factor authentication where you can.

Conclusion

For browser-based apps, server-side sessions with HttpOnly cookies are usually the simplest and safest choice. JWTs shine for service-to-service and mobile scenarios, but without short lifetimes, rotation and proper storage they become a security problem.

GraphQL vs REST: Which One Fits Your Project?

December 2, 2026 · 2 min read

GraphQL vs REST: Which One Fits Your Project?

The strengths and weaknesses of GraphQL and REST: data-fetching flexibility, caching, performance, security, tooling, and recommendations by project type.

APIGraphQLBackendArchitecture

All articles →