Script Valley
Node.js: The Complete Runtime
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 jsonwebtoken
const 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.

Up next

Building a JWT auth middleware for Express

Sign in to track progress

JWT authentication in Node.js: how it actually works โ€” Authentication and Security โ€” Node.js: The Complete Runtime โ€” Script Valley โ€” Script Valley