Sub topic 8
Unicode-Safe Base64 in the Browser
The previous chapter showed that btoa throws InvalidCharacterError on any character above U+00FF, and that atob returns a "binary string" rather than real text. This chapter turns those limits into a working pattern. You first encode text to UTF-8 bytes, then hand btoa a string with exactly one character per byte. Decoding runs the same steps in reverse.
This chapter assumes you already know how to:
- Use
TextEncoder.encodeandTextDecoder.decode, including thefataloption. - Read a
Uint8Arrayand usesubarray. - Describe how base64 groups 3 bytes into 4 characters.
The Core Idea: Binary Strings as a Bridge
A binary string is an ordinary JavaScript string where each UTF-16 code unit holds a value from 0 to 255, and each character stands for one byte. btoa was designed for exactly this input. It reads each character's code as a byte value and base64-encodes the resulting bytes.
The problem with btoa("€") is that € is U+20AC, a single code unit with value 8364. That value cannot be a byte, so btoa refuses it. The fix is to decide on the bytes yourself:
- Encode the text to UTF-8 with
TextEncoder.€becomes the three bytes0xE2 0x82 0xAC. - Turn each byte into a character with
String.fromCharCode. The result is"\u00E2\u0082\u00AC", three characters, all at or below U+00FF. - Pass that binary string to
btoa.
Decoding reverses the steps. atob gives a binary string, you copy each charCodeAt value into a Uint8Array, and TextDecoder turns the bytes back into text.
The bytes are the real data. The binary string is only an adapter for an API that predates Uint8Array.
The Byte-Level Helpers
Keep two layers apart. The bottom layer converts bytes to base64 and back, and it knows nothing about text. The top layer adds UTF-8. This split matters because base64 often carries data that is not text at all: image data, hashes, encryption keys.
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))); // "€"Why the Loop Uses Chunks
The obvious one-liner is String.fromCharCode(...bytes). Spread syntax passes every byte as a separate function argument, and engines cap the number of arguments a call can take. The exact cap depends on the engine and the available stack, but a few hundred thousand arguments is often enough to throw a RangeError such as "Maximum call stack size exceeded". A 1 MB file has a million bytes, so the one-liner breaks on ordinary inputs.
subarray creates a view over the same memory without copying it, so slicing into 32,768-byte chunks (0x8000) is cheap. Each fromCharCode call stays well under any engine's limit. The cost is building one string per chunk, which is negligible.
You can also convert one byte at a time:
function bytesToBase64Simple(bytes) {
let binary = "";
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}This version is correct and has no argument limit. It runs more slowly on large inputs because it makes one function call per byte, though modern engines handle repeated string concatenation well. Use either one. The chunked version is the usual default.
Why `charCodeAt` Is Safe on the Way Back
atob always returns characters in the range U+0000 to U+00FF, so charCodeAt(i) always gives a value from 0 to 255. Assigning it to a Uint8Array element stores it exactly. Do not use codePointAt or for...of here. Those work in code points, and although a binary string never contains surrogates, charCodeAt with an index loop states the one-character-per-byte intent clearly.
The Text-Level Helpers
With the byte helpers in place, text support takes one line in each direction:
function textToBase64(text) {
return bytesToBase64(new TextEncoder().encode(text));
}
function base64ToText(base64, { fatal = false } = {}) {
return new TextDecoder("utf-8", { fatal }).decode(base64ToBytes(base64));
}
// Helpers from the previous section
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 b64 = textToBase64("héllo €");
console.log(b64); // "aMOpbGxvIOKCrA=="
console.log(base64ToText(b64)); // "héllo €"Check the output against what you know. "héllo €" has 7 code units and 10 UTF-8 bytes. Ten bytes form three full 3-byte groups plus one leftover byte, so the output has 3 × 4 + 4 = 16 characters and ends in ==.
The fatal option matters when the base64 comes from outside your program. Suppose someone sends you base64 of Latin-1 or random binary data. The default decoder quietly inserts U+FFFD replacement characters. With fatal: true it throws a TypeError, so you can reject the input instead of storing corrupted text.
Gotchas When Decoding
atob uses the "forgiving base64" rules from the HTML specification. Know where it forgives and where it fails:
| Input | `atob` behavior |
|---|---|
| Missing `=` padding, such as `"aGk"` | Accepted. Returns `"hi"` |
| ASCII whitespace or newlines, such as MIME-wrapped base64 | Stripped and accepted |
| base64url characters `-` or `_` | Throws `InvalidCharacterError` |
| Length of 1 modulo 4 after removing whitespace, such as `"aGkxa"` | Throws `InvalidCharacterError` |
| A `data:` URL prefix such as `"data:image/png;base64,..."` | Throws, because `:` and `;` are not in the alphabet |
So wrap decoding of untrusted input in try/catch:
function tryBase64ToText(base64) {
try {
const binary = atob(base64);
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
return { ok: true, text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
} catch (err) {
return { ok: false, error: err.name };
}
}
console.log(tryBase64ToText("aGk")); // { ok: true, text: "hi" }
console.log(tryBase64ToText("a-b_")); // { ok: false, error: "InvalidCharacterError" }
console.log(tryBase64ToText("/w==")); // { ok: false, error: "TypeError" } (byte 0xFF is not UTF-8)These are two separate failures. InvalidCharacterError means the string is not valid base64. TypeError from the fatal decoder means the base64 was valid but its bytes are not UTF-8. Reporting them separately makes bugs easier to trace. To handle - and _, convert base64url to standard base64 first, as covered in the next chapter.
The Legacy Trick and Why to Avoid It
Older code often contains this pattern:
const legacy = btoa(unescape(encodeURIComponent("€")));
console.log(legacy); // "4oKs"
const back = decodeURIComponent(escape(atob(legacy)));
console.log(back); // "€"encodeURIComponent produces UTF-8 percent-escapes (%E2%82%AC), and unescape turns each %XX into a single character, which yields a binary string. The output is correct. Avoid it anyway: escape and unescape are deprecated legacy features, the intent is unclear to readers, and encodeURIComponent throws URIError on lone surrogates, while TextEncoder replaces them. Replace it with the helpers above when you come across it.
An Asynchronous Alternative for Large Data
For multi-megabyte payloads, the browser can do the conversion in native code. FileReader.readAsDataURL produces a data URL whose payload is base64, and fetch can decode a data URL back into bytes:
function bytesToBase64Async(bytes) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const url = reader.result;
resolve(url.slice(url.indexOf(",") + 1));
};
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(new Blob([bytes]));
});
}
async function base64ToBytesAsync(base64) {
const response = await fetch(`data:application/octet-stream;base64,${base64}`);
return new Uint8Array(await response.arrayBuffer());
}
const bytes = new TextEncoder().encode("héllo €");
bytesToBase64Async(bytes)
.then((b64) => {
console.log(b64); // "aMOpbGxvIOKCrA=="
return base64ToBytesAsync(b64);
})
.then((decoded) => console.log(new TextDecoder().decode(decoded))); // "héllo €"This approach does not block the main thread with a JavaScript loop. It is asynchronous, though, and a Content Security Policy whose connect-src excludes data: blocks the fetch decode. Use it when payloads are large and you already work with Promises.
| Approach | Sync | Handles any size | Main trade-off |
|---|---|---|---|
| Chunked `fromCharCode` + `btoa` | Yes | Yes | JavaScript loop on the main thread |
| Unchunked spread `fromCharCode(...bytes)` | Yes | No | Throws `RangeError` on large arrays |
| `unescape(encodeURIComponent())` | Yes | Text only | Deprecated, unclear, throws on lone surrogates |
| `FileReader` / `fetch` data URL | No | Yes | Async, subject to CSP |
Newer runtimes ship Uint8Array.prototype.toBase64 and Uint8Array.fromBase64, which make all of these unnecessary. A later chapter covers them along with feature detection. Until every browser you target supports them, keep the chunked helpers as your fallback.
Exercise
A colleague writes btoa(String.fromCharCode(...new TextEncoder().encode(text))). It passes every unit test but fails in production when users upload a 2 MB document. What error do they most likely see, and what change fixes it without changing the output?
Show answer
Most likely a RangeError (often "Maximum call stack size exceeded"). Spread passes about two million arguments to String.fromCharCode, which exceeds the engine's argument limit. To fix it, build the binary string in chunks with bytes.subarray(i, i + 0x8000) and concatenate the results before calling btoa. The base64 output stays identical because the binary string is the same.
Exercise
How long is the base64 output of textToBase64("€€"), and how many = padding characters does it end with? Explain using byte counts.
Show answer
Each € is 3 UTF-8 bytes, so the input is 6 bytes. That is exactly two 3-byte groups, giving 8 base64 characters with no padding ("4oKs4oKs").
Exercise
base64ToText("/w==", { fatal: true }) throws, but atob("/w==") succeeds. Which step fails, what is the error name, and why?
Show answer
atob succeeds and returns "\u00FF", the single byte 0xFF. The TextDecoder step fails with a TypeError because 0xFF is never valid in UTF-8 and fatal: true makes the decoder throw instead of producing U+FFFD.