Node

Fix JWT Errors: jwt malformed, jwt expired, invalid signature and invalid token

Fix JWT Errors: jwt malformed, jwt expired, invalid signature and invalid token
On this page
  1. Every jsonwebtoken error and what it means
  2. jwt malformed
  3. jwt must be provided
  4. invalid token: the Bearer prefix
  5. invalid signature
  6. jwt expired
  7. A complete, safe middleware
  8. Debugging a token safely
  9. Changing the secret without logging everyone out
  10. Refreshing an expired token on the client
  11. Frequently asked questions about JWT errors
  12. Oh hi there 👋It’s nice to meet you.
  13. Sign up to receive awesome content in your inbox.

Your Express API rejects a request with JsonWebTokenError: jwt malformed, or invalid signature, or jwt expired. These messages come from the jsonwebtoken package, and each one points to a different mistake, so the fix depends on reading the message exactly. This guide lists every common JWT error with its real cause, reproduced with jsonwebtoken 9 on Node.js 22. Some of the results contradict advice you will find elsewhere.

Every jsonwebtoken error and what it means

Here is what jwt.verify() returned for each kind of bad input in testing:

What was passed to verify Error
null or an empty string JsonWebTokenError: jwt must be provided
The text "undefined" JsonWebTokenError: jwt malformed
"Bearer eyJ…" with the prefix still attached JsonWebTokenError: invalid token
A token signed with a different secret JsonWebTokenError: invalid signature
A token whose payload was edited JsonWebTokenError: invalid signature
A token past its exp time TokenExpiredError: jwt expired
A token with a future nbf time NotBeforeError: jwt not active
A token whose algorithm isn’t in the allowed list JsonWebTokenError: invalid algorithm
The checks jwt.verify runs, and the error each one raisesjwt.verify checks that a token was provided, that it has three parts, that the signature matches the secret, and that it has not expired.Provided?jwt must be providednull or emptyThree parts?jwt malformed"undefined"Signature?invalid signaturewrong secretExpired?jwt expiredpast exp
jwt.verify runs its checks in order; the first one that fails decides the error you see.

jwt malformed

A JSON Web Token has three parts separated by dots: header.payload.signature. “Malformed” means the value doesn’t have that shape at all. In testing, the string "undefined" produced it, and that is the most common real cause: the frontend sends a token that doesn’t exist yet.

// localStorage has no token, so this sends "Bearer undefined" or "Bearer null"
fetch('/api/orders', { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } });

Other causes are reading the wrong header or cookie name, or splitting the header incorrectly so only part of the token remains. Log what the server actually received, then fix the client so it only sends the header when a token exists:

const token = localStorage.getItem('token');
const headers = token ? { Authorization: `Bearer ${token}` } : {};

jwt must be provided

The value passed to jwt.verify() was empty: null, undefined or an empty string. Either the request had no Authorization header, or your code read it from the wrong place. Check for a missing token before verifying, so the client gets a clear 401 rather than an exception:

const header = req.headers.authorization ?? '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ error: 'No token provided' });

invalid token: the Bearer prefix

Many articles say that forgetting to remove Bearer causes “jwt malformed”. With the current package, testing showed otherwise: passing "Bearer eyJ…" to verify gives invalid token. The value has the right number of dots, so it passes the shape check, but its first part isn’t valid once decoded. The fix is the header parsing shown above: verify only the part after Bearer .

invalid signature

The token is well-formed, but its signature doesn’t match the one computed with your secret. In testing, two different situations produced this same error:

  • A different secret verified the token than signed it.
  • The payload was changed after signing, for example editing the user id, which is exactly the attack signatures exist to stop.

In real projects, the first is nearly always the cause:

  • JWT_SECRET differs between environments, or between two services that share tokens.
  • The secret changed, so tokens issued before the change no longer verify. Users must log in again.
  • process.env.JWT_SECRET is undefined where you verify, because .env wasn’t loaded. Signing with an undefined secret fails with secretOrPrivateKey must have a value, so check both places.
  • Extra whitespace or quotes around the secret in the environment file.

Compare the secrets without printing them: log their lengths, or a short hash, in both places.

jwt expired

The current time is past the token’s exp claim. This isn’t a bug; it is the token doing its job. The error is a TokenExpiredError, and in testing it carried an expiredAt date you can use in logs. Handle it separately so the client knows to refresh rather than treating the user as an attacker:

try {
  req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
  next();
} catch (err) {
  if (err.name === 'TokenExpiredError') {
    return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
  }
  return res.status(401).json({ error: 'Invalid token' });
}

