JWT Verify Expiry And Custom Claims
Parse and verify a JWT signature expiry and custom claims with explicit clock tolerance and audience validation.
Code
export async function verifyJWT(token,{secret,tolerance=0,audience}={}){const[header,payload,sig]=token.split('.');const enc=new TextEncoder();const keyObj=await crypto.subtle.importKey('raw',enc.encode(secret),{name:'HMAC',hash:'SHA-256'},false,['verify']);const valid=await crypto.subtle.verify('HMAC',keyObj,base64urlDecode(sig),enc.encode(header+'.'+payload));if(!valid)throw new Error('invalid signature');const claims=JSON.parse(new TextDecoder().decode(base64urlDecode(payload)));const now=Math.floor(Date.now()/1000);if(claims.exp!==undefined&&now>claims.exp+tolerance)throw new Error('token expired');if(audience&&claims.aud!==audience)throw new Error('audience mismatch');return claims;}function base64urlDecode(s){const b64=s.replace(/-/g,'+').replace(/_/g,'/')+'==='.slice(0,(4-s.length%4)%4);return Uint8Array.from(atob(b64),c=>c.charCodeAt(0));}What the code does
JWT Verify Expiry And Custom Claims is built around the functions verifyJWT and base64urlDecode.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Failure is loud: Error aborts the current operation instead of degrading it.
Caveats
cryptoexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
!validshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
Signature: export async function verifyJWT(token,{secret,tolerance=0,audience}={})
verifyJWT is what another module would consume; nothing else here is load-bearing for callers.
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 the code validate its input?
- It throws `Error` before any real work runs, via the guard `!valid` — handle it at the call site or let it propagate deliberately.
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `verifyJWT`, `base64urlDecode` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.