Base64 Encoding Explained: When to Use It and When to Avoid It
What is Base64 encoding, why it exists, and when to use it in web development. Includes real-world examples for APIs, image data URIs, and authentication tokens.
Base64 Encoding Explained: When to Use It and When to Avoid It
What Base64 Actually Does
Base64 converts binary data into ASCII text. Itβs an encoding, not encryption.
// Encoding: binary β text
const encoded = btoa('hello'); // "aGVsbG8="
const decoded = atob('aGVsbG8='); // "hello"
// In Node.js
Buffer.from('hello').toString('base64'); // "aGVsbG8="
Buffer.from('aGVsbG8=', 'base64').toString('utf8'); // "hello"
Why Base64 Exists
Email was designed for 7-bit ASCII text. When email needed to send images, attachments, or non-text data, Base64 provided a way to convert binary into printable characters.
Today, the same principle applies to:
- Embedding images directly in CSS/HTML (
data:image/png;base64,...) - Transmitting binary over JSON APIs
- Storing binary in environments that only support text
Real-World Example: Data URI Images
<!-- β External image (extra HTTP request) -->
<img src="https://example.com/icon.png">
<!-- β
Inline data URI (no extra request, increases HTML size) -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==">
Size Overhead
Base64 increases size by ~33%:
| Original | Base64 Encoded |
|---|---|
| 100 bytes | ~133 bytes |
| 10 KB | ~13.3 KB |
| 100 KB | ~133 KB |
Rule: Only inline images smaller than 2-4 KB. Larger images should be external files.
When to Use Base64
β Good use cases:
- Embedding small icons in CSS/HTML
- Transmitting binary API tokens over JSON
- Storing small binary configs in text-based formats
- Email attachment encoding (MIME)
β Bad use cases:
- Embedding large images in HTML (bloats page size)
- Storing passwords (use bcrypt instead)
- βEncryptingβ data (itβs not encryption)
- URL encoding (use
encodeURIComponentinstead)
Detecting Base64
function isBase64(str) {
try {
return btoa(atob(str)) === str;
} catch {
return false;
}
}
isBase64('aGVsbG8='); // true
isBase64('hello'); // false (needs padding) Free Newsletter
Level Up Your Dev Workflow
Get new tools, guides, and productivity tips delivered to your inbox.
Plus: grab the free Developer Productivity Checklist when you subscribe.
Found this guide useful? Check out our free developer tools.
Affiliate disclosure: Some links below are affiliate links β we may earn a small commission at no extra cost to you. Learn more.
Recommended Tools & Resources
DigitalOcean
$200 credit for new users. Simple, affordable cloud hosting for developers.
GitHub Student Pack
Free access to 100+ developer tools. Perfect for students and new devs.
Vercel
Deploy frontend apps instantly. Free tier is generous for side projects.
DevPlaybook Products
Boilerplates, scripts & AI toolkits to 10x your dev workflow.