Base64 Encoding Guide: Usage & Examples
Complete guide to Base64 encoding. Learn how it works, when to use Data URLs vs binary files, and avoid common security pitfalls in web development.
What is Base64 Encoding?
Base64 is a binary-to-text encoding scheme that represents binary data using 64 ASCII characters. It's commonly used to transmit binary data over text-based protocols like HTTP, email, and JSON.
The Base64 Alphabet
Base64 uses:
- A-Z (26 characters)
- a-z (26 characters)
- 0-9 (10 characters)
-
- and / (2 characters)
- = for padding
Common Use Cases
1. Data URLs
Embed images directly in HTML or CSS:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" />
2. Email Attachments
MIME uses Base64 to encode binary attachments in email.
3. API Authentication
Basic Auth headers use Base64:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
4. Storing Binary in JSON
JSON doesn't support binary data, so Base64 is used:
{
"file": "SGVsbG8gV29ybGQh",
"filename": "hello.txt"
}
Base64 in JavaScript
Encoding
// For ASCII strings
const encoded = btoa('Hello World');
// Result: "SGVsbG8gV29ybGQ="
// For UTF-8 strings
const utf8Encoded = btoa(unescape(encodeURIComponent('Hello 世界')));
Decoding
// For ASCII
const decoded = atob('SGVsbG8gV29ybGQ=');
// Result: "Hello World"
// For UTF-8
const utf8Decoded = decodeURIComponent(escape(atob('SGVsbG8g5LiW55WM')));
Common Pitfalls
1. Size Increase
Base64 increases data size by ~33%. A 1MB file becomes ~1.37MB when encoded.
2. Not Encryption
Base64 is encoding, not encryption. Anyone can decode it. Never use it for security.
3. URL Safety
Standard Base64 uses + and / which aren't URL-safe. Use Base64URL for URLs:
- Replace + with -
- Replace / with _
- Remove = padding
4. Newlines
Some implementations add newlines every 76 characters. Be aware when comparing Base64 strings.
Performance Considerations
- Base64 encoding is CPU-intensive for large files
- Data URLs skip HTTP requests but can't be cached
- For images, consider actual file references for production
When NOT to Use Base64
- Large files (use binary upload instead)
- When you need caching
- When bandwidth is a concern
- For security/encryption purposes
Conclusion
Base64 is a versatile encoding that bridges binary and text worlds. Understanding when to use it—and when not to—is essential for modern web development.