What is JWT?
A JWT (JSON Web Token) is a compact, URL-safe token made of three base64url parts (header.payload.signature) that carries claims such as a user id and expiry, signed so the server can verify it was not tampered with.
The three parts
- Header: algorithm and type, e.g.
{"alg":"HS256","typ":"JWT"}. - Payload: claims. Registered claims include
sub(subject/user id),exp(expiry),iat(issued at),iss(issuer),aud(audience). You can add custom ones likerole. - Signature: created with a secret (HMAC, e.g. HS256) or a private key (RSA/ECDSA, e.g. RS256, ES256).
Signed, not encrypted
Anyone can decode the payload; base64 is not encryption. Never put secrets or sensitive personal data in a JWT. (JWE is the encrypted variant.)
How it is used
The server issues a token at login; the client sends it with requests (usually Authorization: Bearer <token>); the server verifies the signature and expiry without a database lookup, which makes JWTs popular for stateless APIs and between services.
Security essentials
- Always verify the signature with a trusted library, and pin the expected algorithm (reject
alg: noneand algorithm-confusion tricks). - Check
exp,issandaud. - Keep access tokens short-lived (minutes), with refresh tokens to renew them.
- Storage: in browsers, prefer HttpOnly, Secure, SameSite cookies over
localStorage, which is readable by any XSS. - Revocation is hard: a valid JWT works until it expires. Use short lifetimes, rotation, or a deny-list for logout and compromised accounts.
JWT vs server sessions
Sessions are easy to revoke and keep data on the server; JWTs avoid a lookup per request and work across services. Many web apps are simpler with sessions.
Code example
1// Sign and verify an HS256 JWT with the Web Crypto API (browsers, Node, Deno, Bun)2const enc = new TextEncoder();3const b64url = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");4const b64urlJson = (obj) => b64url(enc.encode(JSON.stringify(obj)));5const fromB64url = (s) => JSON.parse(atob(s.replace(/-/g, "+").replace(/_/g, "/")));67const secret = await crypto.subtle.importKey("raw", enc.encode("a-long-random-server-secret"), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);89async function sign(payload) {10 const data = `${b64urlJson({ alg: "HS256", typ: "JWT" })}.${b64urlJson(payload)}`;11 const sig = await crypto.subtle.sign("HMAC", secret, enc.encode(data));12 return `${data}.${b64url(sig)}`;13}1415async function verify(token) {16 const [header, payload, signature] = token.split(".");17 if (fromB64url(header).alg !== "HS256") throw new Error("Unexpected algorithm");18 const sigBytes = Uint8Array.from(atob(signature.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));19 const valid = await crypto.subtle.verify("HMAC", secret, sigBytes, enc.encode(`${header}.${payload}`));20 if (!valid) throw new Error("Invalid signature");21 const claims = fromB64url(payload);22 if (claims.exp * 1000 < Date.now()) throw new Error("Token expired");23 return claims;24}2526const now = Math.floor(Date.now() / 1000);27const token = await sign({ sub: "user-42", role: "editor", iat: now, exp: now + 15 * 60 });28console.log(token.split(".").length, "parts"); // 3 parts29console.log(await verify(token)); // { sub: "user-42", role: "editor", iat: ..., exp: ... }3031// Anyone can READ the payload (it is not encrypted)...32console.log(fromB64url(token.split(".")[1]).role); // editor33// ...but tampering breaks the signature34const [h, , s] = token.split(".");35const forged = `${h}.${b64urlJson({ sub: "user-42", role: "admin", exp: now + 900 })}.${s}`;36try {37 await verify(forged);38} catch (e) {39 console.log(e.message); // Invalid signature40}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.