Fixing “jwt expired”.

The token is genuine but past its expiry time. Here’s how each library reports it, the usual causes, and the fix for each.

By the NestedBit team · Updated

What the error means

“jwt expired” (TokenExpiredError in jsonwebtoken, ExpiredSignatureError in PyJWT) means the token’s exp time is earlier than the verifying server’s clock: the token was valid, but its lifetime has ended.

Every JWT verifier compares the token’s exp claim, a time in seconds since 1 January 1970, with its own clock (RFC 7519, section 4.1.4). Once that time has passed, it rejects the token. jsonwebtoken, jose and PyJWT check the signature before the times, so in those libraries this error means the token is genuine, just old.

To see exactly when a token expired, paste it into the free JWT decoder. It shows exp and iat in your own time zone, and flags the timing mistakes below. It runs in your browser, so the token isn’t sent anywhere.

Quick fix

  1. When the API answers 401, use the refresh token to get a new access token, then retry the request once.
  2. If tokens expire as soon as they’re issued, check that exp is in seconds, not milliseconds.
  3. If it fails only on some machines, sync their clocks with NTP and allow no more than a minute of leeway.

How each library reports it

Node.js, jsonwebtoken
TokenExpiredError: jwt expired
Node.js, jose
JWTExpired: "exp" claim timestamp check failed
Python, PyJWT
ExpiredSignatureError: Signature has expired
Java, jjwt
ExpiredJwtException: JWT expired at …
Spring Security
Jwt expired at …
.NET
IDX10223: Lifetime validation failed. The token is expired.
Go, golang-jwt
token has invalid claims: token is expired

Cause 1: the token really is old

Access tokens are meant to expire, often within an hour or so, so that a stolen one stops working soon. Microsoft Entra ID, for example, gives them 60 to 90 minutes by default. An expired token is the design working. The fix belongs in the client: when the API answers 401, use the refresh token to get a new access token, then retry the request once.

// Refresh once and retry when the API says the token has expired.
async function apiFetch(url, init = {}) {
  const send = () =>
    fetch(url, {
      ...init,
      headers: { ...init.headers, Authorization: `Bearer ${getAccessToken()}` },
    });

  let res = await send();
  if (res.status === 401) {
    await refreshTokens(); // trade the refresh token for a new access token
    res = await send();
  }
  return res;
}

Many apps also refresh shortly before expiry, using the exp in the token they already hold:

// Read exp from the token you hold, to refresh a minute early.
const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
const expiresSoon = payload.exp * 1000 - Date.now() < 60_000;

Reading a token without verifying it is fine for timing a refresh. Never use an unverified token to decide what a user is allowed to do.

Cause 2: the lifetime is in the wrong unit

If tokens expire seconds after they’re issued, check the unit first. In Node’s jsonwebtoken, a number for expiresIn means seconds, but a string without a unit means milliseconds. A value read from an environment variable is always a string:

// .env: JWT_EXPIRES_IN=3600
jwt.sign(claims, key, { expiresIn: process.env.JWT_EXPIRES_IN });         // "3600" = 3.6 seconds
jwt.sign(claims, key, { expiresIn: Number(process.env.JWT_EXPIRES_IN) }); // 3600 seconds
jwt.sign(claims, key, { expiresIn: '1h' });                               // 1 hour

If you write exp yourself, it must be seconds: Math.floor(Date.now() / 1000) + 3600. The opposite mistake shows up in hand-written checks, where comparing exp with JavaScript’s millisecond clock makes every token look expired:

if (payload.exp < Date.now()) { ... }            // wrong: always true
if (payload.exp * 1000 < Date.now()) { ... }     // right

Cause 3: the clocks disagree

If tokens fail on one server but not another, or expire early only in some environments, the machine that issues tokens and the one that verifies them disagree about the time. A laptop that slept with Docker or a virtual machine running often wakes up minutes behind, and containers take their clock from that host.

Fix the clocks first: run NTP (chrony or systemd-timesyncd) everywhere, and restart the Docker or VM host after sleep. Then allow a small leeway for the drift that remains, no more than a minute:

jsonwebtoken
jwt.verify(token, key, { clockTolerance: 30 })
jose
jwtVerify(token, key, { clockTolerance: '30s' })
PyJWT
jwt.decode(token, key, algorithms=["RS256"], leeway=30)
.NET
ClockSkew = TimeSpan.FromSeconds(30) (the default is five minutes)
golang-jwt
jwt.WithLeeway(30 * time.Second)
jjwt
Jwts.parser().clockSkewSeconds(30)

Cause 4: a stored token is reused

A token kept in local storage, a mobile keychain or a server-side cache keeps being sent after it expires: when an app resumes from the background, when a tab is left open overnight, or when a backend caches a machine-to-machine token. Check exp before using a stored token and refresh it if it’s close, as in the snippet above, and refresh when the app comes back to the foreground.

Cause 5: the provider’s lifetime is shorter than you assumed

Identity providers set their own lifetimes. Firebase ID tokens, for example, last one hour. Rather than storing one, call getIdToken() before each request: it returns the current token, or refreshes it when it’s about to expire. Most provider SDKs have an equivalent; use it instead of caching tokens yourself.

When a hosted service shows it

Supabase
In the Supabase Dashboard, “JWT expired” usually means your computer’s clock is wrong, according to Supabase’s troubleshooting guide. Sync the clock and reload.
Okta
okta-auth-js reports AuthSdkError: The JWT expired and is no longer valid, or The JWT was issued in the future when the device’s clock runs ahead. Both usually mean the device’s clock is off. The SDK’s maxClockSkew already allows 300 seconds, so fix the clock rather than raising it.
Keycloak
Keycloak reports an expired token, and one whose nbf hasn’t arrived, as Token is not active. The lifetime comes from the realm’s Access Token Lifespan, which a client can override; see Keycloak’s timeout settings.
Auth0
Access tokens for your own API last 86,400 seconds (24 hours) unless the API’s settings say otherwise. If they expire sooner than you expect, check the API’s access token lifetime first, then the causes above.

What not to do

  • Don’t switch the check off. ignoreExpiration: true in jsonwebtoken or options={"verify_exp": False} in PyJWT makes a stolen token work forever.
  • Don’t stretch access tokens to days to avoid writing refresh logic. Keep them short and rotate refresh tokens.
  • Don’t raise the leeway to minutes to hide clock drift. Fix the clock.

Expired, or something else?

“Invalid signature” means the wrong key, or a token that was changed after signing. “jwt not active” means the token’s nbf time hasn’t arrived, which is usually the same clock drift in the other direction. And if the error names the audience, read Fixing “jwt audience invalid”.

Free tool · No sign-up

JWT Decoder and Security Inspector

A JWT decoder that runs in your browser and shows what's wrong with a token's claims and signing.

Starts with a free 30-minute intro call, or email hello@nestedbit.com.