Skip to main content
DevTool House
Back to Blogs
Developer Guides

JWT Expired? How to Debug 401 Unauthorized Errors Step by Step

Decode the token, read the exact jsonwebtoken error, and fix expired tokens, invalid signatures, clock skew and audience mismatches.

By Wali UllahDecember 2, 20269 min read
A token split into three coloured parts with a red 401 badge and an hourglass, for an expired JWT

A 401 Unauthorized from an API that uses JWTs nearly always comes from one of six causes: the token has expired, it is not being sent the way the server expects, its signature does not match, its audience or issuer is wrong, it is not valid yet, or the server rejects its algorithm. You can tell which in about two minutes by decoding the token and reading the server's exact error message. This is the step-by-step routine I follow, with the real error messages from the jsonwebtoken library that most Node.js APIs use.

Step 1: Decode the token and read its claims

A JWT is three Base64url parts separated by dots: header.payload.signature. The header and payload are plain JSON that anyone can read; only the signature needs the secret. Paste the token into the JWT Decoder. It decodes in your browser, so the token is not sent anywhere. Then check these claims:

Claim Meaning What to check
exp Expiry time (Unix seconds) Is it in the past?
iat Issued at (Unix seconds) How long ago was the token created?
nbf Not before (Unix seconds) Is it in the future?
aud Audience Does it match what the API expects?
iss Issuer Does it match your auth server's URL?
alg (header) Signing algorithm Does the server accept it?

exp, iat and nbf are Unix timestamps in seconds. In JavaScript, new Date(payload.exp * 1000) gives you the date, or paste the number into the Timestamp Converter.

You can also decode the payload in a browser console or in Node without any library:

function decodeJwtPayload(token) {
  const payload = token.split('.')[1];
  const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
  return JSON.parse(atob(base64));
}

const claims = decodeJwtPayload(token);
console.log(new Date(claims.exp * 1000).toISOString(), claims.exp * 1000 < Date.now() ? 'EXPIRED' : 'valid');

Decoding is not verification. It tells you what the token claims, not whether it was signed by your server. Never make authorization decisions from a decoded token on the client.

Step 2: Read the exact error on the server

The client usually only sees 401. The server knows why. In a Node.js API using the jsonwebtoken package, log the error's name and message (not the token itself):

import jwt from 'jsonwebtoken';

try {
  req.user = jwt.verify(token, process.env.JWT_SECRET, {
    algorithms: ['HS256'],
    audience: 'api',
    issuer: 'https://auth.example.com',
  });
} catch (err) {
  console.warn('JWT rejected:', err.name, err.message);
  return res.status(401).json({ message: 'Invalid or expired token' });
}

These are the messages jsonwebtoken (version 9) actually produces, and what each one means:

err.name err.message Cause
TokenExpiredError jwt expired exp is in the past. The error also has an expiredAt date.
JsonWebTokenError invalid signature Signed with a different secret or key than the server is verifying with
JsonWebTokenError jwt malformed Not a JWT at all: truncated, extra quotes, or Bearer included in the token string
JsonWebTokenError jwt must be provided The token string was empty: the header was missing or parsed wrongly
NotBeforeError jwt not active nbf is in the future, often clock skew between servers
JsonWebTokenError jwt audience invalid. expected: api aud does not match the audience option
JsonWebTokenError jwt issuer invalid. expected: … iss does not match the issuer option
JsonWebTokenError invalid algorithm The token's alg is not in your algorithms list

With the message in hand, jump to the matching fix below.

Fix: "jwt expired"

An expired token is not a bug. It is the token doing its job. Short-lived access tokens (often 15 minutes to an hour) limit the damage if one leaks. What needs fixing is how the client handles expiry:

  1. Refresh before or after expiry. Issue a long-lived refresh token alongside the short access token. When the API returns 401 with an expired access token, call your refresh endpoint once, store the new access token, and retry the original request.
  2. Do not refresh in a loop. If the refresh call also returns 401, the refresh token has expired or been revoked: send the user to log in again instead of retrying forever.
  3. Handle many requests at once. If ten requests fail at the same moment, refresh once and let the other nine wait for the same new token, instead of firing ten refresh calls.

Here is the core of that pattern for fetch:

let refreshing = null;

async function apiFetch(url, options = {}) {
  const withToken = () =>
    fetch(url, { ...options, headers: { ...options.headers, Authorization: `Bearer ${getAccessToken()}` } });

  let res = await withToken();
  if (res.status !== 401) return res;

  refreshing ??= refreshAccessToken().finally(() => { refreshing = null; });
  const ok = await refreshing;
  if (!ok) { redirectToLogin(); return res; }

  return withToken(); // retry once with the new token
}

