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

typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
javascript
const express = require('express');
const router = express.Router();
const { pool } = require('../db');
const redis = require('../redis');

Building a health check endpoint in Express

health-check timeouts promise-race
Intermediate 9 steps
rust
use std::cmp::Ordering;
use std::str::FromStr;
 
#[derive(Debug, Clone, PartialEq, Eq)]

Parsing and ordering semantic versions in Rust

parsing trait-implementation ordering
Intermediate 8 steps
javascript
'use client';
 
import { useEffect } from 'react';
import * as Sentry from '@sentry/nextjs';

How a Next.js error boundary recovers

error-boundary error-handling observability
Intermediate 8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps
ruby
class ApacheLogParser
  LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/
 
  TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"

Parsing Apache logs with named captures

regex named-captures parsing
Intermediate 6 steps

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