signing and verifying JWTs with jsonwebtoken in Node.js
jsonwebtoken library, jwt.sign options, jwt.verify, secret key management, TokenExpiredError, JsonWebTokenError, synchronous vs async sign
Signing and Verifying JWTs with jsonwebtoken
The jsonwebtoken package is the Node.js standard for JWT operations.
const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET; // never hardcode
// Signing
const token = jwt.sign(
{ sub: user.id, role: user.role },
SECRET,
{ expiresIn: '1h', issuer: 'myapp' }
);
// Verifying
try {
const payload = jwt.verify(token, SECRET);
console.log(payload.sub); // user ID
} catch (err) {
if (err.name === 'TokenExpiredError') {
// token is valid but expired
} else if (err.name === 'JsonWebTokenError') {
// signature invalid, malformed token, algorithm mismatch
}
}jwt.sign accepts the payload object, the secret, and an options object. expiresIn accepts time strings like '15m', '1h', '7d'.
jwt.verify throws on any failure. Always wrap it in try/catch. The two errors you must handle separately are TokenExpiredError (valid signature, but past expiry — trigger a refresh flow) and JsonWebTokenError (invalid — reject immediately).
Store your secret in an environment variable. A 256-bit random string is the minimum. For production, generate it with openssl rand -base64 32. Rotating secrets requires re-issuing all tokens — plan for this early.
