You've probably encountered Base64 strings—those long sequences of letters, numbers, and occasional plus signs or slashes. They look like gibberish, but they serve a crucial purpose: safely transmitting binary data through text-only channels.
What Is Base64?
Base64 is an encoding scheme that converts binary data into ASCII text using 64 printable characters: A-Z, a-z, 0-9, plus (+), and slash (/). The equals sign (=) is used for padding.
Example:
Text: "Hello"
Base64: "SGVsbG8="
Why Base64 Exists
Many systems were designed to handle only text (ASCII characters). Binary data—like images, audio, or encrypted content—contains bytes that might be misinterpreted or corrupted by text-only systems.
Base64 solves this by representing binary data using only safe, printable characters that survive transmission through any text-based system.
Common Use Cases
Email Attachments
MIME (email format) uses Base64 to embed attachments. When you attach a PDF or image to an email, it's Base64-encoded for transmission.
Data URIs in HTML/CSS
Small images can be embedded directly in code:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE...">
This eliminates an HTTP request but increases HTML file size by ~33%.
Basic Authentication
HTTP Basic Auth encodes username:password in Base64:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Note: This is encoding, not encryption. It's trivially reversible and not secure without HTTPS.
API Payloads
When APIs need to transmit binary data in JSON (which is text), Base64 is the standard solution.
Storing Binary in Text Fields
Databases with text-only columns can store binary data as Base64 strings.
The 33% Size Increase
Base64 encoding increases data size by approximately 33%. Every 3 bytes of binary data become 4 characters of Base64. This is the tradeoff for text safety.
Base64 Variants
- Standard Base64: Uses + and / (can cause issues in URLs)
- URL-safe Base64: Uses - and _ instead (safe for URLs)
- Base64 without padding: Omits the trailing = signs
Base64 in JavaScript
// Encode
const encoded = btoa("Hello, World!");
// "SGVsbG8sIFdvcmxkIQ=="
// Decode
const decoded = atob("SGVsbG8sIFdvcmxkIQ==");
// "Hello, World!"
Note: btoa() only works with Latin1 characters. For Unicode, use additional encoding steps.
Common Mistakes
- Thinking Base64 is encryption: It's not. Anyone can decode it instantly.
- Embedding large files: Base64 data URIs bloat page size and aren't cached separately.
- Forgetting URL encoding: Standard Base64 contains characters that need URL encoding.
The Bottom Line
Base64 is a simple but essential tool for transmitting binary data through text channels. It's not for security—it's for compatibility. Use it when you need to embed binary in text formats, and remember the 33% size overhead.