decodeBase64Url
Decodes a base64url-encoded string into its original form. Replaces base64url-safe characters with base64 ones and adds padding if needed.
1/**
2 * Decodes a base64url-encoded string into its original form.
3 * Replaces base64url-safe characters with base64 ones and adds padding if needed.
4 *
5 * @param input - The base64url-encoded string.
6 * @returns The decoded UTF-8 string.
7 */
8export function decodeBase64Url(input: string): string {
9 const base64 = input
10 .replace(/-/g, '+')
11 .replace(/_/g, '/')
12 .padEnd(Math.ceil(input.length / 4) * 4, '=');
13
14 return Buffer.from(base64, 'base64').toString('utf-8');
15}
Base64url Compatibility
Properly converts base64url format back to standard Base64, restoring original characters and padding.
Resilient Padding Handling
Automatically restores missing padding, making it tolerant of input with variable lengths.
UTF-8 Safe Decoding
Outputs decoded content in UTF-8, supporting international characters and binary-safe data.
Simple and Readable Logic
Clear substitution and padding steps make the function easy to understand, maintain, and audit.
Tests | Examples
1test('decodeBase64Url - decodes simple text', () => {
2 expect(decodeBase64Url('aGVsbG8')).toBe('hello');
3});
4
5test('decodeBase64Url - decodes text with special characters', () => {
6 expect(decodeBase64Url('aGVsbG8rd29ybGQv')).toBe('hello+world/');
7});
8
9test('decodeBase64Url - adds padding as needed', () => {
10 expect(decodeBase64Url('Zm9v')).toBe('foo'); // 'foo' is 'Zm9v'
11});
12
13test('decodeBase64Url - handles unicode characters', () => {
14 expect(decodeBase64Url('4pyTIMOgY2hlY2s')).toBe('✓ check');
15});
16
17test('decodeBase64Url - empty string', () => {
18 expect(decodeBase64Url('')).toBe('');
19});
Common Use Cases
Parsing JWT Payloads
Decode base64url-encoded sections of a JWT to inspect claims or metadata.
Reading URL Tokens
Restore URL-safe encoded tokens back to their original string representation.
Reversing Secure Identifiers
Decode identifiers used in API routes, QR codes, or query parameters.
Data Interchange with Web Services
Decode base64url data from OAuth, OpenID, or other standards-based services.
Extracting Embedded Metadata
Decode strings that store configuration or metadata in a compressed, URL-safe format.