Sub topic 7
btoa and atob, and Why They Reject Unicode
This chapter assumes you know the earlier material. JavaScript strings are sequences of UTF-16 code units. UTF-8 encodes code points as one to four bytes. Base64 maps each group of 3 bytes to 4 characters and pads incomplete groups with =. You should also be able to run snippets in a browser console or a recent Node.js version, which has btoa and atob as globals.
btoa and atob are the oldest base64 functions on the web platform. Nearly every runtime has them, and they are short to call. They work on bytes, but they represent those bytes in a string type that holds text. That design is the source of most base64 bugs in JavaScript. This chapter explains what the two functions accept and return, why btoa throws on characters like €, and why it can also give a wrong answer without throwing.
What btoa and atob actually do
The names come from Unix tradition: "binary to ASCII" and "ASCII to binary." Read "binary" as binary string. A binary string is an ordinary JavaScript string in which each character stands for one byte. The character's code unit value, from 0 to 255, is the byte value.
| Function | Input | Output |
|---|---|---|
| `btoa(data)` | A binary string: every code unit in the range U+0000 to U+00FF | A base64 string |
| `atob(data)` | A base64 string | A binary string: every code unit in the range U+0000 to U+00FF |
Neither function knows about UTF-8, and neither function knows about text. btoa takes each code unit, treats its value as a byte, and base64-encodes the resulting byte sequence. atob does the reverse and turns each decoded byte into a character with the same code.
console.log(btoa("hi")); // "aGk="
console.log(atob("aGk=")); // "hi"
// A binary string can hold any byte value, including non-printable ones
const binary = String.fromCharCode(0x00, 0x7f, 0xff);
console.log(btoa(binary)); // "AH//"
console.log([...atob("AH//")].map((c) => c.charCodeAt(0))); // [0, 127, 255]The last line shows the reliable way to inspect atob output. Do not print the string itself. Read each character's code instead, because those codes are the bytes.
Why btoa throws on Unicode
A byte holds values from 0 to 255. If btoa meets a code unit above 0xFF, it cannot represent that code unit as one byte. It does not try to pick an encoding for you. It throws a DOMException whose name is "InvalidCharacterError".
for (const input of ["€", "日本", "😀", "a\uD800"]) {
try {
btoa(input);
} catch (err) {
console.log(input.length, err.name); // each logs "InvalidCharacterError"
}
}Each input fails for the same reason:
€is U+20AC, one code unit with value 0x20AC.日本contains code units 0x65E5 and 0x672C.😀is U+1F600. It is stored as the surrogate pair 0xD83D 0xDE00, and both units are above 0xFF."a\uD800"contains a lone surrogate with value 0xD800.btoachecks code unit values, not well-formedness, so it rejects this the same way.
The diagram also shows that btoa converts its argument to a string first. This produces some surprising results:
console.log(btoa(123)); // "MTIz" (encodes the string "123")
console.log(btoa(null)); // "bnVsbA==" (encodes "null")
console.log(btoa(undefined)); // "dW5kZWZpbmVk" (encodes "undefined")
console.log(btoa([1, 2, 3])); // "MSwyLDM=" (encodes "1,2,3")Passing a Uint8Array to btoa is a common mistake. The array becomes a comma-separated list of numbers, and that list is what gets encoded. The call succeeds, and the output is useless.
The quieter failure: Latin-1 characters encode wrong
The thrown error is the visible problem. A worse one gets no error at all. Characters from U+0080 to U+00FF, such as é, ü, ñ, £, and ©, pass the range check. btoa encodes each of them as one byte, the character's Latin-1 value. Almost every other system expects UTF-8, which encodes these characters as two bytes.
// What btoa produces: the single Latin-1 byte 0xE9
console.log(btoa("é")); // "6Q=="
// What UTF-8 needs: the two bytes 0xC3 0xA9
const utf8Binary = String.fromCharCode(0xc3, 0xa9);
console.log(btoa(utf8Binary)); // "w6k="If you send "6Q==" to a server that decodes base64 and then reads the bytes as UTF-8, the server gets the single byte 0xE9. That byte is not valid UTF-8 by itself. The server either rejects the data or shows U+FFFD, the replacement character. Your tests may still pass if they only round-trip through btoa and atob in the same program, because both sides make the same Latin-1 assumption.
The mirror problem in atob: mojibake
atob has the opposite problem. Suppose some other system encoded UTF-8 text as base64. atob returns one character per byte, so a multi-byte UTF-8 sequence turns into several Latin-1 characters. The garbled result is called mojibake.
console.log(atob("w6k=")); // "é" (should be "é")
console.log(atob("4oKs")); // "â\u0082¬" (should be "€")atob did its job correctly here. The bytes 0xC3 0xA9 came back as the code units 0xC3 and 0xA9. The mistake is reading that binary string as if it were text. To recover é, you have to copy the code units into a Uint8Array and decode the bytes as UTF-8 with TextDecoder. The next chapter builds that bridge in full.
How forgiving atob is
atob uses a "forgiving" base64 decoder defined in the HTML standard. The rules decide which inputs decode and which throw InvalidCharacterError:
- All ASCII whitespace (spaces, tabs, line feeds, form feeds, carriage returns) is removed first, wherever it appears.
- If the remaining length is a multiple of 4, up to two trailing
=characters are removed. - If the length is now 1 more than a multiple of 4, decoding fails, because one character carries only 6 bits and cannot make a byte.
- If any character outside
A–Z,a–z,0–9,+, and/remains, decoding fails. - Leftover bits that do not fill a whole byte are discarded.
const attempts = ["aGk=", "aGk", " aG\nk= ", "aGk-", "aGk_", "a", "aGk=="];
for (const s of attempts) {
try {
console.log(JSON.stringify(s), "->", JSON.stringify(atob(s)));
} catch (err) {
console.log(JSON.stringify(s), "->", err.name);
}
}
// "aGk=" -> "hi"
// "aGk" -> "hi" (missing padding is accepted)
// " aG\nk= " -> "hi" (whitespace is stripped)
// "aGk-" -> InvalidCharacterError (base64url character)
// "aGk_" -> InvalidCharacterError (base64url character)
// "a" -> InvalidCharacterError (length 1 mod 4)
// "aGk==" -> InvalidCharacterError (too much padding)This gives you two practical consequences:
- Missing padding is fine for
atob. Other decoders, including many server libraries, are strict about padding. A string thatatobaccepts may still be rejected elsewhere. - base64url input throws. Tokens such as JWT segments use
-and_. You must map those characters back to+and/before callingatob. A later chapter covers base64url.
Because step 5 drops leftover bits, different inputs can decode to the same bytes. atob("aGk") and atob("aGl") both return "hi". Do not use a btoa/atob round trip to check whether a base64 string is canonical.
Detecting safe input before calling btoa
If you must call btoa on a string, for example in legacy code you cannot change yet, you can check whether the call will succeed:
function isBinaryString(str) {
return /^[\x00-\xFF]*$/.test(str);
}
console.log(isBinaryString("hi")); // true
console.log(isBinaryString("é")); // true (safe to call, but Latin-1, not UTF-8)
console.log(isBinaryString("€")); // false (btoa would throw)This check only tells you whether btoa will throw. It does not tell you whether the output is what you want. A true result for real text that contains characters from U+0080 to U+00FF still means a Latin-1 encoding.
The legacy workaround and why to avoid it
Older code often contains this one-liner:
// Legacy pattern: works, but relies on deprecated functions
const legacy = btoa(unescape(encodeURIComponent("€")));
console.log(legacy); // "4oKs"
const back = decodeURIComponent(escape(atob(legacy)));
console.log(back); // "€"encodeURIComponent produces percent-escaped UTF-8 bytes. unescape then turns each %XX into one character with that code, which builds a UTF-8 binary string. The result is correct, but escape and unescape are deprecated legacy features listed in Annex B of the ECMAScript specification. The pattern hides the byte step inside URL-encoding functions, and encodeURIComponent throws URIError on lone surrogates. When you meet this pattern, replace it with the TextEncoder-based approach from the next chapter.
Summary of failure modes
| Situation | What happens | Error? |
|---|---|---|
| `btoa` with a code unit above 0xFF (`€`, CJK, emoji, lone surrogate) | Throws | `InvalidCharacterError` |
| `btoa` with U+0080 to U+00FF (`é`, `£`) | Encodes Latin-1 bytes, not UTF-8 | None, wrong output |
| `btoa` with a `Uint8Array`, number, or `null` | Encodes the value's string form | None, wrong output |
| `atob` on base64 of UTF-8 text | Returns mojibake binary string | None, needs decoding |
| `atob` with `-` or `_` | Throws | `InvalidCharacterError` |
| `atob` with missing padding or whitespace | Decodes normally | None |
Exercise
A form sends btoa(name) to an API that decodes base64 and reads the bytes as UTF-8. Users named "Zoë" see their name shown as "Zo\uFFFD", and users named "Zoë 😀" get an error in the browser. Explain both symptoms.
Show answer
"ë" is U+00EB, inside btoa's 0x00–0xFF range, so btoa encodes it as the single Latin-1 byte 0xEB with no error. That byte alone is not valid UTF-8, so the server's decoder replaces it with U+FFFD. The emoji is a surrogate pair whose code units (0xD83D, 0xDE00) are above 0xFF, so btoa throws InvalidCharacterError in the browser before anything is sent.
Exercise
Predict the result of each call: btoa(new Uint8Array([104, 105])), atob("aGk"), atob("aGk-"), and [...atob("w6k=")].map(c => c.charCodeAt(0)).
Show answer
btoa(new Uint8Array([104, 105])) encodes the string "104,105" and returns "MTA0LDEwNQ==", not "aGk=". atob("aGk") returns "hi" because missing padding is accepted. atob("aGk-") throws InvalidCharacterError because "-" is not in the standard alphabet. The last expression returns [195, 169], the UTF-8 bytes of "é", which must be passed through TextDecoder to get the text back.
Exercise
Write a function safeBtoa(str) that returns btoa(str) when every code unit is in the range 0 to 255 and otherwise throws a RangeError naming the first offending index. Why does a successful call still not guarantee UTF-8 output?
Show answer
function safeBtoa(str) { for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 0xff) { throw new RangeError("Code unit above 0xFF at index " + i); } } return btoa(str); } A successful call only proves that each code unit fits in one byte. Characters from U+0080 to U+00FF are still written as single Latin-1 bytes, while UTF-8 needs two bytes for each of them, so the output is UTF-8 only when the input is pure ASCII or is already a UTF-8 binary string.