javascript 27 lines · 6 steps

Decoding a JWT payload in JavaScript

How to split a JWT, base64url-decode its middle segment, and validate expiry without a library.

Explained by highlit
1function parseJwtPayload(token) {
2 const parts = token.split('.');
3 if (parts.length !== 3) {
4 throw new Error('Invalid JWT: expected 3 segments');
5 }
6 
7 const payload = base64UrlDecode(parts[1]);
8 const claims = JSON.parse(payload);
9 
10 if (claims.exp && Date.now() >= claims.exp * 1000) {
11 throw new Error('Token expired');
12 }
13 
14 return claims;
15}
16 
17function base64UrlDecode(segment) {
18 let base64 = segment.replace(/-/g, '+').replace(/_/g, '/');
19 const padding = base64.length % 4;
20 if (padding) {
21 base64 += '='.repeat(4 - padding);
22 }
23 
24 const binary = atob(base64);
25 const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
26 return new TextDecoder('utf-8').decode(bytes);
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A JWT is just three base64url-encoded segments joined by dots, so parsing starts with a split and a length check.
  2. 2Base64url differs from standard base64 by swapping two characters and dropping padding, both of which must be reversed before decoding.
  3. 3Client-side expiry checks catch obviously stale tokens but never replace server-side signature verification.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Decoding a JWT payload in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code