Skip to content
All posts
9 min read(updated October 20, 2026)

How to Base64 encode and decode in JavaScript: btoa, atob, Buffer, and Data URLs

A complete, copy-paste-tested guide to Base64 in JavaScript: the btoa/atob basics, the Unicode trap that breaks naive code, TextEncoder done right, Node Buffer equivalents, and Data URL patterns for files.

  • javascript
  • guide
  • web

Every JavaScript developer ends up needing Base64 eventually: you tuck a state object into a URL, you send a binary payload through a JSON-only API, you inline a small image into a stylesheet. And every year the same bug reproduces itself somewhere — code that works for English text and then breaks the first time it meets a character above the U+00FF ceiling — an emoji, a currency symbol like €, or a CJK character. This guide covers the platform properly: what btoa/atob actually accept, the Unicode trap and its two correct fixes, the Node.js Buffer equivalents, modern built-in methods, and the file/FileReader patterns for Data URLs. Every snippet below is copy-paste tested.

Scope first: btoa is not a string encoder

The single most important fact about btoa() is the one its name hides. It does not mean “binary to ASCII” in the sense of “some bytes to some text”. It means: give me a string whose characters are all in the range U+0000 to U+00FF — one character per byte — and I will Base64-encode those bytes.

const encoded = btoa('Hello world'); // 'SGVsbG8gd29ybGQ='
const decoded = atob(encoded);       // 'Hello world'

That works because every character in 'Hello world' has a code point below 256, so the string is already a sequence of bytes. But this is an accident of using English, not a guarantee. Two traps follow. First, btoa('Müller') appears to work — ü is U+00FC, still under the ceiling — but it encodes ü as the single Latin-1 byte 0xFC instead of UTF-8’s 0xC3 0xBC. Locally, atob round-trips it back to 'Müller' without complaint; the damage surfaces the moment a real UTF-8 decoder sees those bytes — a lone 0xFC is not a valid UTF-8 lead byte, so the text comes back as M<FFFD>ller (the replacement character — the decode-side failure this site explains in depth). Second, anything above the ceiling fails outright: btoa('Müller 🎉') throws InvalidCharacterError (U+1F389 is far above U+00FF). Characters U+0080–U+00FF straddle both behaviors — the ceiling is not the same boundary as “ASCII”.

So the real job statement is: btoa/atob translate between byte strings and Base64 strings. Encoding an arbitrary JavaScript string to Base64 therefore always has two steps:

  1. string → bytes (choose an encoding, almost always UTF-8)
  2. bytes → Base64 (btoa)

The bug in broken code is skipping step 1 and hoping a string can masquerade as bytes. The rest of this post is about doing step 1 correctly.

The Unicode-safe encode: two proven approaches

Approach 1: encodeURIComponent bridge (compact and battle-tested)

The classic workaround — btoa(unescape(encodeURIComponent(str))) — works, but unescape is a deprecated relic of 1990s JavaScript. The encodeURIComponent version performs exactly the same transformation with modern, sanctioned tools:

// JavaScript string → UTF-8 bytes (as a binary string) → Base64
function utf8ToBase64(str) {
  const bytes = encodeURIComponent(str).replace(
    /%([0-9A-F]{2})/g,
    (_, hex) => String.fromCharCode(parseInt(hex, 16))
  );
  return btoa(bytes);
}

Why this chain works: encodeURIComponent turns every non-ASCII character and unsafe byte into %XX percent-escapes, where XX is the UTF-8 byte value. The regex then converts each escape back into a single character with that byte’s code point. That produces the byte string step 1 needs — UTF-8 bytes wearing a Latin-1 costume — and btoa finishes the job. Note this is not URL encoding; the encodeURIComponent is a conversion conveyor belt, no URL semantics survive it.

The cleaner way names the encoding instead of hiding it inside a regex:

// JavaScript string → Uint8Array of UTF-8 bytes → Base64
function utf8ToBase64(str) {
  const bytes = new TextEncoder().encode(str); // UTF-8 by definition
  const bin = Array.from(bytes, (b) => String.fromCharCode(b)).join('');
  return btoa(bin);
}

