JWT Decoding for Beginners 2026: Security and Debugging Essentials
What a JSON Web Token actually is, what its three parts mean, and how to fix the errors every beginner hits: invalid token format, signature verification failed, and token expired.
What Is a JWT? (And What It Is Not)
A JWT, short for JSON Web Token and defined by RFC 7519, is a compact string that two systems pass back and forth to answer one question: has this person already proven who they are? After you log in to an app, the server hands your browser a JWT. Every later request carries that token, and the server checks it instead of asking for your password again.
Here is the flow in plain language:
- You submit your username and password (or a strong, unique password managed by a password manager).
- The server verifies them and creates a JWT that says, in effect, "this is user 12345, and this claim is valid until 4:15 PM."
- It signs the token so any later edit would be detectable, then sends it to your browser.
- Your browser attaches the token to every API request, usually in the
Authorization: Bearerheader. - The server checks the signature and the expiration, and lets the request through if both check out.
You never need special software to look inside one. Paste any token into our free JWT decoder tool and its header and payload appear instantly. This guide is the beginner-friendly fundamentals track of our security cluster; when you are ready for hardening techniques, the Security Tools Guide pillar and our JWT Decoder tool tutorial are the natural next steps, and the rest of the developer tools guide covers the wider toolkit.
The Three Parts of a JWT, Explained from Scratch
Every JWT looks like a line of gibberish with two dots in it. Those two dots split the token into three parts: header.payload.signature. Each part is base64url encoded, which is a URL-safe flavor of Base64 that swaps the + and / characters for - and _ and usually drops the trailing = padding.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The blue chunk is the header, the green chunk is the payload, and the red chunk is the signature. Let us take them one at a time.
1. The Header
Describes how the token was signed. Decode the blue chunk and you get two or three lines of JSON:
{
"alg": "HS256",
"typ": "JWT"
}
- alg: the signing algorithm (HS256 here)
- typ: the token type, almost always "JWT"
- kid: optional key id, so the server knows which key to use
2. The Payload
Carries the actual statements, called claims. Decode the green chunk:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
- sub: subject, usually the user id
- iat: "issued at" timestamp
- exp: expiration timestamp (added in real tokens)
Anything you add here is readable by anyone. Treat the payload like a sticky note on a postcard, not a sealed letter.
3. The Signature
The tamper-evident seal. The server signs the encoded header and payload with a key only it knows:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
- Purpose: proves the token was not modified
- Key: lives only on the server
- Validation: change one character of the payload and the signature no longer matches
Reading the Payload: Registered and Custom Claims
Claims are the key-value pairs inside the payload. A handful of names are reserved by the JWT standard and have agreed meanings, so every library knows what they mean:
| Claim | Name | Purpose | Example Value | Why It Matters |
|---|---|---|---|---|
iss |
Issuer | Who created and signed the token | "auth.example.com" | Lets the server reject tokens from strangers |
sub |
Subject | Who the token is about | "user123" | The user id your API keys its logic on |
aud |
Audience | Which service the token is meant for | "api.example.com" | Stops a token for service A being replayed to service B |
exp |
Expiration | Unix time after which the token is invalid | 1793472000 | The heart of short-lived tokens |
iat |
Issued At | Unix time when the token was created | 1793468400 | Useful for spotting suspiciously old tokens |
nbf |
Not Before | Unix time before which the token is invalid | 1793468400 | Handy for tokens that activate later |
jti |
JWT ID | Unique id for this specific token | "9b1deb4d..." | Enables blocklists; generate one with our UUID generator |
Beyond the reserved names, apps freely add custom claims such as "role": "editor" or "permissions": ["read", "write"]. The golden rule stands for all of them: claims are statements, not proof. Only the server-side signature check turns those statements into something trustworthy, and every registered claim should be validated on the server, never in the browser alone.
Encoding vs Signing vs Encryption: A Suitcase Analogy
These three words get mixed up constantly, so here is a suitcase analogy that keeps them straight:
- Encoding is rewriting the label in a different alphabet. You print the itinerary in a font that airports everywhere can scan. Anybody who walks by can read it. Nothing is hidden; it is just portable.
- Signing is a tamper-evident wax seal. The note inside stays readable, but if anyone edits it, the seal cracks in a way you can prove. Only the owner of the stamp (the server key) can produce a valid seal.
- Encryption is locking the suitcase. Now the contents are unreadable without the key, not just un-editable.
A standard JWT uses encoding plus signing. It does not use encryption. You can see this yourself with nothing but a browser:
// Anyone can read a JWT payload - no key required
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const parts = token.split('.');
const json = atob(parts[1].replace(/-/g, '+').replace(/_/g, '/'));
// Result: {"sub":"1234567890","name":"John Doe","iat":1516239022}
| Concept | What It Does | Reversible Without a Key? | Protects Against | In a Standard JWT? |
|---|---|---|---|---|
| Encoding | Repackages data in a portable alphabet (base64url) | Yes, by anyone | Nothing - it is not a security measure | Yes |
| Signing | Adds a verifiable seal over the header and payload | Reading: yes. Forging: no | Tampering | Yes |
| Encryption | Scrambles contents so they are unreadable | No | Reading | No (that is JWE, a separate standard) |
Because HMAC is just a keyed hash, you can build intuition for the signature side by experimenting with our hash generator and SHA-256 hash generator: change one character of the input and the entire digest changes.
HS256 vs RS256 in Plain English
The alg header in real tokens is usually one of two names, and the difference between them is easier than it sounds:
- HS256 is a shared-password scheme. One secret key both creates the signature and checks it. It is like a house key: the same key locks and unlocks the door, so every copy of that key must be guarded.
- RS256 is a key-pair scheme. A private key signs, and a mathematically linked public key verifies. Anyone can check the seal, but only the private key holder can create it - like a padlock you can click shut but only one key can open.
| HS256 | RS256 | |
|---|---|---|
| Key type | One shared secret string | Private key + public key pair |
| Who can verify | Only services that know the secret | Anyone with the public key |
| Best for | A single app with one server or a tightly controlled cluster | Multiple services or third parties that need to verify your tokens |
| Beginner watch-out | Weak or leaked secrets (generate long random ones) | Do not confuse private and public keys when verifying |
Whichever algorithm you pick, keep access tokens short-lived. Current OAuth 2.1 draft guidance favors short-lived access tokens paired with refresh tokens, and that advice works just as well for a weekend project as for a large platform.
Where Should Your JWT Live? localStorage vs httpOnly Cookies
Once your browser has a token, something has to hold it between requests. Beginners almost always start with localStorage because it is two lines of code. It is worth understanding the trade-off you are making:
| Aspect | localStorage | httpOnly Cookie |
|---|---|---|
| Readable by JavaScript? | Yes - any script on the page | No - the browser manages it |
| Exposure to XSS bugs | High: one injected script steals the token | Low: the token cannot be read even if a script runs |
| Exposure to CSRF | Low: you attach the token manually per request | Higher: the browser sends it automatically, so set SameSite |
| Typical size limit | About 5 MB per origin | About 4 KB per cookie |
| Effort to use | Trivial | Needs server cookie configuration |
A httpOnly cookie is set by the server with flags that do the protecting for you:
Set-Cookie: access_token=eyJhbGciOi...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=900
- HttpOnly hides the cookie from JavaScript, which neutralizes token theft via XSS.
- Secure restricts the cookie to HTTPS connections.
- SameSite limits cross-site sending, which blunts CSRF attacks.
- Max-Age keeps the window short - fifteen minutes is a common choice for access tokens.
The honest summary: for learning and prototypes, localStorage is fine. For anything users depend on, prefer short-lived tokens in httpOnly, Secure, SameSite cookies, and keep access tokens small regardless of where they live.
Debugging the Three Most Common JWT Errors
Almost every beginner JWT problem falls into one of three buckets. Before touching any of them, run this universal three-step check:
- Check the shape: does the token have exactly two dots and three non-empty chunks?
- Decode it: paste it into the JWT decoder and confirm the header and payload are readable JSON.
- Verify it: confirm the algorithm and key your server expects match what the header claims.
Now the three errors, each with its cause and fix.
Error 1: "Invalid token format" (or "jwt malformed")
What it means: the library could not even split the token into three parts, so it gave up before any cryptography happened.
Typical causes:
- The token got truncated or wrapped when copied - a common casualty of terminal line breaks or chat apps
- An extra space, newline, or the word "Bearer" was pasted along with the token
- Only two parts exist because the signature was dropped (some APIs return unsigned tokens by misconfiguration)
- You are passing the whole
Authorizationheader value instead of just the token
The fix: trim the string, remove any Bearer prefix, and assert the three-part shape before doing anything else:
function assertJwtShape(token) {
if (typeof token !== 'string') {
throw new Error('Token must be a string');
}
const parts = token.trim().split('.');
if (parts.length !== 3 || parts.some(p => p.length === 0)) {
throw new Error('Invalid JWT format: expected header.payload.signature');
}
return parts; // [header, payload, signature]
}
Error 2: "Signature verification failed" (or "invalid signature")
What it means: the token is well-formed, but when the server re-computed the signature it did not match the third chunk. Either the contents changed after signing, or you are checking with the wrong key.
Typical causes:
- Wrong secret: dev secret in production, or a typo, or a trailing newline in an environment variable
- Environment mismatch: a token issued by your staging server being verified by production
- Algorithm mismatch: the header says HS256 but your code verifies with RS256 keys (or vice versa)
- The payload really was edited - by you testing, or by an attacker
The fix: first decode the token and read the alg header. Then verify with the exact expected algorithm and the exact counterpart key:
// Node.js example - never let the library guess the algorithm
const jwt = require('jsonwebtoken');
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
algorithms: ['HS256'], // explicit allowlist
issuer: 'auth.myapp.com', // optional but recommended checks
clockTolerance: 30 // seconds of clock-skew allowance
});
// Token is authentic and unmodified
} catch (err) {
// err.name === 'JsonWebTokenError' means signature/format problems
// err.name === 'TokenExpiredError' means exp has passed
}
Error 3: "Token expired" (TokenExpiredError)
What it means: everything about the token is valid, but the current time is now past the exp claim. This is your security working as designed - the token has a built-in odometer that ran out.
Typical causes:
- Simple as it sounds: the token really is older than its expiration
- Clock skew: your server's clock is minutes ahead of or behind the token issuer's clock
- An unreasonably short expiration (a 30-second token will feel "randomly broken")
- Missing refresh flow: the app has no way to swap a stale token for a fresh one
The fix: decode the payload and convert exp to a human-readable date, then decide whether you need clock tolerance or a refresh flow:
// Inspect expiration manually
const payload = JSON.parse(
atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
);
const expiresAt = new Date(payload.exp * 1000);
const msLeft = payload.exp * 1000 - Date.now();
// Rule of thumb: if msLeft is negative, refresh or re-authenticate.
// If it is small but positive, schedule a silent refresh before it lapses.
Short-lived access tokens (15 to 60 minutes) paired with a refresh token are the modern pattern, and they are why a well-built app logs you out quietly rather than nagging you.
60-Second JWT Debugging Checklist
- Two dots, three chunks, no stray spaces or "Bearer" prefix
- Header and payload decode to valid JSON
algin the header matches the algorithm your verifier expects- Verification key is the exact counterpart of the signing key (same environment)
- Current server time is between
nbfandexp, with a little clock tolerance issandaudmatch what your server expects
Try It Yourself: Decode a JWT in Under a Minute
The fastest way to make JWTs stop feeling magical is to open one up. Grab a token from your app (browser DevTools, the Application tab, then Local Storage or Cookies) and follow along:
- Paste the token into the JWT Decoder. The header and payload appear decoded, with each part labeled.
- Want to do it manually instead? Split the token on the dots and run the first two chunks through the Base64 encoder/decoder with the URL-safe alphabet.
- Pretty-print the resulting payload JSON with the JSON formatter to read the claims comfortably.
- Check
exp: multiply by 1000 and compare with the current time to see exactly when the token dies. - If your token arrived inside a query string looking doubly-mangled, it was probably URL-encoded - decode the wrapper first with the URL encoder/decoder.
Learning to read tokens by hand pays off beyond authentication work, too. Many APIs wrap JSON in base64 or URL encoding, and the rest of our developer tools handle those formats the same no-nonsense way.
Beginner-Friendly Security Habits
You do not need to memorize an attack catalog to use JWTs responsibly. Internalize these habits and you will avoid the mistakes that cause most real-world incidents:
- Generate signing secrets with a cryptographic random source - 256 bits or more. Our random string generator and password generator both use one in your browser.
- Keep access tokens short-lived and lean on refresh tokens for longevity.
- Always verify signatures server-side, and specify the allowed algorithm explicitly.
- Never log tokens - logs are read by more people and systems than you think.
- Serve everything over HTTPS; a bearer token sent in the clear is a gift to network snoops.
- Prefer httpOnly cookies for browser storage, and set
SecureandSameSite. - Keep secrets out of code and client bundles; environment variables or a key manager only.
- Remember that the same discipline behind choosing a strong password applies to signing secrets: long, random, unique.
Two notes on the wider landscape. First, authentication itself is drifting passwordless - passkeys and FIDO2 are now mainstream on major platforms - but the tokens issued after authentication still follow the JWT rules in this guide, so these skills are not going anywhere. Second, this article deliberately stops at the beginner line. Attack classes such as the alg: none trick and algorithm confusion are real and worth learning once you are comfortable here; our advanced JWT security hardening guide picks up exactly where this one ends, and if you want to know how password storage differs from token signing, see our deep dive on password hash generators and advanced security strategies.
Decode Your First JWT Now
Reading a token takes ten seconds and makes everything above click. No signup, no server round-trip - it all happens in your browser.