How do you encode and decode Base64 strings safely in JavaScript including Unicode? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How do you encode and decode Base64 strings safely in JavaScript including Unicode?

message-square
0

In JavaScript, btoa() and atob() only handle Latin-1 (ISO-8859-1) byte values (0x00–0xFF) and throw an InvalidCharacterError on Unicode characters like emojis or Urdu/Arabic/CJK text. To encode and decode full UTF-8/Unicode strings safely across modern browsers and runtimes, convert strings to UTF-8 bytes with TextEncoder (or Uint8Array) before Base64 encoding, and reverse the process with TextDecoder after decoding.


1. UTF-8 Safe Encoding (encodeBase64Unicode)

Convert the string into UTF-8 bytes using TextEncoder, turn the byte array into a binary string, and pass it to btoa():

// Safely encode any Unicode / UTF-8 string to Base64
function encodeBase64Unicode(text) {
  const utf8Bytes = new TextEncoder().encode(text);
  let binaryString = "";

  for (let i = 0; i < utf8Bytes.length; i += 1) {
    binaryString += String.fromCharCode(utf8Bytes[i]);
  }

  return btoa(binaryString);
}

const sampleText = "سلام دنیا 🚀 — JavaScript UTF-8";
const encodedBase64 = encodeBase64Unicode(sampleText);

console.log("Encoded Base64:", encodedBase64);
  • new TextEncoder().encode(text): Encodes multi-byte Unicode code points into standard UTF-8 bytes without losing characters.
  • String.fromCharCode(...) + btoa(): Maps each UTF-8 byte (0–255) safely into the Latin-1 range btoa() expects.
  • Works in browsers and modern runtimes: TextEncoder, btoa(), and atob() are built into modern browsers and standard runtime environments.

2. UTF-8 Safe Decoding (decodeBase64Unicode)

Decode the Base64 string with atob(), convert each character code back into a Uint8Array of bytes, and decode UTF-8 using TextDecoder:

// Safely decode a Base64 string back into a Unicode / UTF-8 string
function decodeBase64Unicode(base64String) {
  const binaryString = atob(base64String);
  const utf8Bytes = new Uint8Array(binaryString.length);

  for (let i = 0; i < binaryString.length; i += 1) {
    utf8Bytes[i] = binaryString.charCodeAt(i);
  }

  return new TextDecoder().decode(utf8Bytes);
}

const roundTripText = decodeBase64Unicode(encodedBase64);
console.log("Decoded text:", roundTripText);
  • atob(base64String): Converts Base64 characters back into raw byte values (0–255).
  • new TextDecoder().decode(utf8Bytes): Reconstructs the original Unicode string cleanly from the UTF-8 byte sequence.
  • Full round-trip fidelity: Preserves emojis, accents, non-Latin scripts, and symbols accurately.

3. Common Traps to Avoid

Base64 is an encoding—not encryption—and Unicode handling introduces several classic mistakes:

  • Calling btoa(unicodeString) directly: Any character outside Latin-1 (U+0000–U+00FF) causes btoa() to throw a DOMException (InvalidCharacterError).
  • Using deprecated escape() / unescape() tricks: Older unescape(encodeURIComponent(str)) workarounds rely on deprecated functions and are less explicit than TextEncoder and TextDecoder.
  • Treating Base64 as security or encryption: Base64 only changes representation and is easily decoded by anyone; never use it alone to hide secrets, passwords, or sensitive data.

TL;DR: Pair TextEncoder + btoa() to encode Unicode strings into Base64, and atob() + TextDecoder to decode Base64 back into Unicode text without InvalidCharacterError.

Are you encoding/decoding text payloads in the browser, handling URL-safe Base64 variants, or working with binary data like files or ArrayBuffer?