Blog · 3 min read ·

Why btoa() Breaks on Emoji (and the Two-Line Fix)

Try this in a browser console: btoa("hi 👋"). You get an error saying the string contains characters outside the Latin1 range. It's one of those bugs everyone hits once. I hit it while building my Base64 encoder.

Why it happens

Base64 encodes bytes, not text. btoa() was designed back when JavaScript treated each character as one byte. It reads every character's code and expects it to be between 0 and 255. "h" is 104, fine. The waving hand emoji is code point 128075, which doesn't fit in a byte, so btoa() gives up.

The fix: turn text into bytes first

Text has to become bytes before it can be Base64'd, and the standard way to do that is UTF-8. Browsers have a built-in for it: TextEncoder. Encode the string to a byte array, turn each byte into a one-byte character, then call btoa() on that:

  • encode: new TextEncoder().encode(text) gives UTF-8 bytes
  • map each byte to String.fromCharCode(byte) and join
  • call btoa() on the result

Decoding is the same in reverse: atob() gives one character per byte, copy those into a Uint8Array, and run new TextDecoder().decode(bytes).

Bonus: URL-safe Base64

Some systems (like JWTs) use - and _ instead of + and /, and drop the = padding. My decoder swaps those back before calling atob(), so either form works.

Try the Base64 encoder and decoder. Paste in any emoji you like.