TextEncoder().encode() always produces UTF-8 — there is no encoding parameter to pick wrongly — and hands you a Uint8Array, a real byte container. Mapping each byte through String.fromCharCode builds the one-char-per-byte string btoa expects. For large inputs, build the byte string in chunks to avoid the max-arguments limit of apply:

function bytesToBase64(bytes) {
  const CHUNK = 0x8000; // 32768: keeps Array/String APIs comfortably alive
  const parts = [];
  for (let i = 0; i < bytes.length; i += CHUNK) {
    parts.push(String.fromCharCode(...bytes.subarray(i, i + CHUNK)));
  }
  return btoa(parts.join(''));
}

Both approaches produce byte-identical output. Pick one and use it everywhere.

The Unicode-safe decode: round-trip in the same direction

Decoding is not the mirror of any single encode step — it must reverse both steps: Base64 → bytes → string. Calling atob and stopping there gives you a byte string; feeding that to decodeURIComponent without re-escaping misdecodes accented text in subtle ways. The correct inverse of the approaches above:

// Base64 → UTF-8 bytes → JavaScript string
function base64ToUtf8(b64) {
  const bin = atob(b64); // binary string, one char per byte
  const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes); // UTF-8
}

TextDecoder handles multi-byte UTF-8 sequences the way the spec demands: complete emoji and accented characters reconstruct exactly, malformed sequences surface as U+FFFD replacement characters instead of silent corruption. That last property — loud failure for broken input — is worth real money in debugging time.

Node.js: Buffer does all of it

In Node.js, btoa and atob exist as globals (since v16) and follow the browser rules exactly — the same Unicode ceiling applies. But the idiomatic Node-native path is Buffer, which is simultaneously a byte container and an encoder, collapsing the two steps into one call each way:

const encoded = Buffer.from('Hello, Müller 👋!', 'utf8').toString('base64');
// 'SGVsbG8sIE3DvGxsZXIg8J+RiyE='

const decoded = Buffer.from(encoded, 'base64').toString('utf8');
// 'Hello, Müller 👋!'

Three practical notes that save debugging sessions:

  1. Buffer.from(str, 'base64') is forgiving by design. It skips whitespace, accepts missing padding, and tolerates either alphabet. Handy for user input — useless for validation. If you need to reject malformed Base64, validate a strict pattern first (below).
  2. The URL-safe alphabet is built in: myBuffer.toString('base64url') uses - and _ and drops padding — exactly the JWT flavor. No manual swap.
  3. Buffer is not available in browsers. Bundlers sometimes shim it badly enough to work in dev and explode in production. For web code, depend on TextEncoder/TextDecoder; reserve Buffer for server code.

The modern shortcut: toBase64 / fromBase64 on typed arrays

A recent addition to the language standard closes the biggest ergonomic gap — encoding a Uint8Array (a file, an image thumbnail, a signature) without building an intermediate string at all:

const bytes = new TextEncoder().encode('Hello, Müller 👋!');
const b64 = bytes.toBase64();          // browser native, no btoa dance
const back = Uint8Array.fromBase64(b64);
new TextDecoder().decode(back);        // round-trips perfectly

Uint8Array.prototype.toBase64() and Uint8Array.fromBase64() grew out of the TC39 base64 proposal and have now shipped in current evergreen browsers and recent Node versions — check availability before building on them (a one-line feature test: typeof Uint8Array.fromBase64 === 'function'), since slightly older runtimes still need the fallback patterns above — the new methods do the same job natively, and faster. Also note the btoa/atob duo itself is now flagged legacy on the Web platform — it isn’t going anywhere, but the typed-array methods are where the standard is investing. fromBase64 is forgiving toward whitespace and missing padding, and offers strict-mode options when you need them.

Data URLs: encoding and decoding files

The most frequent file-shaped ask is turning a picked file into a Data URL for previews, inline uploads, or form submissions. The browser gives you this built in — no manual Base64 involved:

