Base64 is one of those things every developer encounters but many never fully understand. This guide explains exactly what Base64 is, how it works, and when to use (and avoid) it.
What is Base64?
Base64 is an encoding scheme that converts binary data into ASCII text using 64 characters: A-Z, a-z, 0-9, +, and /. The = sign is used for padding.
The name "Base64" comes from the 64 characters used in the encoding โ enough to represent 6 bits per character.
How Does It Work?
// Encoding in JavaScript
btoa("Hello World") // โ "SGVsbG8gV29ybGQ="
// Decoding
atob("SGVsbG8gV29ybGQ=") // โ "Hello World"
// Node.js
Buffer.from("Hello World").toString("base64") // โ "SGVsbG8gV29ybGQ="
Buffer.from("SGVsbG8gV29ybGQ=", "base64").toString() // โ "Hello World"
Kotlin Example
import android.util.Base64
// Encode
val encoded = Base64.encodeToString("Hello World".toByteArray(), Base64.DEFAULT)
// โ "SGVsbG8gV29ybGQ=\n"
// Decode
val decoded = String(Base64.decode(encoded, Base64.DEFAULT))
// โ "Hello World"
// URL-safe Base64 (for URLs and filenames)
val urlSafe = Base64.encodeToString(data, Base64.URL_SAFE or Base64.NO_WRAP)
Common Use Cases
1. Embedding Images in CSS/HTML
/* Embed small icons directly in CSS */
.icon {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANS...");
}
2. Email Attachments (MIME)
Email protocols (SMTP) were designed for ASCII text. Base64 allows binary files like PDFs and images to be transmitted as text.
3. HTTP Basic Authentication
// HTTP Basic Auth header
const credentials = btoa("username:password");
fetch("/api/data", {
headers: { "Authorization": "Basic " + credentials }
});
4. Storing Binary Data in JSON
{
"filename": "avatar.jpg",
"data": "iVBORw0KGgoAAAANSUhEUgAA..."
}
๐ Free Base64 Tool
Encode and decode text, files and images with our free Base64 encoder/decoder. Supports URL-safe Base64 too.
Open Base64 Tool โWhen NOT to Use Base64
- Encryption โ Base64 is NOT encryption. Anyone can decode it instantly.
- Large files โ Base64 increases file size by ~33%. Serve large files directly.
- Password hashing โ Use bcrypt or Argon2 for passwords, not Base64.