Base64 is a binary-to-text encoding scheme that represents binary data using only 64 printable ASCII characters. It was designed to safely transport binary data (images, files, binary blobs) through channels that were designed for text.
Why Does Base64 Exist?
Many protocols — email (SMTP), URLs, HTTP headers — were originally designed for ASCII text only. If you tried to send binary data (a JPEG image, a PDF) through these channels, special bytes would get corrupted or misinterpreted as control characters.
Base64 solves this by converting every 3 bytes of binary into 4 printable characters. The output is always plain text, safe to transmit anywhere.
How Base64 Works
The algorithm is simple: take 3 bytes (24 bits), split into 4 groups of 6 bits each, map each 6-bit group to a character from the Base64 alphabet (A-Z, a-z, 0-9, +, /).
Input: "Man"
Binary: 01001101 01100001 01101110
Groups: 010011 010110 000101 101110
Index: 19 22 5 46
Output: T W F u → "TWFu"The Base64 Alphabet
A-Z = 0-25
a-z = 26-51
0-9 = 52-61
+ = 62
/ = 63
= = padding (when input not divisible by 3)Real-World Use Cases
- Email attachments — MIME encodes all attachments as Base64
- CSS data URIs — embed images directly in CSS:
url("data:image/png;base64,...") - JWT tokens — header and payload are Base64URL encoded
- HTTP Basic Auth —
Authorization: Basic base64(user:password) - API payloads — send binary files through JSON APIs
- Fonts in CSS — embed web fonts inline
Base64 in JavaScript
// Encode
const encoded = btoa('Hello, World!');
// → "SGVsbG8sIFdvcmxkIQ=="
// Decode
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
// → "Hello, World!"
// For Unicode strings (btoa breaks on non-ASCII)
const encoded = btoa(unescape(encodeURIComponent('नमस्ते')));
const decoded = decodeURIComponent(escape(atob(encoded)));Base64 vs Base64URL
Standard Base64 uses + and / which are unsafe in URLs. Base64URL replaces them: + → -, / → _, and removes padding =. JWT tokens use Base64URL.