All articles

Base64 encoding explained

· 3 min read

Base64 shows up everywhere: in data URLs, email attachments, HTTP Basic authentication, JWTs and JSON fields that carry files. It isn't compression or encryption. It's a way to write arbitrary bytes using only characters that survive systems built for text.

Why Base64 exists

Many protocols and formats were designed for text: email bodies, URLs, HTML attributes, JSON strings. Raw binary data contains bytes that those systems treat specially, such as zero bytes, line breaks or quotes. Base64 avoids the problem by using just 64 characters that are safe nearly everywhere:

A–Z  a–z  0–9  +  /     (and = for padding)

How the encoding works

Base64 takes the input 3 bytes (24 bits) at a time and splits them into four groups of 6 bits. Each 6-bit value (0–63) picks one character from the alphabet.

Encoding the text Man:

M a n
ASCII 77 97 110
Bits 01001101 01100001 01101110

Regrouped into 6 bits: 010011 010110 000101 101110 → 19, 22, 5, 46 → T, W, F, u. So Man becomes TWFu.

That 3-to-4 ratio is why Base64 output is about a third larger than the input.

What the = padding means

When the input length isn't a multiple of 3, the last group is short. The encoder pads it with zero bits and adds = characters so the output length stays a multiple of 4:

  • 1 leftover byte → 2 characters + ==
  • 2 leftover bytes → 3 characters + =
"M"   → "TQ=="
"Ma"  → "TWE="
"Man" → "TWFu"

Base64URL

+ and / have special meanings in URLs and file names, so RFC 4648 defines a URL-safe variant: - replaces +, _ replaces /, and the padding is usually dropped. JWTs and many web APIs use it. Converting between the two:

const toBase64Url = (b64) => b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const fromBase64Url = (url) => {
  const b64 = url.replace(/-/g, "+").replace(/_/g, "/");
  return b64 + "=".repeat((4 - (b64.length % 4)) % 4);
};

Base64 in JavaScript

The btoa trap

Browsers have had btoa and atob for a long time, but they work on "binary strings" where each character is one byte. Text with characters outside Latin-1 throws:

btoa("café ✓"); // InvalidCharacterError

And decoding UTF-8 Base64 with atob alone produces garbled text like café, because the bytes are read as Latin-1 characters.

Encode text correctly

Convert the text to UTF-8 bytes first with TextEncoder, then encode the bytes:

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

function decodeBase64(base64) {
  const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

encodeBase64("café ✓"); // "Y2Fmw6kg4pyT"
decodeBase64("Y2Fmw6kg4pyT"); // "café ✓"

Newer JavaScript engines add Uint8Array.prototype.toBase64() and Uint8Array.fromBase64(), which do the byte conversion directly and support Base64URL with { alphabet: "base64url" }. Check browser support before relying on them.

Node.js

Buffer handles both variants and UTF-8:

Buffer.from("café ✓", "utf8").toString("base64");      // "Y2Fmw6kg4pyT"
Buffer.from("Y2Fmw6kg4pyT", "base64").toString("utf8"); // "café ✓"
Buffer.from("hello?").toString("base64url");           // "aGVsbG8_"

Files

To turn a file into a data URL in the browser, FileReader.readAsDataURL does the encoding:

const reader = new FileReader();
reader.onload = () => console.log(reader.result); // "data:image/png;base64,iVBOR..."
reader.readAsDataURL(file);

Base64 in Python and the shell

import base64
base64.b64encode("café ✓".encode("utf-8")).decode("ascii")  # 'Y2Fmw6kg4pyT'
base64.urlsafe_b64encode(b"hello?")                          # b'aGVsbG8_'
printf 'café ✓' | base64          # Y2Fmw6kg4pyT
echo 'Y2Fmw6kg4pyT' | base64 -d   # café ✓  (macOS: base64 -D on older versions)

Use printf rather than echo when encoding: echo adds a newline, which becomes part of the encoded data.

When to use Base64, and when not to

Good uses:

  • Small images or fonts inlined as data URLs, saving a request.
  • Binary values inside JSON or XML, such as a signature or a short key.
  • HTTP Basic auth, which sends user:password Base64-encoded (always over HTTPS).
  • Email attachments, where MIME requires text-safe content.

Avoid it for:

  • Hiding data. Anyone can decode it. Encrypt instead, and hash passwords.
  • Large files in APIs. A 10 MB upload becomes 13+ MB of JSON that must be held in memory. Upload binary data directly, with multipart/form-data or a pre-signed URL.
  • Big inline images. They make HTML and CSS heavier and can't be cached separately.

Common errors

Symptom Cause
InvalidCharacterError from btoa The text has characters outside Latin-1; encode to UTF-8 bytes first.
InvalidCharacterError from atob Whitespace in the input, or Base64URL characters - and _.
Decoded text shows é UTF-8 bytes decoded as Latin-1; use TextDecoder.
Output differs from another tool by a trailing Cg== One side encoded a trailing newline.

Base64 is also what makes a JWT readable by anyone who holds it, which is why decoding a token isn't the same as verifying it.

Frequently asked questions

Is Base64 encryption?

No. It has no key and anyone can decode it. Use it to transport data, never to hide it.

Why does Base64 make data bigger?

Every 3 bytes become 4 characters, so the output is about 33% larger, plus padding. Line breaks added by some encoders (MIME uses 76-character lines) add a little more.

Can I remove the = padding?

The length can be recovered without it, and Base64URL often omits it. Some decoders require it, though, so add it back (to a multiple of 4 characters) before decoding with a strict decoder.

Why does atob fail on my string?

Usually because it contains characters outside the alphabet: spaces or line breaks, or - and _ from Base64URL. Remove the whitespace or convert - to + and _ to / first.

Further reading