Base64 Encoding: When and Why to Use It
Complete Base64 guide: how it works, when to use it, practical examples in JavaScript and Python.
You're building an API and need to send an image in the JSON body. Or you want to embed an icon directly in CSS without making an extra HTTP request. Or you're reading a JWT and wondering how to decode that blob of seemingly random characters. In all these cases, the answer is the same: Base64.
But what exactly is Base64? When should you use it and, more importantly, when should you avoid it? In this guide, we'll cover the 8 real use cases for Base64, with ready-to-use code examples.
Base64 in 30 seconds
Base64 is an encoding system that transforms binary data (images, files, any sequence of bytes) into a text string using only 64 "safe" characters: A-Z, a-z, 0-9, + and /. This makes it perfect for transmitting binary data through channels designed only for text.
Warning: Base64 is not encryption. The data is perfectly readable by anyone who decodes it. Never use it to "hide" sensitive information.
The trade-off: Base64 output is about 33% larger than the original input. A 100KB image becomes ~133KB in Base64.
The 8 real use cases for Base64
1. Email attachments (MIME)
The original use case. Email protocols (SMTP) were designed to transmit only ASCII text. To send binary files like PDFs or images, the client automatically encodes them in Base64.
When you send an attachment, this happens behind the scenes:
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="document.pdf"
JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL1hPYmplY3QvU3VidHlwZS...
2. Inline images in HTML/CSS (Data URI)
Want to reduce HTTP requests? You can embed small images directly in your code:
<!-- HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEU..." />
/* CSS */
.icon {
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bW...");
}
When to use it: small icons (<2KB), images critical for first paint, situations where you want to eliminate external dependencies.
When to avoid it: large images (the 33% extra matters), images that could be cached by the browser.
3. Binary data in JSON/APIs
JSON is a pure text format. You can't insert raw bytes. If your API needs to handle file uploads or return images, Base64 is the standard solution:
// Request
{
"fileName": "photo.jpg",
"fileContent": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA...",
"mimeType": "image/jpeg"
}
// In backend (Node.js)
const buffer = Buffer.from(fileContent.split(',')[1], 'base64');
fs.writeFileSync('upload.jpg', buffer);
4. JWT (JSON Web Token)
Every JWT consists of three parts separated by dots, and the first two (header and payload) are encoded in Base64URL (a URL-safe variant of Base64):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4ifQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
// Decode the payload
atob('eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4ifQ')
// → '{"sub":"1234567890","name":"John"}'
Important: JWT content is not encrypted, only signed. Anyone can read the payload by decoding it. Never put sensitive data in the payload.
5. HTTP Basic Authentication
The simplest authentication method encodes username and password in Base64:
// Format: username:password → Base64
const credentials = btoa('john:password123');
// → 'am9objpwYXNzd29yZDEyMw=='
// HTTP Header
Authorization: Basic am9objpwYXNzd29yZDEyMw==
Warning: this is not secure without HTTPS. Anyone intercepting the request can decode the credentials instantly.
6. SSL certificates and cryptographic keys (PEM)
Have you ever opened a .pem or .crt file? What you see is Base64:
-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAJC1HiIAZAiUMA0Gcg...
Df84LN5ILHR4eKBJnQy1mZo8OsGJ0RV5HRD...
-----END CERTIFICATE-----
Base64 encoding allows saving cryptographic binary data in text files that are easily copyable, shareable, and readable by any system.
7. Binary data in databases
Some databases (especially NoSQL) handle text strings better than binary blobs. Base64 lets you save images or files in text fields:
// MongoDB example
{
"_id": "user_123",
"avatar": "data:image/png;base64,iVBORw0KGgoAAAANSU...",
"name": "John Doe"
}
Pros: simplicity, portability.
Cons: +33% storage, can't query binary contents. For large files, use dedicated storage (S3, GridFS).
8. Environment variables with multiline content
Environment variables don't handle newlines well. If you need to pass a certificate or private key, Base64 solves it:
# Encode
cat private-key.pem | base64 -w 0 > key_base64.txt
# In .env
PRIVATE_KEY=LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0t...
# In code (Node.js)
const key = Buffer.from(process.env.PRIVATE_KEY, 'base64').toString();
Practical implementation
JavaScript (Browser)
// Encode string → Base64
const encoded = btoa('Hello World'); // 'SGVsbG8gV29ybGQ='
// Decode Base64 → string
const decoded = atob('SGVsbG8gV29ybGQ='); // 'Hello World'
// For Unicode (special characters)
const encodeUnicode = (str) => btoa(encodeURIComponent(str));
const decodeUnicode = (str) => decodeURIComponent(atob(str));
Node.js
// Encode
const encoded = Buffer.from('Hello World').toString('base64');
// Decode
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
// From file
const imageBase64 = fs.readFileSync('image.png').toString('base64');
Python
import base64
# Encode
encoded = base64.b64encode(b'Hello World').decode('utf-8')
# Decode
decoded = base64.b64decode(encoded).decode('utf-8')
# From file
with open('image.png', 'rb') as f:
image_base64 = base64.b64encode(f.read()).decode('utf-8')
When NOT to use Base64
- To "hide" sensitive data: Base64 is not encryption, just encoding
- For large files: the +33% size impacts performance and storage costs
- When you can use references: better a URL to a file on CDN than 100KB of inline Base64
- For compression: Base64 increases size, doesn't reduce it
Conclusion
Base64 is a simple but powerful tool when used in the right context. Remember:
- Use it to transmit binary data through text channels
- Avoid it for large files or as "security"
- The 33% overhead is the price of compatibility
Try our free Base64 tool to encode and decode strings and files instantly.