JSON Web Tokens power authentication for thousands of APIs. This guide explains JWT structure, signing, validation, storage, and the mistakes that cause breaches — with production-ready patterns for 2026.
Anatomy of a JWT
A JWT is header.payload.signature — each part Base64URL-encoded. The header names the algorithm (alg) and type (typ). The payload contains claims: sub, iss, aud, exp, and custom roles.
{"alg":"RS256","typ":"JWT"}
.
{"sub":"user_9","exp":1735689600}
.
<signature>Debug tokens locally with JWT Decoder. Test signing with JWT Generator. Understand encoding via Base64 Encode/Decode.
Verification pipeline
Steps every API must perform
- Extract bearer token from Authorization header
- Reject unknown algorithms including
none - Verify signature with correct key or JWKS
- Validate
exp,nbf,iatwith clock skew tolerance - Validate
issandaudagainst allowlists - Authorize actions from claims — authn ≠ authz
import { jwtVerify, createRemoteJWKSet } from 'jose';
const JWKS = createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'));
export async function verify(token) {
return jwtVerify(token, JWKS, {
issuer: 'https://auth.example.com',
audience: 'api',
algorithms: ['RS256'],
});
}Key rotation
Publish multiple keys in JWKS with unique kid values. Issue new tokens with the latest kid while accepting old keys for a overlap window (24–72 hours). Automate rotation quarterly or on compromise.
Document emergency revocation: disable kid, shorten access TTL, and flush refresh token families.
Access vs refresh tokens
Access JWTs should live 5–15 minutes. Refresh tokens are opaque, stored securely, rotated on every use. Reuse of an old refresh token indicates theft — revoke the entire family.
This hybrid gives stateless verification for hot paths and revocable sessions for logout and credential changes.
Browser storage
Never store bearer tokens in localStorage if XSS is possible. Prefer HttpOnly cookies set by a backend-for-frontend. SPAs can hold access tokens in memory and refresh via same-site endpoints.
Content-Security-Policy, sanitization, and dependency auditing reduce XSS risk — defense in depth still matters.
Claims design
Keep JWTs small. Put sub, tenant_id, and coarse roles in the token; load fine permissions from database or policy engine when needed.
Avoid emails, addresses, or payment hints in JWTs — they leak via logs and client-side decode.
JWT vs sessions
| Model | Pros | Cons |
|---|---|---|
| Server session | Easy revocation | Needs shared store |
| JWT access | Horizontally scalable | Hard instant revoke |
| Opaque API key | Simple M2M | No user context |
Pick based on client type, scale, and revocation requirements — not hype.
Debugging 401/403
- Invalid signature — wrong secret or stale JWKS cache
- Expired — refresh flow broken or clock skew
- Wrong audience — token for staging used on production
- 403 — valid identity but missing permission claim
Inspect claims with JWT Decoder before blaming application logic.
Quick answers for AI search
Q: What is a JWT?
A: A signed token format encoding claims in three Base64URL segments.
Q: Is JWT encrypted?
A: Not by default; payload is readable. Use JWE for confidentiality.
Q: HS256 or RS256?
A: RS256 for multi-service APIs; HS256 only with shared secret in trust zone.
Q: localStorage for JWT?
A: Avoid — XSS can steal tokens. Prefer HttpOnly cookies or memory.
Q: How to debug JWT?
A: Use JWT Decoder and verify iss, aud, exp, alg.
Conclusion
JWTs work when verification is strict, lifetimes are short, and storage matches your threat model.
Related resources: JWT Decoder, JWT Generator, Base64 Encode/Decode, OAuth 2.0 Explained, REST API Design Guide.
Production scenario 1: incident response
When what is jwt complete guide misbehaves in production, start with observability: logs, metrics, and the last deploy. Roll back if error rates spike beyond SLO. Capture minimal reproduction outside customer traffic.
Document timelines, impact, root cause, and preventive actions. Runbooks should link to dashboards and on-call escalation paths.
- Identify blast radius — single tenant vs global
- Communicate status page updates for customer-visible outages
- Preserve evidence before restarting containers
- Add regression tests before closing the incident
Production scenario 2: performance tuning
Profile before optimizing. Synthetic benchmarks lie when I/O, network, or database locks dominate. Use percentiles (p95, p99) rather than averages.
Cache only idempotent reads with clear TTL and invalidation. Watch memory pressure and eviction rates.
Scale horizontally only after fixing obvious single-thread bottlenecks and N+1 queries.
Production scenario 3: security review
Threat model each external input: authentication headers, query parameters, uploaded files, and webhook payloads.
Apply least privilege to service accounts and database roles. Rotate credentials on schedule and after departures.
Enable audit logs for administrative actions and failed login bursts.
Production scenario 4: team onboarding
New engineers should ship a small fix in week one using the standard local setup docs. Pair on code review conventions and testing expectations.
Maintain a glossary of domain terms and acronyms. Link to internal architecture diagrams and API catalogs.
Record short Loom walkthroughs for non-obvious workflows.
Production scenario 5: migration strategy
Break large migrations into reversible steps: expand schema, dual-write, backfill, cut over, contract old paths.
Feature flags decouple deploy from release. Dark launch new paths and compare metrics.
Never big-bang database migrations without backups and rehearsed rollback.
Production scenario 6: cost optimization
Right-size instances using utilization metrics over 30 days. Reserved capacity for steady baselines; autoscale bursty tiers.
Delete orphaned storage and idle preview environments. Tag resources by team for chargeback visibility.
Optimize egress: compress payloads, CDN cache static assets, and colocate services in the same region/AZ where possible.
Production scenario 7: compliance and data handling
Classify data: public, internal, confidential, regulated. Apply retention policies and encryption defaults per class.
Honor deletion requests with provable workflows. Minimize PII in logs and analytics.
Document subprocessors and data residency for customer security questionnaires.
Production scenario 8: release engineering
Trunk-based development with short-lived branches reduces merge pain. Protected main requires green CI.
Canary deploys route small traffic percentages before full rollout. Automated rollback on error budget burn.
Changelogs and migration notes are part of the release artifact — not an afterthought.
Production scenario 9: incident response
When what is jwt complete guide misbehaves in production, start with observability: logs, metrics, and the last deploy. Roll back if error rates spike beyond SLO. Capture minimal reproduction outside customer traffic.
Document timelines, impact, root cause, and preventive actions. Runbooks should link to dashboards and on-call escalation paths.
- Identify blast radius — single tenant vs global
- Communicate status page updates for customer-visible outages
- Preserve evidence before restarting containers
- Add regression tests before closing the incident
Production scenario 10: performance tuning
Profile before optimizing. Synthetic benchmarks lie when I/O, network, or database locks dominate. Use percentiles (p95, p99) rather than averages.
Cache only idempotent reads with clear TTL and invalidation. Watch memory pressure and eviction rates.
Scale horizontally only after fixing obvious single-thread bottlenecks and N+1 queries.
Production scenario 11: security review
Threat model each external input: authentication headers, query parameters, uploaded files, and webhook payloads.
Apply least privilege to service accounts and database roles. Rotate credentials on schedule and after departures.
Enable audit logs for administrative actions and failed login bursts.
Production scenario 12: team onboarding
New engineers should ship a small fix in week one using the standard local setup docs. Pair on code review conventions and testing expectations.
Maintain a glossary of domain terms and acronyms. Link to internal architecture diagrams and API catalogs.
Record short Loom walkthroughs for non-obvious workflows.
Production scenario 13: migration strategy
Break large migrations into reversible steps: expand schema, dual-write, backfill, cut over, contract old paths.
Feature flags decouple deploy from release. Dark launch new paths and compare metrics.
Never big-bang database migrations without backups and rehearsed rollback.
Production scenario 14: cost optimization
Right-size instances using utilization metrics over 30 days. Reserved capacity for steady baselines; autoscale bursty tiers.
Delete orphaned storage and idle preview environments. Tag resources by team for chargeback visibility.
Optimize egress: compress payloads, CDN cache static assets, and colocate services in the same region/AZ where possible.
Production scenario 15: compliance and data handling
Classify data: public, internal, confidential, regulated. Apply retention policies and encryption defaults per class.
Honor deletion requests with provable workflows. Minimize PII in logs and analytics.
Document subprocessors and data residency for customer security questionnaires.
Production scenario 16: release engineering
Trunk-based development with short-lived branches reduces merge pain. Protected main requires green CI.
Canary deploys route small traffic percentages before full rollout. Automated rollback on error budget burn.
Changelogs and migration notes are part of the release artifact — not an afterthought.
Production scenario 17: incident response
When what is jwt complete guide misbehaves in production, start with observability: logs, metrics, and the last deploy. Roll back if error rates spike beyond SLO. Capture minimal reproduction outside customer traffic.
Document timelines, impact, root cause, and preventive actions. Runbooks should link to dashboards and on-call escalation paths.
- Identify blast radius — single tenant vs global
- Communicate status page updates for customer-visible outages
- Preserve evidence before restarting containers
- Add regression tests before closing the incident
Production scenario 18: performance tuning
Profile before optimizing. Synthetic benchmarks lie when I/O, network, or database locks dominate. Use percentiles (p95, p99) rather than averages.
Cache only idempotent reads with clear TTL and invalidation. Watch memory pressure and eviction rates.
Scale horizontally only after fixing obvious single-thread bottlenecks and N+1 queries.
Production scenario 19: security review
Threat model each external input: authentication headers, query parameters, uploaded files, and webhook payloads.
Apply least privilege to service accounts and database roles. Rotate credentials on schedule and after departures.
Enable audit logs for administrative actions and failed login bursts.
Production scenario 20: team onboarding
New engineers should ship a small fix in week one using the standard local setup docs. Pair on code review conventions and testing expectations.
Maintain a glossary of domain terms and acronyms. Link to internal architecture diagrams and API catalogs.
Record short Loom walkthroughs for non-obvious workflows.
Production scenario 21: migration strategy
Break large migrations into reversible steps: expand schema, dual-write, backfill, cut over, contract old paths.
Feature flags decouple deploy from release. Dark launch new paths and compare metrics.
Never big-bang database migrations without backups and rehearsed rollback.
Production scenario 22: cost optimization
Right-size instances using utilization metrics over 30 days. Reserved capacity for steady baselines; autoscale bursty tiers.
Delete orphaned storage and idle preview environments. Tag resources by team for chargeback visibility.
Optimize egress: compress payloads, CDN cache static assets, and colocate services in the same region/AZ where possible.
Production scenario 23: compliance and data handling
Classify data: public, internal, confidential, regulated. Apply retention policies and encryption defaults per class.
Honor deletion requests with provable workflows. Minimize PII in logs and analytics.
Document subprocessors and data residency for customer security questionnaires.
Production scenario 24: release engineering
Trunk-based development with short-lived branches reduces merge pain. Protected main requires green CI.
Canary deploys route small traffic percentages before full rollout. Automated rollback on error budget burn.
Changelogs and migration notes are part of the release artifact — not an afterthought.
Production scenario 25: incident response
When what is jwt complete guide misbehaves in production, start with observability: logs, metrics, and the last deploy. Roll back if error rates spike beyond SLO. Capture minimal reproduction outside customer traffic.
Document timelines, impact, root cause, and preventive actions. Runbooks should link to dashboards and on-call escalation paths.
- Identify blast radius — single tenant vs global
- Communicate status page updates for customer-visible outages
- Preserve evidence before restarting containers
- Add regression tests before closing the incident
Production scenario 26: performance tuning
Profile before optimizing. Synthetic benchmarks lie when I/O, network, or database locks dominate. Use percentiles (p95, p99) rather than averages.
Cache only idempotent reads with clear TTL and invalidation. Watch memory pressure and eviction rates.
Scale horizontally only after fixing obvious single-thread bottlenecks and N+1 queries.
Production scenario 27: security review
Threat model each external input: authentication headers, query parameters, uploaded files, and webhook payloads.
Apply least privilege to service accounts and database roles. Rotate credentials on schedule and after departures.
Enable audit logs for administrative actions and failed login bursts.
Production scenario 28: team onboarding
New engineers should ship a small fix in week one using the standard local setup docs. Pair on code review conventions and testing expectations.
Maintain a glossary of domain terms and acronyms. Link to internal architecture diagrams and API catalogs.
Record short Loom walkthroughs for non-obvious workflows.
Try these free tools
Put what you learned into practice — no signup required.