jsonwebtoken rejects a token: invalid signature, jwt expired or jwt malformed
JsonWebTokenError: jwt malformedShort answer
Each message points at a different step. jwt malformed means the string is not three dot-separated parts, usually because of a Bearer prefix or an undefined value. invalid signature means a different key or algorithm signed it. jwt expired means the exp time has passed, often a refresh gap or a clock that is off. Decode the token, without trusting it, to see which.
Fix it fast
1Find out which cause you have
Look inside the token without verifying it. jwt.decode only reads; it proves nothing, so use it for diagnosis and never for access decisions. The header shows the algorithm, the payload shows exp, iat, iss and aud, and the error class tells you which step failed.
node -e " const jwt = require('jsonwebtoken'); const t = process.argv[1]; console.log(JSON.stringify(jwt.decode(t, { complete: true }), null, 2)); console.log('now:', Math.floor(Date.now() / 1000)); " 'PASTE.TOKEN.HERE'2Match what you see, then jump to its fix
- 1
jwt malformed, and the value you log has no dots, starts with a Bearer prefix, or is the text undefined.The string is not a JWT at all: prefix, quotes or an undefined valueFix - 2
invalid signature, the header and payload decode fine, and the token came from another service, an older deploy or another environment.Signed with one key, verified with anotherFix - 3
invalid signature after you changed from a shared secret to RSA or ECDSA keys, or the decoded header shows an alg you did not expect.The algorithm or key type does not matchFix - 4
jwt expired with an expiredAt value, or jwt not active (the nbf time is still in the future), mostly right after login on a server whose clock is off.The token really expired, or the clocks disagreeFix - 5
jwt audience invalid. expected: ..., jwt issuer invalid. expected: ... or jwt subject invalid, named in the message.The token is valid but for another audience or issuerFix
- 1
What does the error look like?
JsonWebTokenError: jwt malformedJsonWebTokenError: invalid signatureTokenExpiredError: jwt expiredNotBeforeError: jwt not activeJsonWebTokenError: jwt audience invalid. expected: api.example.com
Cause 1 of 5
The string is not a JWT at all: prefix, quotes or an undefined value
1Check
A JWT has three parts separated by two dots. Code that reads the Authorization header must remove the scheme word before verifying, and a missing header can turn into the text undefined or null. Log the length and the number of dots, not the token itself.
// inside the handler
const raw = req.headers.authorization ?? ''
console.log({ prefix: raw.slice(0, 7), dots: (raw.match(/\./g) || []).length })2Fix
Parse the header strictly: expect the word Bearer, a space, then the token; reject the request with 401 when it does not fit. Read the token from the one place your client actually sends it.
function readBearer(req) {
const [scheme, token] = (req.headers.authorization ?? '').split(' ')
return scheme === 'Bearer' && token ? token : null
}
const token = readBearer(req)
if (!token) return res.status(401).json({ error: 'missing token' })3Verify
A valid request gets past the parser, and a request with no header gets 401 instead of a malformed error.
curl -s -o /dev/null -w "%{http_code}\n" https://api.example.com/me
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $TOKEN" https://api.example.com/meConfirmed by github.com
Cause 2 of 5
Signed with one key, verified with another
1Check
Services that sign and verify must hold the identical secret (HMAC) or the matching key pair (RSA, ECDSA). A staging secret in production, a secret rotated on one side only, or a stray space or newline in the environment variable all give this error. Compare a hash of the value on both sides; do not print the secret.
node -e "console.log(require('crypto').createHash('sha256').update(process.env.JWT_SECRET ?? '').digest('hex').slice(0, 12), (process.env.JWT_SECRET ?? '').length)"2Fix
Keep one source of truth for the key (a secret manager or a single env file per environment) and trim the value on load. When rotating, accept both keys for a short period instead of changing one side. Tokens signed with the old key stay invalid until users sign in again.
const secret = (process.env.JWT_SECRET ?? '').trim()
if (secret.length < 32) throw new Error('JWT_SECRET missing or too short')
const payload = jwt.verify(token, secret, { algorithms: ['HS256'] })3Verify
A token created by the signing service passes verify in the verifying service.
node -e "
const jwt = require('jsonwebtoken');
const s = process.env.JWT_SECRET.trim();
console.log(jwt.verify(jwt.sign({ sub: 'test' }, s, { algorithm: 'HS256', expiresIn: 60 }), s, { algorithms: ['HS256'] }));
"Confirmed by github.com
Cause 3 of 5
The algorithm or key type does not match
1Check
A token's header names its algorithm. With a secret, the library allows only the HMAC family by default, and with an RSA public key only the RSA family. The verifier must be given the kind of key that goes with the algorithm that signed the token: a secret for HS256, the public key for RS256.
node -e "console.log(require('jsonwebtoken').decode(process.argv[1], { complete: true }).header)" 'PASTE.TOKEN.HERE'2Fix
Pin the allowed algorithms to exactly what you issue, so the header can never choose for you. Sign with the private key and verify with the public key for asymmetric algorithms.
// issuer
const token = jwt.sign({ sub: userId }, privateKeyPem, { algorithm: 'RS256', expiresIn: '15m' })
// verifier
const payload = jwt.verify(token, publicKeyPem, { algorithms: ['RS256'] })3Verify
A token signed with the private key verifies with the public key, and a token signed with a different algorithm is rejected.
node -e "
const jwt = require('jsonwebtoken');
console.log(jwt.decode(process.argv[1], { complete: true }).header.alg);
" 'PASTE.TOKEN.HERE'Confirmed by github.com
Cause 4 of 5
The token really expired, or the clocks disagree
1Check
Compare exp, iat and nbf with the verifying server's current time. expiresIn given as a number is in seconds; a string such as 15m or 7d is also accepted. If the issuer and the verifier run on different hosts, a clock that is minutes apart can make a new token look expired or not yet valid.
date -u +%s
timedatectl status | grep -E "System clock synchronized|NTP service"
node -e "const p=require('jsonwebtoken').decode(process.argv[1]); console.log(p.iat, p.exp, p.nbf)" 'PASTE.TOKEN.HERE'2Fix
Keep every server's clock on NTP. Add a short refresh-token flow so users do not meet the expiry in the middle of work, and allow a small clockTolerance (a few seconds) rather than a long lifetime or a long tolerance.
sudo timedatectl set-ntp true
const payload = jwt.verify(token, secret, { algorithms: ['HS256'], clockTolerance: 5 })3Verify
timedatectl reports the clock as synchronized, and a fresh token is accepted immediately.
timedatectl status | grep -E 'System clock synchronized'Confirmed by github.com
Cause 5 of 5
The token is valid but for another audience or issuer
1Check
If verify is given audience, issuer or subject options, the token's aud, iss and sub claims must match them. Tokens from another API, from the identity provider's other app, or from a different environment fail here even with the correct signature.
node -e "const p=require('jsonwebtoken').decode(process.argv[1]); console.log({ iss: p.iss, aud: p.aud, sub: p.sub })" 'PASTE.TOKEN.HERE'2Fix
Set the same issuer and audience when you issue and when you verify, and keep them in configuration per environment.
jwt.sign({ sub: userId }, secret, { algorithm: 'HS256', expiresIn: '15m', issuer: 'https://auth.example.com', audience: 'api.example.com' })
jwt.verify(token, secret, { algorithms: ['HS256'], issuer: 'https://auth.example.com', audience: 'api.example.com' })3Verify
A token issued with those values passes verify, and one with another audience is rejected with the audience message.
node -e "console.log(require('jsonwebtoken').decode(process.argv[1]).aud)" 'PASTE.TOKEN.HERE'Confirmed by github.com
How do I stop it coming back?
- Always pass the algorithms option to verify so the token's own header cannot pick the algorithm.
- Use a random HMAC secret at least as long as the hash output (32 bytes for HS256), generated for each environment and stored outside the code.
- Keep access tokens short-lived and refresh them, instead of stretching one token's life.
- Never use decode for decisions; it does not check anything.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Security
Entra ID token request fails: the request body must contain the parameter 'grant_type'
AADSTS900144: The request body must contain the following parameter: 'grant_type'.
The token endpoint did not find grant_type in the form body of your POST.
3 causes, each with a fixSecurity
The browser blocks a script because of your Content Security Policy
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
The page's Content-Security-Policy does not allow what it tried to run or load.
5 causes, each with a fixSecurity
A valid JWT fails to decode because its segments are base64url, not base64
Convert.FromBase64String throws FormatException on a JWT segment
A JWT is three base64url segments joined by dots, and a standard base64 decoder refuses all three differences: base64url uses - and _ instead of + and /, leaves off the = padding, and the dots are not part of any base64 alphabet.
3 causes, each with a fixSecurity
Keycloak blocks your single-page app with a CORS error
Request requires preflight, which is disallowed to follow cross-origin redirects.
Keycloak checks the Origin header of a browser call against the Web origins configured on that client and refuses it with 403 when it does not match.
2 causes, each with a fixSecurity
An HTTPS page is blocked from loading an insecure http:// resource
Mixed Content: The page at 'https://example.com/' was loaded over HTTPS, but attempted to connect to the insecure endpoint 'http://api.example.com/items'. This request has been blocked.
Your page came over HTTPS but something on it points at an http:// address, and the browser refuses the risky kinds (scripts, styles, frames, fetch calls).
4 causes, each with a fixSecurity
Node.js HTTPS call fails with UNABLE_TO_VERIFY_LEAF_SIGNATURE
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
Node.js could not build a trusted chain from the server's certificate to a root it knows.
3 causes, each with a fix