On the client, a TOKEN_EXPIRED response should trigger one call to your refresh endpoint and a retry of the original request. If tokens expire sooner than expected, check the expiresIn value: a number means seconds, so expiresIn: 15 is fifteen seconds, while '15m' is fifteen minutes. Also check that the server’s clock is correct; a small difference between servers can be absorbed with the clockTolerance option.

A complete, safe middleware

import jwt from 'jsonwebtoken';

export function requireAuth(req, res, next) {
  const header = req.headers.authorization ?? '';
  const token = header.startsWith('Bearer ') ? header.slice(7).trim() : null;
  if (!token) return res.status(401).json({ error: 'No token provided' });

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
    next();
  } catch (err) {
    const expired = err.name === 'TokenExpiredError';
    res.status(401).json({ error: expired ? 'Token expired' : 'Invalid token', code: expired ? 'TOKEN_EXPIRED' : 'TOKEN_INVALID' });
  }
}

Three details matter. Passing algorithms restricts which signing methods are accepted; in testing, a token signed with a method outside the list was rejected with “invalid algorithm”. Every failure returns 401, never 500, because a bad token is the client’s problem, not a server crash. And the response doesn’t reveal why an invalid token failed, which would only help an attacker.

Debugging a token safely

To see what a token contains without verifying it, decode it:

console.log(jwt.decode(token));   // { sub: 'u1', iat: 1794523745, exp: 1794524645 }

jwt.decode() only reads the payload; it performs no security check, so never use it to decide whether a request is allowed. It is useful for checking the expiry time and the claims while debugging. Remember that anyone can decode a JWT’s payload, so never put passwords or other secrets in it.

The full login flow, including refresh tokens and where to store tokens in the browser, is in JWT authentication in Node.js and Express. If you would rather use server-side sessions, see Passport.js authentication in Express.

Changing the secret without logging everyone out

Changing JWT_SECRET instantly invalidates every token, so all users get “invalid signature” and must log in again. To rotate a secret smoothly, accept both the new and the old secret for a while, and sign new tokens only with the new one:

const SECRETS = [process.env.JWT_SECRET, process.env.JWT_SECRET_PREVIOUS].filter(Boolean);   // newest first

function verifyWithRotation(token) {
  let lastError;
  for (const secret of SECRETS) {
    try {
      return jwt.verify(token, secret, { algorithms: ['HS256'] });
    } catch (err) {
      if (err.name === 'TokenExpiredError') throw err;   // expired is final: don't try other secrets
      lastError = err;
    }
  }
  throw lastError;
}

In testing, tokens signed with either secret verified, a token signed with an unknown secret still failed with “invalid signature”, and an expired token was reported as expired. Once the longest-lived token signed with the old secret has expired, remove JWT_SECRET_PREVIOUS. If a secret has leaked, skip the grace period: replace it immediately and accept that users must log in again.

Refreshing an expired token on the client

Handle expiry in one place, so components never deal with it:

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

  let res = await call();
  if (res.status === 401 && (await res.clone().json()).code === 'TOKEN_EXPIRED') {
    const refreshed = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' });
    if (!refreshed.ok) { redirectToLogin(); throw new Error('Session ended'); }
    setAccessToken((await refreshed.json()).accessToken);
    res = await call();                      // retry once with the new token
  }
  return res;
}

Retry only once, or a failing refresh would loop forever. Keeping the refresh token in an HttpOnly cookie, as here, means JavaScript can’t read it, which limits the damage of a cross-site scripting bug.

Frequently asked questions about JWT errors

What does “jwt malformed” mean?

The value isn’t shaped like a token: three parts separated by dots. Most often the server received the text “undefined” or “null” because the client sent a token it didn’t have.

Why do I get “invalid signature” when the token looks correct?

The secret used to verify differs from the one that signed the token. Check that JWT_SECRET is defined and identical wherever tokens are signed and verified.

How do I handle “jwt expired” in React?

Return a specific code such as TOKEN_EXPIRED from the API. On the client, call your refresh endpoint once, store the new token and retry the original request. If the refresh fails, send the user to the login page.

Is jwt.decode safe to use for authentication?

No. It reads the payload without checking the signature, so anyone could forge it. Always use jwt.verify() to authenticate requests.

Should a failed token return 401 or 403?

401: the request isn’t authenticated. Use 403 when the token is valid but the user isn’t allowed to do that action.

logo

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Saurabh

Saurabh Pathak is an AI engineer and MERN stack developer, and the founder of mernstackdev.com. He builds open-source projects such as the Haat gateway and MCP safety tooling, and he writes hands-on tutorials on React, Node.js, MongoDB and AI agents. He cares most about code that works in production.