In this guide
A simple guide to this issue: 'JsonWebTokenError / TokenExpiredError' in Node.js JWT Auth. Learn why it happens, what to check first, and how to fix it.
jsonwebtoken throws different errors for different problems — and treating them all as a generic 500 gives users a broken experience. Branch on the error type and add refresh tokens.
The Errors
TokenExpiredError: jwt expired | JsonWebTokenError: invalid signature | JsonWebTokenError: jwt malformed
Branch on the Error Type
const jwt = require("jsonwebtoken");
function verifyToken(req, res, next) {
try {
req.user = jwt.verify(req.token, process.env.JWT_SECRET);
return next();
} catch (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ code: "TOKEN_EXPIRED" });
}
return res.status(401).json({ code: "TOKEN_INVALID" });
}
}Add a Refresh Token Flow
Keep access tokens short-lived (15m) and issue a long-lived refresh token. When the client sees TOKEN_EXPIRED, it silently calls /refresh to get a new access token instead of logging the user out.
const accessToken = jwt.sign({ id }, SECRET, { expiresIn: "15m" });
const refreshToken = jwt.sign({ id }, REFRESH_SECRET, { expiresIn: "30d" });Clock Skew
If tokens 'expire instantly' across servers, their clocks differ. Allow a small tolerance: jwt.verify(token, secret, { clockTolerance: 10 }).
Relevant Scaleup Infotech Services
Keep Reading
Fix React Search Results Showing the Wrong Data
Fix React search race conditions with request cleanup, cancellation, and stale-response checks. Includes code and a slow-network verification checklist.
5 min readFix Next.js Environment Variables Missing in Production
Fix missing Next.js production environment variables by checking build-time values, public prefixes, deployment settings, and the exact release artifact.
5 min readFix Laravel Queue Jobs Not Processing After Deployment
Recover Laravel queue jobs after deployment by checking the connection, queue name, workers, cached configuration, failed jobs, and restart behavior.
5 min read