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

Detecting Token Expiration

Learn to decode JWTs and check expiration times to proactively refresh tokens before API requests fail.

Detecting Token Expiration

You'll learn how to proactively check if a JWT has expired before making API requests, preventing unnecessary failures.

When your frontend stores a JWT access token, it contains an exp (expiration) claim as a Unix timestamp. Rather than waiting for the server to reject your request with a 401 error, you can decode the token yourself and check if it's still valid before sending it.

Why Check Expiration Client-Side?

Think of it like checking your milk's expiration date before pouring it into your coffee—you avoid a bad experience by catching the problem early. By detecting expiration proactively, you can trigger a silent refresh flow (from the previous lesson) before attempting the API call, creating a seamless user experience.

How to Decode and Check

Since JWTs are base64-encoded JSON, you can decode the payload section (the middle part between the dots) in the browser. Most JWT libraries provide a decode() function that extracts the payload without verifying the signature (remember, you learned never to verify on the frontend—that's the server's job).

// Decode the JWT payload (no verification)
const payload = JSON.parse(atob(token.split('.')[1]));

// exp is in seconds since epoch
const expirationTime = payload.exp * 1000; // Convert to milliseconds
const currentTime = Date.now();

const isExpired = currentTime >= expirationTime;

Many developers add a buffer (like 60 seconds) before the actual expiration to refresh tokens early:

const bufferTime = 60 * 1000; // 60 seconds
const needsRefresh = currentTime >= (expirationTime - bufferTime);

This way, you refresh tokens before they expire, not after.

Key Takeaway: Decode your JWT's exp claim and compare it to the current time to detect expiration proactively, allowing you to refresh tokens before API requests fail.