A JWT can be easy to decode and still unsafe to trust. This JavaScript JWT guide shows how to inspect token anatomy, validate signatures and claims, design a refresh flow, and debug authentication without exposing credentials.
Overview
JSON Web Tokens (JWTs) are compact, URL-safe strings commonly used to carry claims between an identity provider, an API, and a JavaScript application. A typical signed JWT contains three Base64URL-encoded parts separated by periods:
header.payload.signature
| Part | What it contains | What it proves |
|---|---|---|
| Header | Metadata such as the token type and signing algorithm identifier | Nothing by itself; it is untrusted input until the token is verified |
| Payload | Claims such as subject, issuer, audience, expiration, and issued-at time | Nothing by itself; decoding is not validation |
| Signature | A cryptographic value calculated over the encoded header and payload | Integrity and authenticity only when checked with the expected key and algorithm |
The most important distinction is between decoding and validation. A JWT decoder can display a payload without possessing a secret or public key. That makes decoding useful for troubleshooting, but it does not make the claims reliable. An API must verify the signature and enforce the claims that matter to that API.
Keep responsibilities separate. A browser can inspect a token to decide whether to update its user interface, but the server must authorize requests. Never treat a decoded browser payload as permission to access data.
Checklist by scenario
When decoding a JWT in JavaScript
- Confirm that the value has the expected three-part structure before parsing it.
- Decode only for inspection, logging a redacted result rather than the original token.
- Remember that Base64URL decoding is not cryptographic verification.
- Do not place decoded claims into authorization decisions in frontend code.
A small inspection helper can make development diagnostics clearer. It deliberately does not verify the token:
function decodeJwtForInspection(token) {
const parts = token.split('.');
if (parts.length !== 3) {
throw new Error('Expected a JWT with three parts');
}
const decodePart = (value) => {
const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
return JSON.parse(atob(padded));
};
return {
header: decodePart(parts[0]),
payload: decodePart(parts[1])
};
}
This browser-oriented example may need a different Base64URL implementation in Node.js, depending on the runtime. It also assumes the decoded bytes represent JSON. Treat malformed input as expected input, not as a reason to bypass checks.
When validating a token on an API
- Obtain verification keys through the identity provider's documented configuration or a securely managed key source.
- Restrict accepted algorithms to the algorithms your service is configured to use; do not blindly trust the header's algorithm value.
- Verify the signature before using identity claims.
- Check expiration and, where applicable, not-before, issuer, audience, and subject claims.
- Return a generic authentication failure to the client and keep detailed verification errors in protected server logs.
For a Node.js API, a JOSE-compatible library is generally safer than implementing cryptographic verification manually. The exact API varies by package and version, so consult the installed library's documentation and pin changes through your normal dependency review process. A representative pattern using the jose package looks like this:
import { jwtVerify, createRemoteJWKSet } from 'jose';
const jwks = createRemoteJWKSet(new URL(process.env.JWKS_URL));
export async function verifyAccessToken(token) {
const result = await jwtVerify(token, jwks, {
issuer: process.env.JWT_ISSUER,
audience: process.env.JWT_AUDIENCE,
// Use the algorithm configured by your identity provider.
algorithms: ['RS256']
});
return result.payload;
}
Treat the algorithm in this snippet as an example, not a universal default. Your provider may use a different algorithm or key arrangement. The important practice is to configure an explicit, expected algorithm and validate issuer and audience according to your application contract.
When implementing access and refresh tokens
A common flow separates a short-lived access token from a longer-lived refresh credential:
Sign in → receive credentials → call API with access token → access token expires → send refresh credential → receive new access token → retry the original request once.
Use a refresh credential only with the refresh endpoint. The refresh endpoint should validate it, apply the provider's rotation or revocation rules, and issue a new access token according to the configured policy. Do not refresh indefinitely in a client-side loop.
For browser applications, evaluate storage and transport together. An HttpOnly, Secure cookie can prevent ordinary JavaScript from reading a refresh credential, while a cookie-based design requires appropriate cross-site request protections and carefully chosen cookie settings. Storing long-lived credentials in localStorage makes them readable by JavaScript and therefore increases the impact of a successful script-injection attack. There is no storage choice that removes the need for XSS prevention, origin controls, and server-side authorization.
When a refresh request fails, clear the local authentication state and direct the user through the sign-in path. Avoid retrying a failed refresh request with the same credential.
What to double-check
Claims and time handling
Compare timestamps consistently. JWT registered time claims are normally expressed as seconds since the Unix epoch, while JavaScript dates use milliseconds. A safe expiration check must account for that difference:
function isExpired(payload, clockSkewSeconds = 30) {
if (typeof payload.exp !== 'number') return true;
const nowSeconds = Math.floor(Date.now() / 1000);
return payload.exp <= nowSeconds - clockSkewSeconds;
}
Clock skew should be a deliberate, small tolerance agreed by the systems involved, not a way to make substantially expired tokens acceptable. If tokens fail only on some machines, compare server time, container time, and identity-provider time before changing expiration logic.
Check the difference between:
- Issuer: the authority that created the token.
- Audience: the API or service the token is intended for.
- Subject: the identity represented by the token.
- Expiration: the latest accepted time.
- Not-before: the earliest accepted time, when supplied.
Key rotation and provider configuration
When an identity provider rotates signing keys, a verifier that caches keys too aggressively can reject newly issued tokens. A verifier that accepts arbitrary keys or algorithms creates a different security problem. Confirm how the selected library refreshes key metadata, how failures are surfaced, and how your deployment handles a temporary key endpoint outage. Test rotation in a non-production environment before changing production configuration.
Browser, server, and log boundaries
- Validate authorization at the API boundary, even if the frontend hides controls for unauthorized users.
- Keep signing secrets and private keys out of browser bundles, public environment variables, and client repositories.
- Redact bearer tokens, cookies, authorization headers, and refresh responses from logs, screenshots, issue trackers, and analytics.
- Use HTTPS for token transport and review cross-origin settings as part of the authentication design.
Common mistakes
- Using a JWT decoder as a validator. A decoded
roleclaim is still user-controlled until signature and claim checks succeed on the server. - Accepting whatever algorithm the header specifies. Configure the allowed algorithm and key type in the verifier.
- Checking only the expiration claim. An unexpired token issued for another service or issuer should not automatically be accepted.
- Putting secrets in frontend environment variables. Many build systems embed client-exposed variables into downloadable JavaScript. Treat anything shipped to the browser as public configuration.
- Retrying every 401 response automatically. One request may trigger a refresh, but refresh failures and repeated 401 responses need a terminal path.
- Logging the complete Authorization header. A debugging log can become a credential leak. Log a request identifier, status, issuer configuration, and redacted error category instead.
- Assuming token storage solves XSS or CSRF. Storage, cookie attributes, content security, input handling, and request protections address different risks.
- Copying library examples without checking versions. Review package documentation, security advisories, supported runtime versions, and key-loading behavior before upgrading an authentication dependency. The NPM package evaluation checklist and dependency upgrade workflow can help structure that review.
For storage trade-offs, compare cookies, Web Storage, and other browser mechanisms in the browser storage guide. Keep environment configuration separate from credentials by using the practices in the JavaScript environment variables guide.
When to revisit
Authentication code should be reviewed whenever its surrounding inputs change, not only when a login bug appears. Revisit this checklist:
- Before a seasonal planning or security review cycle.
- When changing identity providers, audiences, issuers, signing algorithms, or key endpoints.
- When adding a new browser client, API, mobile client, or server-side rendering path.
- When changing token storage, cookie settings, cross-origin configuration, or refresh behavior.
- When upgrading the JWT, JOSE, HTTP, framework, or runtime packages involved in verification.
- After a security advisory, suspected token exposure, unusual refresh volume, or repeated clock-related failures.
Use this practical review sequence: document which component issues each token; write down the expected issuer, audience, algorithm, key source, and lifetime; test valid, expired, malformed, wrong-audience, wrong-issuer, and wrong-signature tokens; test refresh success, refresh failure, and concurrent requests; then inspect logs to confirm that credentials are absent. Record the library versions and provider settings alongside the test results. This gives the next developer a reproducible implementation guide instead of a collection of assumptions.