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.

JavascriptAuth Jwt

Code

javascriptsnippet
14 lines
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 !== 3 short-circuits the flow with an early throw when 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

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.