refreshAccessToken() calls your refresh endpoint and returns true when it stored a new token. If tokens "expire immediately", compare exp with iat in the decoder. A classic cause in jsonwebtoken is the unit of expiresIn: the number 15 means 15 seconds and the string '15m' means 15 minutes, but the string '15', with no unit, means 15 milliseconds, so the token is expired before it reaches the client. Always write the unit: '15m', '1h', '7d'.

Fix: "invalid signature"

The token was signed with a different key than the one the server verifies with. In practice:

  • Different secrets per environment. A token from staging sent to production, or a .env that was never updated on the server.
  • Trailing whitespace or quotes in the secret. JWT_SECRET="abc " and JWT_SECRET=abc are different secrets. Log the secret's length (never the value) on both sides to compare.
  • Asymmetric keys mixed up. With RS256 or ES256, the auth server signs with the private key and the API verifies with the matching public key. Verifying with the wrong public key, or with the private key's text pasted as an HMAC secret, gives this error.
  • Rotated keys. If your provider rotates signing keys, fetch the current key set (JWKS) and select the key by the token's kid header instead of hard-coding one key.

Fix: "jwt malformed" or "jwt must be provided"

Both mean the server did not receive a clean token string:

  • The header must be exactly Authorization: Bearer <token>, with one space after Bearer. Split it correctly on the server (header.split(' ')[1]), and do not pass Bearer eyJ… into jwt.verify().
  • Tokens copied from logs or chat apps often pick up quotes, a newline or a trailing space. A JWT never contains whitespace.
  • Behind some proxies and serverless platforms, the Authorization header is stripped or renamed. Log req.headers once on the server to confirm it arrives.
  • In the browser, check that the token you stored is not the string "undefined" from a failed login.

Fix: "jwt not active" and clock skew

nbf and iat assume both servers agree on the time. If the auth server's clock is a few seconds ahead of the API server's, brand-new tokens are briefly "not active", and recently expired ones get rejected a moment early. Keep servers synchronized with NTP, and allow a small tolerance when verifying:

jwt.verify(token, secret, { clockTolerance: 30 }); // accept up to 30 seconds of skew

Keep the tolerance small. It exists to absorb clock drift, not to extend token lifetimes.

Fix: audience, issuer and algorithm errors

  • Audience: tokens for one API often get reused on another. If the aud claim says web and the API expects api, the token was issued for a different service. Request a token for the correct audience instead of removing the check.
  • Issuer: the iss value is compared exactly, including the trailing slash: https://auth.example.com and https://auth.example.com/ are different issuers.
  • Algorithm: always pass an explicit algorithms list to jwt.verify(). It stops a token from choosing its own algorithm, which is the root of several well-known JWT attacks.

401 or 403?

Return 401 Unauthorized when the request has no valid credentials: missing, expired, malformed or badly signed. Return 403 Forbidden when the token is valid but the user lacks permission, such as a normal user calling an admin endpoint. Keeping them separate tells the client what to do: refresh or log in after a 401, and show "you don't have access" after a 403.

A quick checklist

  1. Decode the token: is exp in the past? Is nbf in the future?
  2. Read the server's err.name and err.message.
  3. Confirm the request sends Authorization: Bearer <token>, with no quotes or whitespace in the token.
  4. Compare secrets or keys between the issuing and verifying environments.
  5. Check that aud, iss and alg match the server's verify options.
  6. Make sure the client refreshes once and stops when the refresh fails.

FAQ

What does "jwt expired" mean?

The token's exp claim is in the past, so the server rejects it. The token was valid when it was issued. Get a new one through your refresh flow, or log in again.

How do I check whether a JWT is expired?

Decode the payload, read the exp claim, and compare it with the current time: exp * 1000 < Date.now() in JavaScript. The JWT Decoder shows the expiry date and whether the token has expired.

Can I decode a JWT without the secret?

Yes. The header and payload are only Base64url-encoded, not encrypted, so anyone can read them. The secret is needed only to verify the signature. That is also why a JWT payload must never contain passwords or other secrets.

Why do I get 401 Unauthorized with a valid token?

Usually the token is not reaching the server intact (wrong header format, quotes, a stripped Authorization header), or it was issued for a different audience or environment. Log the server's exact verification error to see which.

How long should a JWT access token last?

Short: commonly 15 minutes to an hour, paired with a longer-lived refresh token. Short access tokens limit the damage if one leaks, and the refresh flow keeps users signed in.

Try the related tools

Related articles