A JSON Web Token (JWT) is a compact, signed string that carries a set of claims about a user or a session. Servers hand one out after login, and clients send it back on every request, usually in an Authorization: Bearer header.
Three parts, one string
A JWT is three base64url-encoded segments joined by dots:
header.payload.signature
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiJ9.4pcPyMD09olPSyXnrXCjTwXyr4BsezdI1AVTmud2fU4- Header: the signing algorithm, e.g.
{"alg":"HS256","typ":"JWT"}. - Payload: the claims, such as
sub(who),exp(when it expires) and anything custom. - Signature: a hash of the first two parts made with a secret or private key.
The payload is encoded, not encrypted. Anyone holding the token can read it, so never put secrets in there.
How verification works
The server recomputes the signature from the header and payload using its key and compares it with the one on the token. If a single byte of the payload changed, the signatures no longer match and the token is rejected. That is the whole trick: the server does not need to store the session, it only needs the key.
import { jwtVerify } from "jose";
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
export async function getUserId(token: string) {
const { payload } = await jwtVerify(token, secret, {
algorithms: ["HS256"],
});
return payload.sub;
}Mistakes worth avoiding
- Trusting the header's algorithm. Pin the algorithms you accept, or an attacker can send
alg: none. - Long-lived access tokens. A JWT cannot be revoked once issued. Keep access tokens short (minutes) and pair them with a refresh token you can revoke.
- Storing tokens in localStorage. Any XSS can read it. An
HttpOnly,Secure,SameSitecookie is usually the safer home. - Skipping claim checks. Verify
exp, andissandaudwhen more than one service issues tokens.
When to reach for one
JWTs shine when several services need to trust the same identity without calling a central session store. For a single app with a single database, a plain server-side session is often simpler and easier to revoke. Pick the tool that fits, not the one that is fashionable.