input.addEventListener('change', () => {
  const file = input.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = () => {
    // reader.result === 'data:image/png;base64,iVBORw0KGgoAA...'
    preview.src = reader.result;
  };
  reader.readAsDataURL(file);
});

To go the other way — a Base64 string (or Data URL you received from an API) into a real Blob you can download or re-upload — decode to bytes and let Blob describe the type:

function base64ToBlob(b64OrDataUrl, mime = 'application/octet-stream') {
  const b64 = b64OrDataUrl.replace(/^data:[^;]+;base64,/, ''); // strip a Data URL header if present
  const bin = atob(b64);
  const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
  return new Blob([bytes], { type: mime });
}

const url = URL.createObjectURL(base64ToBlob(b64, 'image/png'));
const a = Object.assign(document.createElement('a'), { href: url, download: 'photo.png' });
a.click();
URL.revokeObjectURL(url); // release the memory when you're done

Decode actually creating a Blob (rather than a bare string) is what preserves binary content — images, PDFs, zip archives — through a text-only host like JSON.

Decoding user input without crashes

Default atob behavior on malformed input is to throw — and its error messages say nothing about what was wrong. Before calling it, validate shape with a strict pattern and answer your user with something specific:

function decodeBase64Safe(input) {
  const cleaned = input.replace(/\s+/g, ''); // tolerate newlines/whitespace
  const isStandard = /^[A-Za-z0-9+/]*={0,2}$/.test(cleaned);
  const isUrlSafe = /^[A-Za-z0-9_-]*={0,2}$/.test(cleaned);
  if (!isStandard && !isUrlSafe) {
    throw new SyntaxError('Input contains characters outside any Base64 alphabet.');
  }
  if (cleaned.length % 4 === 1) {
    throw new SyntaxError('Invalid length: a Base64 string can never have remainder 1 mod 4.');
  }
  const padded = cleaned.padEnd(Math.ceil(cleaned.length / 4) * 4, '=');
  const normalized = isUrlSafe ? padded.replaceAll('-', '+').replaceAll('_', '/') : padded;
  const bin = atob(normalized);
  const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
  return { bytes, text: new TextDecoder().decode(bytes) };
}

Two subtleties embedded there: the mod 4 === 1 check is a real mathematical impossibility (padding can yield remainder 0, 2, or 3 — never 1), so it detects truncated input before atob has the chance to be vague; and normalizing the URL-safe alphabet up-front means one decode path handles JWT fragments and standard Base64 with the same code. Each error produced here names the problem the way a first-class decoder tool would.

Where Base64 earns and loses its keep in JavaScript

Three honest notes to close the engineering decision:

  • Size: Base64 makes payloads ~33% bigger (3 bytes → 4 characters) and JavaScript strings add their own overhead. For a 2 MB image, that’s ~2.7 MB of string your garbage collector, network, and browser cache all carry. Prefer inlining genuinely small assets; for anything bigger, load it as a file.
  • Latency: encoding is O(n) and single-threaded on the main thread. If you encode multi-megabyte inputs, do it in a Web Worker so typing and scrolling don’t jank — FileReader and TextEncoder/TextDecoder all work inside workers, so the Data URL pattern above moves over unchanged.
  • Trust model: btoa/atob are rot-13-class tools for secrecy — anyone sees through them instantly. Use Base64 for transit safety (JSON, URL query values after encodeURIComponent, Data URLs), and reach for the Web Crypto API when confidentiality matters. The same discipline applies to tokens: split the parts and inspect them in the JWT inspector before trusting the payload.

If you want to sanity-check any of these snippets against an independent implementation — with byte-level hex views, alphabet detection, and file previews — run the same input through the Base64 encoder and decoder on this site. For the same tour in Python, see the Python guide.

Try it yourself — right now

Both tools run 100% in your browser. Nothing you type or drop is ever uploaded.

Related posts

esc

Tools

Pages

↑↓ navigate↵ open⌘K

Keyboard shortcuts

Same shortcuts everywhere — ⌘ on macOS, Ctrl on Windows and Linux.