Sub topic 8
Unicode-Safe Base64 in the Browser
This chapter assumes you already know three things. TextEncoder turns a string into UTF-8 bytes in a Uint8Array. TextDecoder turns those bytes back into a string. And btoa throws InvalidCharacterError on any character above U+00FF. Here you combine these pieces so that any Unicode text can be converted to base64 and back.
The idea: give btoa bytes, not text
btoa was designed for "binary strings." A binary string is a string in which every character has a code from 0 to 255, so each character stands for one byte. If you hand btoa real Unicode text, a character like € (U+20AC) is outside that range and the call fails.
The fix is to never give btoa the original text. Use this order instead:
- Encode the text to UTF-8 bytes with
TextEncoder. - Turn each byte into one character with the same code, which gives a binary string.
- Pass that binary string to
btoa.
Decoding runs the same steps backward: atob returns a binary string, you copy each character code into a Uint8Array, and TextDecoder turns the bytes back into text.
The helper functions
function bytesToBase64(bytes) {
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
const encoded = bytesToBase64(new TextEncoder().encode("€"));
console.log(encoded); // "4oKs"
console.log(new TextDecoder().decode(base64ToBytes(encoded))); // "€"Some details in this code matter:
- The helpers work on bytes, not strings. They work for any binary data, such as image bytes or a hash digest, as well as for encoded text. Keep the text conversion separate in
TextEncoderandTextDecoder. - Chunking.
String.fromCharCode(...bytes)passes every byte as a separate function argument. Engines limit how many arguments one call can take, and a multi-megabyte array throws aRangeError. Slicing into 32,768-byte pieces withsubarraystays under that limit.subarraycreates a view on the same memory without copying it. - No surprises from
atoboutput. Each character thatatobreturns has a code from 0 to 255, socharCodeAtalways fits in aUint8Arrayslot.
For convenience, you can wrap the full text round trip:
const textToBase64 = (text) => bytesToBase64(new TextEncoder().encode(text));
const base64ToText = (b64) => new TextDecoder().decode(base64ToBytes(b64));
const b64 = textToBase64("héllo €");
console.log(base64ToText(b64) === "héllo €"); // trueCommon errors
| Mistake | Symptom | Fix |
|---|---|---|
| `btoa(text)` on Unicode input | `InvalidCharacterError` | Encode to bytes first |
| `btoa(unescape(encodeURIComponent(text)))` | Works, but depends on the deprecated `unescape` | Use `TextEncoder` |
| Spreading a huge array into `fromCharCode` | `RangeError` | Convert in chunks |
| Decoding `atob` output directly as text | Mojibake such as `€` | Rebuild the bytes, then use `TextDecoder` |
Exercise
Why does bytesToBase64 never throw InvalidCharacterError, even for emoji input?
Show answer
It only passes btoa characters created by String.fromCharCode from Uint8Array values, and those are always in the range 0 to 255. The emoji was already turned into UTF-8 bytes by TextEncoder before btoa sees anything.
Exercise
"héllo €" encodes to 10 UTF-8 bytes. How many characters does textToBase64 return, and how many of them are "=" padding?
Show answer
16 characters. Base64 writes 4 characters for each group of 3 bytes, rounded up: ceil(10 / 3) = 4 groups, and 4 × 4 = 16. The last group holds only 1 byte, so it ends in two "=" characters.