What is the difference between JWT and session-based authentication?
- Technology:
- Node.js
Quick answer
Session authentication stores the login state on the server and gives the browser a session ID cookie, while JWT authentication gives the client a signed token that contains the user's claims so the server can verify it without storing state.
Detailed explanation
Sessions are simple and easy to revoke: delete the server-side record and the user is logged out immediately, but you need shared storage such as Redis once you run several servers. A JWT is self-contained and works well across services, but you cannot invalidate a single token before it expires unless you keep a deny list or use short lifetimes with refresh tokens.
Whichever you pick, store tokens in HttpOnly, Secure, SameSite cookies rather than localStorage to limit XSS risk, hash passwords with bcrypt or Argon2, use short access-token lifetimes, and verify the signature algorithm explicitly. Authentication confirms who you are; authorisation decides what you may do.
How to explain it in an interview
With sessions, the server stores the session and the browser holds only a random id in a cookie, so logging out or revoking access is easy. A JWT is a signed token that carries the claims itself, so any service can verify it without a lookup, but it cannot be revoked before it expires without extra infrastructure. For a typical web app I prefer sessions in HttpOnly cookies; for service-to-service or mobile APIs, short-lived JWTs with refresh tokens.
Key points
- Session: state on the server, easy to revoke
- JWT: stateless, hard to revoke before expiry
- Use HttpOnly Secure cookies and short token lifetimes
Common mistakes
- Storing JWTs in localStorage, where any XSS bug can read them. HttpOnly cookies are safer.
- Issuing long-lived JWTs with no way to revoke them.
- Assuming a JWT is encrypted. A standard JWT is only signed; anyone can read the payload.