To Base64 encode Unicode text in JavaScript, first turn the string into UTF-8 bytes with TextEncoder, then turn those bytes into a one-byte-per-character string and pass it to btoa. Calling btoa directly on emoji or other non-Latin text throws an InvalidCharacterError. In Node.js, Buffer.from(text).toString('base64') does it in one line.
Why btoa can't base64 encode Unicode text in JavaScript
btoa cannot encode Unicode because it only accepts characters that fit in a single byte. MDN's btoa page says "each character must have a code point less than 256", and anything above 0xff throws.
JavaScript strings are UTF-16, as web.dev's guide to Base64 strings explains, and btoa reads each UTF-16 code unit as if it were a byte. Fine for ASCII. It breaks on the cheese emoji 🧀 (U+1F9C0), which UTF-16 stores as a surrogate pair.
Here is the error in Node for a string with an accent and an emoji:
btoa('café 🧀');
// Uncaught DOMException [InvalidCharacterError]: Invalid character
The silent Latin-1 trap
btoa does not always fail on non-ASCII text. é fits in one byte, so btoa('café') succeeds and returns the wrong bytes.
| Input | Method | Output |
|---|---|---|
café |
btoa('café') |
Y2Fm6Q== (Latin-1) |
café |
UTF-8 bytes, then btoa |
Y2Fmw6k= (UTF-8) |
A server or another language that decodes the first string as UTF-8 gets an invalid byte. In my test, a strict TextDecoder with fatal: true threw "The encoded data was not valid for encoding utf-8". A non-strict decoder shows a replacement character instead of é. The bug only appears when someone types an accented name, so English sample data never catches it.
How to Base64 encode Unicode text with TextEncoder
In the browser it takes three steps: encode to UTF-8, map bytes to characters, then call btoa. MDN's TextEncoder page confirms that its encoding "Always returns utf-8", so there is no charset to get wrong.
function utf8ToBase64(text) {
const bytes = new TextEncoder().encode(text); // UTF-8 bytes
let binary = '';
for (let i = 0; i < bytes.length; i += 0x8000) {
// chunks keep the argument count below the engine's limit
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
}
return btoa(binary);
}
utf8ToBase64('café 🧀'); // "Y2Fmw6kg8J+ngA=="
utf8ToBase64('👨👩👧'); // "8J+RqOKAjfCfkanigI3wn5Gn"
The string 'café 🧀' has a length of 7 in JavaScript but becomes 10 UTF-8 bytes. The family emoji is bigger still: a length of 8 and 18 bytes, because it is three emoji joined by invisible joiner characters.
Why the loop and not a spread
Many tutorials, including the web.dev article, write String.fromCodePoint(...bytes). Spreading passes every byte as its own argument, and engines cap argument counts. In my test on Node v24.15.0, the spread form worked for 100,000 bytes and threw RangeError: Maximum call stack size exceeded at 200,000 bytes. The chunked loop round-tripped "🧀é" repeated 300,000 times without trouble.
MDN's own helper avoids the problem a different way, with Array.from(bytes, (byte) => String.fromCodePoint(byte)).join(''), which also works.
How to decode the Base64 back to Unicode
Decoding reverses the steps: atob returns one character per byte, you collect those bytes, and TextDecoder reads them as UTF-8.
function base64ToUtf8(base64) {
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
base64ToUtf8('Y2Fmw6kg8J+ngA=='); // "café 🧀"
If you skip TextDecoder and use the atob result directly, you get mojibake such as café. If atob itself throws, the input is not clean Base64; see why atob says the string is not correctly encoded.
Method comparison, tested on the same string
The three methods I could run give the same Base64 for well-formed text. I ran them on 'hello⛳❤🧀' in Node v24.15.0:
| Method | Where it runs | Output | Status |
|---|---|---|---|
TextEncoder + btoa |
Browsers, Node, Deno | aGVsbG/im7PinaTwn6eA |
Recommended |
btoa(unescape(encodeURIComponent(s))) |
Browsers, Node | aGVsbG/im7PinaTwn6eA |
Deprecated |
Buffer.from(s).toString('base64') |
Node only | aGVsbG/im7PinaTwn6eA |
Fine in Node |
bytes.toBase64() |
Newer browsers | Not tested | Missing in my Node build |
The old unescape trick
btoa(unescape(encodeURIComponent(text))) still works, and older code is full of it. encodeURIComponent produces UTF-8 percent escapes, and unescape turns each escape into a one-byte character. The problem is unescape itself: MDN's unescape page says "Deprecated. Avoid using this feature in new projects."
Node.js Buffer
In Node, skip btoa entirely. The Node.js Buffer docs say UTF-8 is the default encoding, so Buffer.from('café 🧀').toString('base64') is enough. Use 'base64url' for tokens and URLs: it gave Y2Fmw6kg8J-ngA, with - instead of + and no padding. Avoid 'latin1' for text, because the same page warns that characters outside its range "are truncated".
Uint8Array.prototype.toBase64
toBase64() encodes a Uint8Array straight to Base64 with no binary string in between. MDN's toBase64 page lists an alphabet option ("base64" or "base64url") and omitPadding, and marks it Baseline 2025: "Since September 2025, this feature works across the latest devices and browser versions."
new TextEncoder().encode('café 🧀').toBase64();
My take: use toBase64() in code that only targets current browsers, and use utf8ToBase64 everywhere else. Uint8Array.prototype.toBase64 was undefined in my Node v24.15.0 test, so shared code needs a fallback.
Emoji edge cases: lone surrogates
A lone surrogate is half of a surrogate pair with no partner, and TextEncoder silently replaces it with U+FFFD (�). You usually get one from slice at an index that lands between the two halves of 🧀.
The web.dev article shows the string 'hello⛳❤🧀\uDE75' coming back with a replacement character and blames the decode step. In my test the damage happens earlier. Encoding gave aGVsbG/im7PinaTwn6eA77+9, and 77+9 is the bytes EF BF BD, which is U+FFFD. The half character is gone before Base64 runs.
If the data matters, check first:
if (!text.isWellFormed()) {
throw new Error('Text contains a lone surrogate');
}
encodeURIComponent is stricter. It throws URIError: URI malformed on the same input, so the old unescape trick fails loudly where TextEncoder fails quietly.
When Base64 is the wrong tool
Base64 makes text portable, not smaller or secret. MDN's Base64 glossary says the output is "typically roughly a third larger than its source". Emoji make it worse, since each one is already 4 UTF-8 bytes before encoding.
The limitation: Base64 only fixes transport. It hides nothing, which Is Base64 encryption? covers in detail. If the result goes into a URL or a JWT, you need the URL-safe alphabet; Base64 vs Base64URL explains the difference.
To check a result by hand, the OnlineViewer Base64 encoder is UTF-8 safe and can output URL-safe Base64, and it runs in the page without sending your text anywhere. For shell scripts, see how to decode Base64 on the command line.
FAQ
Why does btoa fail on emoji?
btoa only accepts characters with a code point below 256, one byte each. An emoji such as 🧀 is far above that, so btoa throws an InvalidCharacterError instead of encoding it.
Is unescape(encodeURIComponent(str)) still safe to use?
It still produces the same Base64 as the TextEncoder method, but MDN marks unescape as deprecated. Use TextEncoder in new code and keep the old trick only where you can't change it.
How do I decode Base64 back to Unicode text?
Run atob, turn each character of its result into a byte with charCodeAt, put the bytes in a Uint8Array and decode them with new TextDecoder().decode(bytes).
Does Node.js need TextEncoder for Base64?
No. Buffer.from(text).toString('base64') already uses UTF-8 by default, and 'base64url' gives the URL-safe form without padding.