Decoding Base64 in JavaScript

In a browser, decode with atob for byte strings and Uint8Array plus TextDecoder when the content is UTF-8 — atob alone garbles non-ASCII text. In Node, use Buffer.from(value, "base64").toString("utf8"). For Base64URL, convert - and _ back to + and / and restore the padding first.

  • Browser, UTF-8: new TextDecoder().decode(Uint8Array.from(atob(s), c \u003d\u003e c.charCodeAt(0)))
  • Node: Buffer.from(s, "base64").toString("utf8")
  • Base64URL: replace - with +, _ with /, then pad to a multiple of 4
  • atob throws InvalidCharacterError on characters outside the alphabet
  • Paste a string into the tool above to see the decoded text
b64file — converter · local

Processed as you paste — no button to press (Ctrl+Enter converts now / Esc clears)

Paste, drag and drop, or Ctrl+V a screenshot

[01]

Browser: the short version and its trap

atob() decodes Base64 into a binary string — one character per byte. That is correct for binary data and wrong for text that is not pure ASCII, because most of the web is UTF-8 and a single accented character spans two bytes.

// Broken for non-ASCII: "café" comes back as "café"
const text = atob(base64);

// Correct: bytes -> UTF-8
const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
const text = new TextDecoder('utf-8').decode(bytes);

The reverse direction has the same gap. btoa() accepts only characters with codes below 256, so encoding a string containing "→" or an emoji throws. Encode the UTF-8 bytes first:

const bytes = new TextEncoder().encode(text);
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
const base64 = btoa(binary);

The loop is deliberate. String.fromCharCode(...bytes) is shorter but spreads the whole array into arguments, and on a multi-megabyte payload that overflows the call stack.

[02]

Node and Bun

Buffer handles both directions and assumes the encoding is UTF-8 for strings, which is what you want in almost every case:

const text = Buffer.from(base64, 'base64').toString('utf8');
const encoded = Buffer.from(text, 'utf8').toString('base64');

If you need the raw bytes rather than a string — writing a decoded image to disk, say — stop at Buffer.from(base64, 'base64') and pass that to fs.writeFile. Decoding to a string first and re-encoding would corrupt anything that is not valid UTF-8.

Bun implements Buffer and also ships atob/btoa, so browser code runs unchanged. Deno provides atob/btoa and TextDecoder globally as well; Buffer needs an import.

[03]

Base64URL, which is what tokens actually use

JWTs, OAuth state parameters and most signed URLs use the URL-safe alphabet: - and _ instead of + and /, and padding stripped. A standard decoder rejects it, so normalise first:

function fromBase64Url(value) {
  const standard = value.replace(/-/g, '+').replace(/_/g, '/');
  const padded = standard + '='.repeat((4 - (standard.length % 4)) % 4);
  return padded;
}

Decoding a JWT payload is then three lines — and worth doing once on your own tokens to see what a reader can learn from them:

const payload = JSON.parse(
  new TextDecoder().decode(
    Uint8Array.from(atob(fromBase64Url(token.split('.')[1])), (c) => c.charCodeAt(0))
  )
);
[04]

Turning Base64 back into a file

If the string is a data URL (data:application/pdf;base64,JVBERi0...), the browser can fetch it directly. If it is bare Base64, state the type yourself:

const res = await fetch('data:application/pdf;base64,' + base64);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'document.pdf';
a.click();
URL.revokeObjectURL(url);

Two details that bite: the MIME type in the data URL decides how the browser treats the download, and revokeObjectURL has to come after the click, not before. For a quick manual check of what is inside a string, the Base64 to file tool does the same thing without code.

[05]

When it throws

InvalidCharacterError means the string contains characters outside the alphabet — usually a space, a newline, a smart quote pasted from a document, or the URL-safe characters in a standard decoder. Modern browsers strip ASCII whitespace, but they do not forgive the wrong alphabet.

A decode that succeeds but produces garbled text is a different problem: it is almost always the UTF-8 issue from the first section, not corrupt data. A decode that succeeds but produces nothing useful usually means the string was truncated when it was copied — the length will not be a multiple of four. Both cases are covered in common Base64 decode errors.

Frequently asked questions

Is atob deprecated?

No — it is still the standard browser API and fine for byte strings. The problem is only that it returns one character per byte, which is not how text works. Pair it with TextDecoder and it is correct.

Why does atob exist if Buffer is simpler?

Buffer is a Node API. Browsers have no Buffer, and bundling a polyfill for a single decode ships kilobytes to do what two native calls already do.

Can I decode a whole large file in the browser?

Not comfortably in one string. Above a few megabytes, decode in a Web Worker so the main thread stays responsive, and work with Blob/ArrayBuffer rather than building giant JavaScript strings.

Does decoding Base64 tell me what the file type is?

Only if you look at the first bytes. A PDF starts with %PDF, a PNG with the byte sequence 89 50 4E 47, a ZIP-based format such as DOCX with PK. The Base64 text itself carries no type information unless it is wrapped in a data URL.

Related tools and guides