Skip to content
Raisalon

Software Engineering

Encode Unicode text as Base64 in JavaScript without btoa errors

Fix btoa InvalidCharacterError for Unicode text, see why café can silently encode to the wrong bytes, and round-trip UTF-8 with TextEncoder and TextDecoder.

Author
3 min read

If btoa('✓') throws InvalidCharacterError but btoa('é') succeeds, both outcomes follow the same rule. The browser function expects a string whose character values represent bytes. To Base64-encode ordinary Unicode text for a UTF-8 consumer, encode the text into UTF-8 bytes first. Reverse those two operations when decoding.

Look at a character that silently succeeds

Many examples use an emoji because it makes btoa fail visibly. Try the letter é first. Its value fits in one byte, so btoa('é') returns 6Q==. But the UTF-8 representation of é is the two bytes C3 A9, whose Base64 representation is w6k=. The absence of an exception tells you nothing about whether the receiving system will decode the text correctly.

Text UTF-8 bytes in hexadecimal Base64 for those bytes
A 41 QQ==
é C3 A9 w6k=
✓ E2 9C 93 4pyT

ASCII-only test data hides the mistake because those characters use the same byte values in UTF-8 and in the one-byte input expected by btoa. Add an accented letter and a character above 255 to your fixtures. Those two cases catch the silent error and the explicit exception respectively. MDN btoa reference

Encode the bytes and decode the result

The following functions work in a modern browser console. TextEncoder produces a byte array. To use the widely supported btoa interface, assemble a binary string with one character per byte. During decoding, atob recovers that binary string. Convert its character values back to bytes and ask a UTF-8 decoder for text. MDN TextEncoder reference

function encodeText(text) {
  const bytes = new TextEncoder().encode(text);
  let binary = '';
  for (const byte of bytes) binary += String.fromCharCode(byte);
  return btoa(binary);
}

function decodeText(base64) {
  const binary = atob(base64);
  const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0));
  return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
}

for (const text of ['A', 'é', '✓', 'काठमाडौं', '']) {
  const encoded = encodeText(text);
  if (decodeText(encoded) !== text) throw new Error('Round trip failed');
  console.log(text, encoded);
}

The loop avoids spreading a large byte array into the arguments of a single function call. All intermediate values still live in memory. For substantial file uploads, use the transport’s binary upload support where available rather than building several full-size strings in the page. For a short message you can check the output directly in the UTF-8 Base64 encoder and decoder.

Distinguish invalid Base64 from invalid text

There are two decoding boundaries. atob can reject a malformed Base64 input. A syntactically valid Base64 string can also decode to bytes that are invalid UTF-8. For example, 6Q== decodes to the lone byte E9. The strict decoder in the example rejects that incomplete UTF-8 sequence. The failure identifies a disagreement about character encoding.

If the payload represents an image or an archive, arbitrary byte sequences are expected. Keep it as bytes and pass it to the appropriate consumer. An image payload should never have to pass a UTF-8 validation step. For text from a legacy system, use the character encoding that system actually specifies. Guessing from the appearance of one accented name is unreliable. MDN TextDecoder fatal mode

Keep alphabet and character encoding separate

Base64url changes two alphabet characters so the representation travels more conveniently in URLs. Some protocols also omit trailing padding. Neither choice defines how a string such as “café” became bytes in the first place. Establish the text encoding first, then follow the consuming protocol’s alphabet and padding rules. RFC 4648 Base64 and Base64url

Another source of surprises is Unicode normalization. The single code point é and a plain e followed by a combining acute accent may look identical and produce different UTF-8 bytes. Both can round-trip correctly and still have different Base64 strings. If your application treats those spellings as equivalent, choose a normalization policy at the text boundary. If it signs or verifies exact bytes, preserve the original representation.

Next steps

Test one known byte sequence in addition to testing a round trip. Two functions can share the same mistake and still reverse each other successfully. For a UTF-8 text contract, the assertion that é becomes w6k= checks interoperability with another implementation. The assertion that decodeText('w6k=') returns é checks the independent reading path.

Share

Written by