Common causes
1. An access token used after its short lifetime
Access tokens commonly live 5 to 60 minutes. Clients must refresh them, either before exp or after a 401, rather than reusing the same token for the whole session. This is the normal case, not a bug in the verifier.
const res = await fetch('/api/orders', { headers: { Authorization: `Bearer ${token}` } });let res = await fetch('/api/orders', { headers: { Authorization: `Bearer ${token}` } });
if (res.status === 401) {
token = await refreshAccessToken();
res = await fetch('/api/orders', { headers: { Authorization: `Bearer ${token}` } });
}2. expiresIn given as a string without a unit
In the Node jsonwebtoken library a number means seconds, but a string without a unit means milliseconds: "3600" produces a token that lasts 3 seconds. Environment variables are always strings, so convert them, or write the unit as in "1h".
jwt.sign(claims, secret, { expiresIn: process.env.TOKEN_TTL });jwt.sign(claims, secret, { expiresIn: Number(process.env.TOKEN_TTL) });3. Clock skew between servers
If the verifier’s clock runs ahead of the issuer’s, fresh tokens look expired. Keep servers in sync with NTP and allow a small tolerance when verifying. Virtual machines and laptops that have been suspended are frequent offenders.
const payload = jwt.verify(token, secret);const payload = jwt.verify(token, secret, { clockTolerance: 30 });4. A token saved in a config file or CI secret
Tokens pasted into scripts, .env files or CI variables work until they expire and then fail with no other change. A job that broke overnight with no deployment is the classic sign. Fetch a token at runtime with a client-credentials flow instead.
API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjcyMjkyMDB9.c2lnbmF0dXJlAPI_CLIENT_ID=reporting-job
API_CLIENT_SECRET_FILE=/run/secrets/reporting-jobRead the timestamps before changing code
RFC 7519 defines exp, iat and nbf as NumericDate values: seconds since 1970 in UTC. Four checks tell you which cause you have:
- Decode the token and note
expandiat. - Work out the lifetime as
exp - iat. A value of 3 points to a units bug; 3600 is a normal hour. - Compare
expwith the clock of the machine that verifies, usingdate -u +%sthere. Your laptop’s clock proves nothing about the server’s. - If the token was issued moments ago and is already rejected, suspect skew or units. If it is minutes or hours old, the client simply needs to refresh.
To decode in Node without verifying, for diagnosis only:
const [, payload] = token.split('.');
const { exp, iat } = JSON.parse(Buffer.from(payload, 'base64url').toString());
console.log(new Date(exp * 1000).toISOString(), 'lifetime', exp - iat, 'seconds');
The most common home-made bug mixes units, because exp is in seconds and Date.now() is in milliseconds:
// Always true: every token looks expired
if (payload.exp < Date.now()) await refresh();
// Correct
if (payload.exp * 1000 < Date.now()) await refresh();
The reverse mistake, signing with exp: Date.now(), creates a token that effectively never expires.
What each library throws, and its tolerance setting
RFC 7519 lets implementers allow “some small leeway, usually no more than a few minutes” for clock skew. Each library exposes that differently:
- jsonwebtoken (Node):
TokenExpiredError, with the time inerr.expiredAt. Tolerance isclockTolerance, in seconds. - jose (Node):
JWTExpired, witherr.codeset toERR_JWT_EXPIRED.clockTolerancetakes seconds or a string such as'30s'. - PyJWT:
ExpiredSignatureError. Tolerance is theleewayargument tojwt.decode. - golang-jwt v5:
errors.Is(err, jwt.ErrTokenExpired). Tolerance is thejwt.WithLeewayparser option. - Microsoft.IdentityModel (.NET): IDX10223 from
SecurityTokenExpiredException. Tolerance isTokenValidationParameters.ClockSkew, which defaults to five minutes. - jjwt (Java):
ExpiredJwtException. Tolerance isclockSkewSecondson the parser builder.
The .NET default surprises people in both directions: a token stays valid five minutes past its exp, so a test that waits for expiry appears to fail. Skew in the opposite direction produces a related error about nbf, such as NotBeforeError: jwt not active in jsonwebtoken.
Refreshing without a stampede
A protected API should answer an expired token with 401 and, per RFC 6750, WWW-Authenticate: Bearer error="invalid_token". A client then has one job: get a new token and retry once. Retrying in a loop hides real authorisation failures.
When a page fires several requests together, they all receive 401 at the same moment. Many identity providers rotate refresh tokens, so a second refresh with the old token can fail or even revoke the session. Share a single in-flight refresh:
let refreshing = null;
function refreshOnce() {
refreshing ??= refreshAccessToken().finally(() => {
refreshing = null;
});
return refreshing;
}
Refreshing shortly before exp avoids most 401s, but keep the retry path too, because the proactive timer does not run while a tab is asleep. See debugging JWT errors for the wider set of verification failures.
Frequently asked questions
How do I see when a token expires?
Decode it: the exp claim holds the expiry as a Unix timestamp. PasteKit converts exp, iat and nbf to readable UTC dates and shows how long ago or how far ahead each one is.
Does "Signature has expired" mean the signature is invalid?
No. That is PyJWT’s wording for an expired token. Signatures do not expire. PyJWT and jsonwebtoken check the signature first, so a wrong key gives an invalid signature error even on an old token, and an expiry error means the signature passed.
Should I just make tokens last longer?
Long-lived access tokens are risky because a leaked token stays usable. Keep access tokens short and use refresh tokens, which can be revoked, to get new ones.
How much clock tolerance is reasonable?
Thirty to sixty seconds is plenty when servers run NTP. If you need several minutes, fix the clocks instead, since every extra second also extends how long an expired token is accepted.
Can I accept an expired token for one specific case?
Libraries offer an option such as ignoreExpiration, but it disables the check entirely. If you only need to read claims from an expired token, decode it without verifying, and never use that for authorisation.