Sessions, Cookies and JWTs

Keep users logged in with server-side sessions or signed tokens, store them in secure cookies, and understand the trade-offs.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Authentication Fundamentals and Password Storage

After login, the server needs to recognise the user on every request. There are two main approaches.

Server-side sessions

The server stores a session record (in PostgreSQL or Redis) and gives the browser a random session id in a cookie. Logging out or banning a user is instant: delete the record. This is the simplest secure default for web apps.

JWTs

A JSON Web Token is a signed blob containing claims like the user id and expiry. The server can verify it without a database lookup. The catch: you cannot easily revoke a JWT before it expires. Common patterns use a short-lived access token (around 15 minutes) plus a refresh token that is stored and can be revoked.

Cookies done right

  • HttpOnly so JavaScript cannot read the token (limits damage from XSS).
  • Secure so it is only sent over HTTPS.
  • SameSite=Lax (or Strict) to reduce CSRF risk.
  • A sensible expiry and rotation on login.

Choosing

For a browser-based app on one domain, cookie sessions are usually simpler and safer. JWTs suit mobile apps and service-to-service calls.

Pitfalls

  • Storing JWTs in localStorage, where any XSS can steal them.
  • Putting sensitive data in a JWT payload; it is only encoded, not encrypted.
  • Long-lived JWTs with no way to revoke them.

You are ready to move on when you can implement cookie-based sessions with logout and "log out of all devices", and explain when you would choose JWTs instead.

Key concepts

  • Server-side sessions
  • Cookie flags: HttpOnly, Secure, SameSite
  • JWT structure and signing
  • Access and refresh tokens
  • Revocation and logout everywhere
  • Session rotation
  • Where not to store tokens

Mini project

Add database-backed sessions to your API with secure cookies, a sessions table showing active devices, logout, and a 'log out of all devices' button.

Check yourself

A student's account is compromised and you ban it. How quickly does the ban take effect with server sessions vs 24-hour JWTs?

Free resources