Course contentsShow
← JavaScript
Lesson 2356 of 2,72348. Working with Binary DataFree lesson

Encoding Unicode Strings Safely

Work around btoa()'s ASCII-only limitation by combining it with encodeURIComponent or TextEncoder for Unicode text.

Encoding Unicode Strings Safely

You'll learn how to properly encode Unicode text to Base64 by working around btoa()'s ASCII-only limitation.

The btoa() function has a critical flaw: it only works with ASCII characters (0-127). If you try to pass Unicode strings containing emoji, accented characters, or non-Latin scripts, it throws an error. This happens because btoa() expects each character to fit in a single byte, but Unicode characters often don't.

The Problem

Think of btoa() as a narrow doorway built for small packages. Unicode characters are like oversized boxes that won't fit through. When you try to force them, everything breaks.

btoa("Hello"); // ✓ Works: "SGVsbG8="
btoa("Hello 🌍"); // ✗ Error: "The string contains characters outside of the Latin1 range"

Two Solutions

Solution 1: Using encodeURIComponent()

Convert your Unicode string into percent-encoded ASCII first, then apply btoa():

const unicodeStr = "Hello 🌍";
const encoded = btoa(encodeURIComponent(unicodeStr));
// "SGVsbG8lMjAlRjAlOUYlOEMlOEQ="

// To decode:
const decoded = decodeURIComponent(atob(encoded));
// "Hello 🌍"

Solution 2: Using TextEncoder

Convert your string to UTF-8 bytes, then manually convert those bytes to a Base64-compatible string:

const encoder = new TextEncoder();
const bytes = encoder.encode("Hello 🌍");
const binaryString = String.fromCharCode(...bytes);
const encoded = btoa(binaryString);

Both approaches expand Unicode characters into a form btoa() can handle—like disassembling your oversized box into smaller pieces that fit through the doorway.

Key Takeaway: Always encode Unicode strings through encodeURIComponent() or TextEncoder before using btoa() to avoid errors with non-ASCII characters.