Authentication and SecurityLesson 5.1
JWT authentication in Node.js: how it actually works
JWT structure, header/payload/signature, jsonwebtoken library, signing tokens, verifying tokens, token expiration, access vs refresh tokens, token storage
A JWT Is a Signed Claim
A JSON Web Token (JWT) has three base64url-encoded parts separated by dots: header (algorithm), payload (claims like userId), and signature (header + payload signed with a secret). The server verifies the signature — if valid, it trusts the payload without a database lookup.
npm install jsonwebtokenconst jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;
const token = jwt.sign(
{ userId: '123', role: 'admin' },
SECRET,
{ expiresIn: '15m' }
);
try {
const decoded = jwt.verify(token, SECRET);
console.log(decoded.userId); // '123'
} catch (err) {
console.error('Invalid token:', err.message);
}Access + Refresh Token Pattern
Access tokens expire in 15 minutes. Refresh tokens (stored in an httpOnly cookie) last 7 days. When the access token expires, the client silently requests a new one using the refresh token — without re-login. This limits the blast radius if an access token is stolen.
