← Blog

Understanding JWTs

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

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

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.