Files and data

Base64-encode a small byte array in a browser

Btoa encodes a binary string, not arbitrary Unicode text. For a small byte array, map each byte to a code unit before encoding; encode text to UTF-8 bytes first if text is the input.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const bytes = new TextEncoder().encode("café");
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
const encoded = btoa(binary);
const restored = Uint8Array.from(atob(encoded), char => char.charCodeAt(0));
console.log(new TextDecoder().decode(restored));

How it works

Each binary-string code unit represents one byte in the range zero through 255. Base64 operates on that representation, and atob restores it. The final decoder interprets the recovered bytes as UTF-8 to reconstruct the original text.

Limits and mistakes

This simple approach is for small inputs and creates several copies. Do not spread a huge byte array into String.fromCharCode because argument limits can fail. Base64 is encoding, not encryption, and increases payload size.

Check the result

Expect café. Test characters outside the single-byte range, including emoji, to ensure the UTF-8 conversion occurs before Base64 rather than passing the original text directly to btoa.

Sources

Reference documentation for the behavior used in this guide: