Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

atobSafe

Safely decodes a base64-encoded string. Handles Unicode properly using TextDecoder.

TypeScript
Copied!
1/**
2 * Safely decodes a base64-encoded string.
3 * Handles Unicode properly using TextDecoder.
4 *
5 * @param str - Base64-encoded input string.
6 * @returns Decoded string or null if decoding fails.
7 */
8export function atobSafe(str: string): string | null {
9  try {
10    const binary = atob(str);
11    const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
12    return new TextDecoder().decode(bytes);
13  } catch {
14    return null;
15  }
16}
  • Unicode Compatibility

    Utilizes TextDecoder to correctly reconstruct multibyte Unicode strings, avoiding common issues with non-ASCII content.

  • Robust Error Handling

    Catches malformed base64 input and returns null, preventing runtime exceptions and simplifying consumer logic.

  • Byte-Safe Decoding

    Converts binary data to Uint8Array, preserving exact byte values for accurate decoding.

  • Minimal and Dependency-Free

    Relies only on native Web APIs (atob, TextDecoder), ensuring lightweight and fast execution.

Tests | Examples

TypeScript
Copied!
1test('atobSafe - decodes ASCII string', () => {
2  expect(atobSafe('SGVsbG8=')).toBe('Hello');
3});
4
5test('atobSafe - decodes Unicode string', () => {
6  expect(atobSafe('0J/RgNC40LLQtdGC')).toBe('Привет');
7});
8
9test('atobSafe - decodes emojis', () => {
10  expect(atobSafe('8J+SqfCfkb0=')).toBe('🔥🚀');
11});
12
13test('atobSafe - empty string', () => {
14  expect(atobSafe('')).toBe('');
15});
16
17test('atobSafe - returns null for invalid input', () => {
18  expect(atobSafe('invalid@@base64')).toBeNull();
19});

Common Use Cases

  • Reading Base64-Encoded Payloads

    Decode encoded content received from APIs, WebSockets, or embedded in QR codes.

  • Decoding User-Generated Data

    Safely parse stored strings from localStorage, sessionStorage, or cookies.

  • File Restoration

    Convert base64-encoded file content (e.g., CSV, text, JSON) back into usable form.

  • JWT or Token Inspection

    Decode parts of JSON Web Tokens (JWTs) to inspect payloads without triggering errors.

  • Fallback Handling for Low-Trust Input

    Gracefully handle potentially invalid or corrupted base64 input from user or third-party sources.

Codebase: Utilities -> Encoding -> atobSafe | Yevhen Klymentiev