decodeBase64
Decodes a Base64-encoded string.
1/**
2 * Decodes a Base64-encoded string.
3 *
4 * @param base64 - The Base64 string to decode.
5 * @returns The decoded string.
6 */
7export function decodeBase64(base64: string): string {
8 if (typeof window !== 'undefined' && typeof atob === 'function') {
9 return decodeURIComponent(escape(atob(base64)));
10 }
11
12 return Buffer.from(base64, 'base64').toString('utf-8');
13}
Environment-Aware Logic
Detects whether it’s running in a browser or Node.js and uses the appropriate decoding mechanism accordingly.
Unicode Compatibility
Handles multi-byte characters safely using
escape
anddecodeURIComponent
to reconstruct original text correctly in the browser.Failsafe Decoding
Uses only native APIs (
atob
,Buffer
), reducing the chance of decoding inconsistencies across platforms.Lightweight and Dependency-Free
Avoids any third-party libraries while supporting full Base64 decoding functionality.
Tests | Examples
1test('decodeBase64 - decodes plain ASCII text', () => {
2 expect(decodeBase64('SGVsbG8=')).toBe('Hello');
3});
4
5test('decodeBase64 - decodes empty string', () => {
6 expect(decodeBase64('')).toBe('');
7});
8
9test('decodeBase64 - decodes Unicode characters', () => {
10 expect(decodeBase64('0J/RgNC40LLQtdGC')).toBe('Привет');
11});
12
13test('decodeBase64 - decodes emojis', () => {
14 expect(decodeBase64('8J+SqfCfkbE=')).toBe('💡🔥');
15});
Common Use Cases
Parsing Encoded Payloads
Decode Base64 strings from APIs, JWT tokens, or embedded configuration blobs.
User Input Handling
Decode Base64-encoded data submitted through forms or query parameters.
Data Restoration
Convert previously encoded text or files (e.g., images or documents) back into their usable form.
Debugging and Development
Inspect and test Base64-encoded content quickly in development tools or scripts.