Base64 is everywhere in modern web development - from embedding images in CSS to handling JWT tokens. Yet many developers use it without really knowing what it does. This guide breaks it down simply.
What is Base64?
Base64 is a binary-to-text encoding scheme. It converts raw binary data into a safe ASCII string using a 64-character set: A-Z, a-z, 0-9, +, and /. The = character is used for padding to keep output lengths as multiples of 4. It does not encrypt data - it just makes binary safe to transmit through text-based channels.
How It Works
Encoding happens in three steps:
- Split binary data into 3-byte groups (24 bits)
- Divide into four 6-bit chunks
- Map each chunk to a Base64 character
For example, the string "Man" becomes "TWFu" in Base64.
Common Use Cases
- Email attachments - MIME encoding uses Base64 to attach binary files
-
Data URLs - Embed images directly in HTML/CSS (e.g.,
data:image/png;base64,...) - JWT tokens - Header and payload are Base64url encoded
- API responses - Transmit binary data safely over JSON
- Basic Auth - HTTP Authorization header encodes credentials as Base64
Base64 in JavaScript
Browser and Node.js both support Base64 natively:
// Encode
const encoded = btoa('Hello World'); // SGVsbG8gV29ybGQ=
// Decode
const decoded = atob('SGVsbG8gV29ybGQ='); // Hello World
For binary files in Node.js:
const fs = require('fs');
const data = fs.readFileSync('image.png');
const base64 = data.toString('base64');
Base64url Variant
Base64url is a URL-safe variant used in JWTs. It replaces + with - and / with _, and removes = padding. This makes it safe to use in URLs and HTTP headers without encoding issues.
Key Takeaways
- Base64 is encoding, not encryption - never use it for security
- Output is roughly 33% larger than the original input
- Use it when you need to transmit binary data through text-only channels
- For JWTs and URLs, use the Base64url variant
References
- Original article: https://devtoollab.com/blog/base64-encoding-explained
- RFC 4648 - Base64 Encoding Standard: https://datatracker.ietf.org/doc/html/rfc4648
- MDN Web Docs - btoa/atob: https://developer.mozilla.org/en-US/docs/Web/API/btoa
- JWT Introduction: https://jwt.io/introduction
Top comments (0)