How to Fix Node.js JWT jsonwebtoken Verification Failed
In this tutorial, you'll learn about How to Fix Node.js JWT jsonwebtoken Verification Failed. We cover key concepts, practical examples, and best practices.
The Problem
Your Node.js app calls jwt.verify() and gets JsonWebTokenError: invalid signature or TokenExpiredError, because the secret does not match, the token has expired, or the algorithm specified in options does not match the token header.
Quick Fix
Verify Token with the Correct Secret and Algorithm
node -e "
const jwt = require('jsonwebtoken');
const secret = 'my-secret-key';
const token = jwt.sign({ user: 1 }, secret, { expiresIn: '1h' });
try {
const decoded = jwt.verify(token, secret);
console.log('Valid:', decoded);
} catch (err) {
console.error('Invalid:', err.message);
}
"
# Valid: { user: 1, iat: ..., exp: ... }
Always use the exact same secret string for signing and verification. Mismatched secrets cause invalid signature. For HMAC algorithms, the secret must be identical byte-for-byte.
Check for Token Expiration
node -e "
const jwt = require('jsonwebtoken');
const secret = 'key';
const token = jwt.sign({ user: 1 }, secret, { expiresIn: '1s' });
setTimeout(() => {
try {
jwt.verify(token, secret);
} catch (err) {
console.error(err.name, err.message);
}
}, 2000);
"
# TokenExpiredError jwt expired
jwt.verify() throws TokenExpiredError when the token's exp claim has passed. Handle this separately from other verification errors with a specific catch block.
Handle the Error Gracefully
node -e "
const jwt = require('jsonwebtoken');
function verifyToken(token, secret) {
try {
return { valid: true, data: jwt.verify(token, secret) };
} catch (err) {
if (err.name === 'TokenExpiredError') {
return { valid: false, reason: 'expired' };
}
return { valid: false, reason: 'invalid' };
}
}
console.log(verifyToken('bad-token', 'key'));
"
# { valid: false, reason: 'invalid' }
Always wrap jwt.verify() in a try/catch and distinguish between expired tokens and invalid signatures for better user experience, such as prompting re-login vs. token refresh.
Check Node.js and npm Versions
node --version
# v18.17.0
npm --version
# 9.6.7
Verify your runtime versions before troubleshooting module resolution or compatibility issues. Outdated versions of Node.js or npm are a common source of mysterious errors. Use nvm to manage multiple Node versions side by side.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Prevention
- Store the JWT secret in an environment variable, never hardcode it in source code
- Use short expiration times (15–60 minutes) and implement refresh token rotation
- Validate the
iss(issuer) andaud(audience) claims in multi-service architectures - Use RS256 with a public/private key pair instead of HS256 for cross-service verification
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro