JWT Explained
What a JSON Web Token is, what's inside one, how the signature works, and how to create and check them safely in TypeScript.

Many APIs you log in to hand you a JWT. You send it back with every request, and the server knows who you are. It looks like a long string of random characters, but there's nothing random about it, and once you can read one, a lot of security advice starts to make sense.
This post covers what a JWT is, what's inside it, how the signature works, and how to create and check them in TypeScript. Two follow-up posts go further: Refresh Tokens Explained and JWT Signing Keys.
What a JWT is for
When you log in, the server checks your password once. After that, it needs a way to remember who you are on every following request, without asking for your password again.
There are two common ways to do that, and an app usually picks one:
- Sessions: the server makes a random id, stores "this id belongs to alice" in its database, and gives you the id. Every request, it looks the id up.
- Tokens (JWT): the server writes "this is alice" into the token itself, signs it, and gives you the token. Every request, it checks the signature. No database lookup needed.
Both start the same way, with a password check at login. They only differ in how the server remembers you afterwards. Sessions have their own post, Sessions Explained; this one is about tokens.
A JWT is like a wristband at a festival. The staff don't need a list of everyone who paid; they only need to check that the wristband is real.
The whole flow, from login to logout
Most apps hand out two tokens at login: a short-lived JWT, called the access token, that goes with every request, and a long-lived refresh token that is only used to get a new access token. Here's how they work together:
1 · Log in The password is checked once.
- Browser to Server: POST /login email + password
2 · Hand out two tokens The access token is signed, not stored. Only the refresh token goes in the database.
- Server: sign { sub: alice, exp: 15m }
- Server to Database: save r7k2 → alice
- Server to Browser: accessToken: eyJ…
- Server to Browser: Set-Cookie: refreshToken=r7k2; HttpOnly
3 · Every request after that The access token rides along, and the server checks its signature. The database isn’t involved.
- Browser to Server: GET /profile Authorization: Bearer eyJ…
- Server: signature ok, exp not passed
- Server to Browser: 200 alice’s profile
4 · 15 minutes later The access token has expired. The refresh token is used up and swapped for a new pair.
- Browser to Server: POST /refresh Cookie: refreshToken=r7k2
- Server to Database: mark r7k2 used
- Database to Server: alice
- Server to Database: save m4q9 → alice
- Server to Browser: new accessToken + refreshToken=m4q9
5 · Log out Deleting the refresh token means no new access tokens.
- Browser to Server: POST /logout Authorization: Bearer eyJ…
- Server to Database: delete alice’s refresh tokens
- Server to Browser: clear the cookie
6 · A copied token still works, for a while An attacker replays both tokens. The access token works until exp; the refresh token is gone.
- Attacker to Server: GET /profile Authorization: Bearer eyJ…
- Server: signature ok, exp not passed
- Server to Attacker: 200 alice’s profile
- Attacker to Server: POST /refresh Cookie: refreshToken=r7k2
- Server to Database: find r7k2
- Database to Server: not found
- Server to Attacker: 401 Unauthorized
Compare step 3 with the same step in Sessions Explained: the server answers without asking the database, because "this is alice" is written inside the token. The last step shows the price of that. The server has no list to delete the access token from, so a copy keeps working until it expires.
This post is about the access token: what's inside it and how the signature is checked. The refresh token has its own post, Refresh Tokens Explained.
What's inside a token
Here's a real JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIsImlhdCI6MTc2MzUzOTIwMCwiZXhwIjoxNzYzNTQwMTAwfQ.346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bgIt's three parts joined by dots:
header.payload.signatureThe first two parts are just JSON, encoded as base64url (base64 with characters that are safe in a URL). Anyone can decode them:
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIsImlhdCI6MTc2MzUzOTIwMCwiZXhwIjoxNzYzNTQwMTAwfQ.346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bg";
const [header, payload] = token .split(".") .slice(0, 2) .map((part) => JSON.parse(Buffer.from(part, "base64url").toString()));
console.log(header); // { alg: "HS256", typ: "JWT" }console.log(payload); // { sub: "alice", iat: 1763539200, exp: 1763540100 }The header
{ "alg": "HS256", "typ": "JWT" }It says what kind of token this is (typ) and which algorithm made the
signature (alg). HS256 means HMAC with SHA-256: one shared secret both
makes and checks the signature. That's fine when a single server does both,
and it's what the examples below use. JWT Signing Keys
covers when to use a key pair instead.
The payload
{ "sub": "alice", "iat": 1763539200, "exp": 1763540100 }This is the actual information, and each field is called a claim. Some claims have standard, short names:
sub(subject): who the token is about, usually the user id.exp(expiration time): after this moment, the token must be rejected.iat(issued at): when the token was made.iss(issuer): who made it, for example"api.example.com".aud(audience): who it's meant for, for example"example-web".nbf(not before): the token isn't valid until this moment.jti(JWT id): a unique id for this one token.
Times are in seconds since 1 January 1970 (a Unix timestamp), not
milliseconds. 1763540100 - 1763539200 is 900 seconds, so this token lasts
15 minutes.
You can add your own claims too, like role: "admin". Keep the payload small:
it's sent with every single request.
The signature
346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bgThis is what makes a JWT trustworthy. The server takes the first two parts and runs them through HMAC-SHA256 together with a secret key that only the server knows. Here it is one step at a time, with the type and value of each step:
import { createHmac } from "node:crypto";
const [header, payload] = token.split(".");
// 1. Join the two parts with a dot. This is the text we sign.const data = `${header}.${payload}`;// string: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGljZSIs..."
// 2. Make an HMAC object that uses SHA-256 and our secret key.const hmac = createHmac("sha256", "example-secret");// Hmac: nothing is calculated yet
// 3. Give it the text to sign.hmac.update(data);// still the same Hmac object
// 4. Finish the calculation and get the result as text.const signature = hmac.digest("base64url");// string: "346rpzA18fohm5MCh2AudA7bhGK6f12crT65WD2u9bg"Step 4 produces 32 bytes, the size of every SHA-256 result, and "base64url"
writes them as the 43 characters you see in the token. You'll often see the
same thing written as one chain:
createHmac(...).update(...).digest("base64url"). That works because update
returns the same Hmac object.
Why mix in a key? Anyone can compute a plain SHA-256 hash, so an attacker could edit the payload and simply hash it again. With HMAC, only someone who has the key can produce the right signature.
Why sign the header too? Because it tells the server how to check the token:
alg names the algorithm, and kid (when there is one) names the key. If the
header weren't signed, an attacker could edit it without breaking the
signature.
Put together, two things follow:
- Change one character of the header or payload and the signature no longer
matches. Turning
"alice"into"admin"produces a completely different signature. - You can't make a new matching signature without the secret. So the server can be sure that it wrote this payload itself, and nobody edited it since.
That is the whole security of a JWT. It only works if the server actually checks the signature on every request.
Creating and checking tokens in TypeScript
You don't need to do the HMAC by hand. The
jose package does it, along with the claim
checks. It has no dependencies and runs anywhere with Web Crypto: Node,
browsers, Deno, Bun and edge runtimes.
Creating a token at login
import { SignJWT } from "jose";
// At least 32 random bytes, e.g. from `openssl rand -base64 32`. Never in the code.const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET!);
function signToken(user: { id: string; role: string }) { return new SignJWT({ role: user.role }) .setProtectedHeader({ alg: "HS256" }) .setSubject(user.id) // → sub .setIssuer("api.example.com") // → iss .setAudience("example-web") // → aud .setIssuedAt() // → iat .setExpirationTime("15m") // → exp, 15 minutes from now .sign(JWT_SECRET);}jose takes the secret as bytes, not a string, hence the TextEncoder. And
sign returns a promise, so await signToken(user).
The secret needs to be long and random. Anyone holding a token can try
guessing secrets offline until one produces the same signature, so a word like
"mysecret" falls in seconds. HS256 needs at least 32 bytes (256 bits) to be
out of reach.
Checking a token on every request
import { jwtVerify } from "jose";
async function requireAuth(req: Request, res: Response, next: NextFunction) { const header = req.headers.authorization; if (!header?.startsWith("Bearer ")) return res.sendStatus(401);
try { const { payload } = await jwtVerify<{ role: string }>( header.slice("Bearer ".length), JWT_SECRET, { algorithms: ["HS256"], issuer: "api.example.com", audience: "example-web", requiredClaims: ["sub", "exp"], clockTolerance: 5, // seconds of leeway for exp and nbf }, );
req.user = { id: payload.sub!, role: payload.role }; next(); } catch { res.sendStatus(401); }}jwtVerify does all of the following, and throws if any of them fail:
- Recomputes the signature with your secret and compares it.
- Checks the algorithm is one you listed. An attacker can write anything in
the header, including
alg: "none", so the server decides, not the token. - Checks
exphasn't passed (andnbfhas). - Checks
issandaudmatch. - Checks every claim in
requiredClaimsis there. Without it, a token with noexpwould never expire.
clockTolerance is there because two servers' clocks are never exactly the
same. A token made by one can look a second "not yet valid" to another. A few
seconds covers that. Curity
recommends staying under 30 seconds, since every second of leeway stretches
every token's life.
Sending the token
The client sends it in the Authorization header with the word Bearer
("whoever bears this token"):
curl localhost:3000/me -H "Authorization: Bearer eyJhbGciOi..."The catch: you can't take a token back
Because the server doesn't store tokens, it also can't easily cancel one. If a
token is stolen, it keeps working until exp, even if the user logs out or
changes their password. That's why access tokens should last only a few
minutes, paired with a refresh token that keeps the user logged in.
Refresh Tokens Explained covers how to build
that safely.
The short version
- A JWT is
header.payload.signature. The first two parts are readable by anyone, so don't put anything private in them. - The signature is an HMAC of the header and payload. It proves the server wrote them and nobody changed them since.
- Always
jwtVerify, withalgorithms,issandaudpinned, neverdecodeJwt. - Keep the secret in an environment variable: at least 32 random bytes.
- Give access tokens a short
exp. For a single web app, consider plain sessions instead.
Next: Refresh Tokens Explained for staying logged in, and JWT Signing Keys for when more than one service checks tokens.