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

JWT Expiration and the exp Claim

Setting appropriate token lifetimes and handling expired tokens in the frontend.

JWT Expiration and the exp Claim

You'll learn how to control JWT token lifetimes using the exp claim and handle expired tokens gracefully in your applications.

Why Tokens Need Expiration

JWTs are stateless—once issued, the server can't "revoke" them like a session cookie. Setting an expiration date prevents stolen or leaked tokens from being useful forever. Think of it like a parking pass that's only valid until 6pm: even if someone finds it later, it won't work.

The exp Claim

The exp (expiration time) claim is a standard JWT claim that contains a timestamp (in seconds since Unix epoch: January 1, 1970). When the current time passes this timestamp, the token should be rejected:

// Example JWT payload
{
  "sub": "user123",
  "name": "Alice",
  "iat": 1699564800,  // issued at: Nov 10, 2023
  "exp": 1699568400   // expires: Nov 10, 2023, one hour later
}

Setting Appropriate Lifetimes

  • Short-lived access tokens (15 min – 1 hour): reduces risk if compromised
  • Long-lived refresh tokens (days/weeks): used to obtain new access tokens
  • Context matters: banking apps need shorter windows than a blog comment system

Handling Expired Tokens in the Frontend

When your API returns a 401 Unauthorized due to an expired token:

if (response.status === 401) {
  // Clear the invalid token
  localStorage.removeItem('token');
  // Redirect to login or attempt refresh
  window.location.href = '/login';
}

Better yet, check expiration before making requests by decoding the token and comparing exp to the current time.

Key Takeaway: The exp claim limits token validity to a specific window, requiring you to set appropriate lifetimes based on security needs and handle expired tokens by clearing storage and re-authenticating users.