Course contentsShow
← Web Development
Lesson 1574 of 2,98229. Web Authentication PatternsFree lesson

Session Invalidation and Logout

Server-side session destruction vs token revocation challenges in stateless systems.

Session Invalidation and Logout

You'll learn: Why logging users out works differently—and presents different challenges—in session-based versus token-based authentication.

When a user logs out, you need to invalidate their credentials so they can't continue making authenticated requests. How you accomplish this depends fundamentally on whether your authentication is stateful or stateless.

Session-Based Logout: Server-Side Destruction

With cookie-based authentication (stateful), logout is straightforward. The server stores session data (remember from "Session Storage and Management"), so destroying it is simple:

How it works:

  1. Client sends logout request with session cookie
  2. Server finds the session ID in its session store
  3. Server deletes that session record
  4. Cookie is cleared or expired in the response

This works because the server is the "source of truth." Once the session is deleted, that cookie becomes meaningless—even if someone still has a copy of the cookie value, the server won't recognize it.

Token-Based Logout: The Stateless Dilemma

With bearer tokens (stateless), logout becomes tricky. Remember that stateless means the server doesn't store anything about who's logged in—it just validates tokens cryptographically.

The problem: If tokens are self-contained and verifiable without database lookups, how do you "revoke" one that's still valid?

Common approaches:

  • Short expiration times: Make tokens expire quickly (5-15 minutes), so logout just means "stop issuing new tokens"
  • Token blacklist: Add logged-out tokens to a database blocklist (defeats statelessness but works)
  • Refresh token rotation: Revoke the refresh token server-side while letting short-lived access tokens expire naturally

Analogy: A session is like a hotel room key card the hotel can deactivate remotely. A JWT is like a paper ticket—once issued, you have to wait for it to expire or actively track "cancelled tickets" in a list.

Key Takeaway: Session-based auth makes logout trivial through server-side deletion, while token-based auth must balance statelessness with revocation needs—often requiring compromises like short expirations or maintaining revocation lists.