If you've worked with APIs, email protocols, or web development, you've encountered Base64. It shows up in JWT tokens, data URIs, email attachments, and countless API payloads. But why does it exist, and when should you actually use it?
What Base64 Does
Base64 is a binary-to-text encoding. It takes any binary data — an image, a PDF, a string of bytes — and converts it into a string of printable ASCII characters. The output uses only 64 characters: A–Z, a–z, 0–9, +, and /, with = for padding.
"CrispTool" → Q3Jpc3BUb29s
[binary image data] → /9j/4AAQSkZJRgABAQ...
Every 3 bytes of input become 4 bytes of output. This means Base64-encoded data is always approximately 33% larger than the original. That's the cost of text-safe transport.
Why It Exists
Many protocols and formats were designed to handle only text — specifically, 7-bit ASCII text. Email (SMTP) is the classic example: it was built in the 1970s for plain English text. Binary data like images contains bytes outside the ASCII range that would corrupt or be stripped by these systems. Base64 solves this by encoding binary data using only safe ASCII characters.
Common Use Cases
Data URIs: embedding small images directly in HTML or CSS without a separate HTTP request. background-image: url(data:image/png;base64,iVBOR...). This reduces requests but increases page size by 33%.
JWT tokens: JSON Web Tokens encode their header and payload as Base64URL (URL-safe variant) strings separated by dots. The token is text-safe and can be passed in HTTP headers or URL parameters.
Email attachments: MIME encoding uses Base64 to embed binary files in text-based email messages. When you "attach" a file to an email, it's Base64-encoded behind the scenes.
API payloads: when an API needs to accept binary data in a JSON body, Base64 encoding the data is the standard approach since JSON only supports text.
Basic authentication: HTTP Basic Auth encodes "username:password" as Base64 in the Authorization header. Note: this is encoding, not encryption — the credentials are trivially reversible.
Standard vs. URL-Safe Base64
Standard Base64 uses + and / characters, which have special meaning in URLs. URL-safe Base64 (also called Base64URL) replaces + with - and / with _. JWT tokens use Base64URL. If you're putting Base64 in a URL, query parameter, or filename, always use the URL-safe variant.
When NOT to Use Base64
Don't use Base64 for large files. The 33% size overhead is significant for anything over a few kilobytes. Serve images as regular files, not data URIs, unless they're tiny icons. Don't use Base64 as a security measure — it's trivially reversible and provides zero protection. Don't Base64-encode data that's already text — you're just making it bigger and less readable for no benefit.