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

snippet
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");
}