Decode JWT Claims and Check Expiry
Decode the payload of a JSON Web Token and verify that its expiry and not-before claims are respected, without trusting the token's signature blindly.
Code
export function decodeJwt(token, now = Date.now()) {
const parts = token.split(".");
if (parts.length !== 3) throw new Error("token must have three segments");
const payload = JSON.parse(base64UrlDecode(parts[1]));
const clock = Math.floor(now / 1000);
const expired = typeof payload.exp === "number" && clock >= payload.exp;
const notYetValid = typeof payload.nbf === "number" && clock < payload.nbf;
return { payload, expired, notYetValid };
}
function base64UrlDecode(segment) {
const padded = segment.replace(/-/g, "+").replace(/_/g, "/");
return Buffer.from(padded, "base64").toString("utf8");
}What the code does
Count the functions decodeJwt and base64UrlDecode as the entire surface area of Decode JWT Claims and Check Expiry.
When the guard condition holds, Error is thrown rather than a bogus value returned.
The result comes back as an object carrying payload, expired.
What to watch for
- The guard
parts.length !== 3short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The primary signature is export function decodeJwt(token, now = Date.now()
decodeJwt is the public entry point; everything else in the file exists to support it.
The call returns payload, expired — destructure what you need at the call site.
Statements that matter
if (parts.length !== 3) throw new Error("token must have three segments");
return Buffer.from(padded, "base64").toString("utf8");
return { payload, expired, notYetValid };
Interactive Tools for This Topic
JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Does `decodeJwt` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- What happens on invalid input?
- Validation comes first — `Error` marks the failure at `parts.length !== 3`, before any partial work happens.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `decodeJwt`, `base64UrlDecode` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.