Encoding·5 min read·By the developer of StackUtils

Base64 Encoding Explained: What It Is and When to Use It

Base64 is everywhere — JWT tokens, CSS data URIs, email attachments. This guide explains how the algorithm works and when you should (and shouldn't) use it.

What Base64 Is (and Is Not)

Base64 is a way to write arbitrary bytes using only 64 printable ASCII characters: A–Z, a–z, 0–9, + and /, plus = for padding. It exists because many channels were designed for text — email bodies, HTTP headers, JSON strings, HTML attributes — and raw bytes such as 0x00 or 0xFF would be stripped, rewritten or rejected on the way.

It is an encoding, not encryption: the algorithm is public and there is no key, so anyone can reverse it. Authorization: Basic dXNlcjpwYXNz looks opaque, but atob("dXNlcjpwYXNz") returns user:pass. Basic auth is only acceptable over HTTPS for exactly this reason.

How the Algorithm Works: “Man” → “TWFu”

Base64 reads the input three bytes (24 bits) at a time and cuts those 24 bits into four 6-bit groups. Six bits can hold 0–63, which is an index into the alphabet. Here is the classic example:

CharacterByteBits
M7701001101
a9701100001
n11001101110
24 bits:  010011 010110 000101 101110
indexes:  19     22     5      46
alphabet: T      W      F      u        →  "TWFu"

The alphabet order is A=0 … Z=25, a=26 … z=51, 0=52 … 9=61, +=62, /=63.

Padding: where the = comes from

When the input length is not a multiple of three, the last group is short. The encoder fills the missing bits with zeros and adds = so the output length stays a multiple of four:

InputBytesOutputPadding
Man3TWFunone
Ma2TWE=one =
M1TQ==two =

Padding never exceeds two characters. A string ending in ===, or whose length (ignoring whitespace) leaves a remainder of 1 when divided by 4, is not valid Base64.

Size overhead

Every 3 input bytes become 4 output characters, so the encoded length is 4 × ceil(n / 3): one third larger. A 1 MiB file (1,048,576 bytes) becomes 1,398,104 characters. MIME email adds a line break every 76 characters, which pushes the total a few percent higher. This overhead is the main cost to weigh before embedding files as Base64.

Variants: Standard, URL-safe, MIME and PEM

“Base64” is a family. The 64-character core is the same, but the last two characters, padding and line wrapping differ, and mixing them up is the most common cause of decode errors.

VariantChars 62/63PaddingLine breaksWhere you see it
Standard (RFC 4648 §4)+ /RequiredNoneData URIs, JSON payloads, Basic auth
base64url (RFC 4648 §5)- _Usually omittedNoneJWT, WebAuthn, PKCE code challenge, URL parameters
MIME (RFC 2045)+ /RequiredEvery 76 chars (CRLF)Email attachments
PEM (RFC 7468)+ /RequiredEvery 64 chars-----BEGIN CERTIFICATE----- blocks

The same three bytes in both alphabets:

Buffer.from([0xfb, 0xff, 0xfe]).toString("base64")     // "+//+"
Buffer.from([0xfb, 0xff, 0xfe]).toString("base64url")  // "-__-"

JSON Web Tokens use base64url without padding (RFC 7515), which is why a JWT has no = and can sit in a URL unescaped. The JWT guide shows how the three parts are built. If you put standard Base64 in a query string instead, its + will be read as a space by form parsers — see the URL encoding guide for why.

Base64 in JavaScript Without Surprises

btoa() and atob() work on “binary strings” where every character is one byte (code point 0–255). Pass anything outside Latin-1 and the browser throws:

btoa("café ☕")
// InvalidCharacterError: Invalid character

The fix is to encode the text to UTF-8 bytes first, and to decode bytes back with TextDecoder:

function toBase64(text) {
  const bytes = new TextEncoder().encode(text);
  return btoa(String.fromCharCode(...bytes));
}

function fromBase64(b64) {
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

toBase64("café ☕")          // "Y2Fmw6kg4piV"  (9 UTF-8 bytes → 12 chars)
fromBase64("Y2Fmw6kg4piV")  // "café ☕"

For large inputs, spreading millions of bytes into String.fromCharCode can exceed the engine's argument limit; process the array in chunks or use FileReader.readAsDataURL for files. In Node.js, skip all of this and use Buffer, which supports both alphabets:

Buffer.from("café ☕").toString("base64")             // "Y2Fmw6kg4piV"
Buffer.from("Y2Fmw6kg4piV", "base64").toString()     // "café ☕"
Buffer.from("subjects?_d").toString("base64")        // "c3ViamVjdHM/X2Q="
Buffer.from("subjects?_d").toString("base64url")     // "c3ViamVjdHM_X2Q"

Converting between the two alphabets by hand, when you only have btoa/atob:

const toB64Url = (b64) =>
  b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

const fromB64Url = (s) => {
  s = s.replace(/-/g, "+").replace(/_/g, "/");
  while (s.length % 4) s += "=";
  return s;
};

atob(fromB64Url("-__-"))  // bytes 251, 255, 254

Decode Errors and What Causes Them

SymptomLikely causeFix
InvalidCharacterError from atobInput is base64url (- or _) or contains a data: prefixConvert - _ to + / and strip everything up to the comma of data:...;base64,
Python: binascii.Error: Incorrect paddingPadding was removed (JWT, base64url)Append = until length % 4 === 0. Browsers' atob tolerates missing padding; Python's b64decode does not.
Decoded text shows é instead of éUTF-8 bytes were read as Latin-1 (atob result used directly)Decode the bytes with TextDecoder, as above
Hash or signature mismatch on identical textA trailing newline was encoded: echo "hello" | base64 gives aGVsbG8KUse echo -n or printf; aGVsbG8= is "hello" without the newline
Image data URI shows a broken iconWrong MIME type, or the Base64 was line-wrapped or truncatedCheck the first characters (table below) and the total length

Recognising content from the first characters

Because Base64 maps fixed byte patterns to fixed characters, common file signatures produce recognisable prefixes. This is handy when a log or an API response hands you an unlabeled blob:

PrefixDecodes toContent
eyJ{"JSON — typical of JWT header and payload
iVBORw0KGgo\x89PNG\r\n\x1a\nPNG image
/9j/\xFF\xD8\xFFJPEG image
R0lGODGIF8GIF image
JVBERi0%PDF-PDF document
UEsDBAPK\x03\x04ZIP container (also .docx, .xlsx, .jar)

To check a suspected image quickly, paste it into Base64 to Image; for text or arbitrary files, the Base64 encoder/decoder accepts both alphabets, missing padding, line-wrapped input and a leading data: prefix.

When to Use It, and When Not To

SituationBase64?Reason
A 1–2 KB SVG or PNG icon in CSSReasonableSaves a request; the 33% overhead is tiny at this size.
Hero images, fonts, anything over a few KBNoInlined data cannot be cached separately and inflates every HTML/CSS download.
Binary file inside a JSON API bodyYes, if the API is JSON-onlyOtherwise multipart/form-data or a direct upload avoids the overhead.
Storing files in a databaseNoUse BYTEA/BLOB or object storage; Base64 costs a third more space.
Hiding secrets or IDsNeverAnyone can decode it. Use encryption, or keep the data server-side.
Making data smallerNeverBase64 always grows data. Compress first (gzip, Brotli), then encode if the channel needs text.

One more practical constraint: a strict Content Security Policy can block data: images unless img-src lists data:. If inline images vanish only in production, check the CSP header.

To produce a data URI from a local file, use Image to Base64; it outputs the complete data:image/…;base64, string ready for an <img> tag or a CSS url().

Try it in your browser

Encode or decode Base64 and base64url locally — files never leave your device.