DevLab
Encoding

JWT Structure and How It Works

Understand JSON Web Tokens: their structure, how to decode them, and when to use (and not use) them.

What is a JWT?

A JSON Web Token (JWT) is a compact, URL-safe token format for transmitting claims between parties. It's most commonly used for authentication and authorization in web APIs.

A JWT looks like: xxxxx.yyyyy.zzzzz — three parts separated by dots. Each part is Base64URL-encoded.

The Three Parts

1. Header — Specifies the token type and signing algorithm:

{"alg": "HS256", "typ": "JWT"}

2. Payload — Contains the claims (statements about the user):

{"sub": "1234567890", "name": "John Doe", "iat": 1516239022, "exp": 1516242622}

Standard claims include: sub (subject), iat (issued at), exp (expiry), iss (issuer), aud (audience).

3. Signature — Verifies the token hasn't been tampered with:

HMACSHA256(base64url(header) + "." + base64url(payload), secret)

Decoding vs. Verifying

Anyone can decode a JWT — the payload is just Base64, not encrypted. Decoding is just reading the data. Verifying means checking the signature against a secret key to ensure the token is legitimate and hasn't been modified. Client-side decoding is fine for reading claims; never skip server-side verification for security decisions.

Common JWT Pitfalls

  • Don't store sensitive data in the payload — it's readable by anyone with the token
  • Always verify the signature server-side before trusting any claim
  • Check the exp claim — expired tokens should be rejected
  • Use short expiry times — JWTs can't be invalidated after issue (unless you maintain a denylist)
  • Don't store JWTs in localStorage — use httpOnly cookies to prevent XSS attacks

Practice with these tools

More Learning Topics