🍋
Menu
How-To Beginner 1 min read 262 words

Base64 Encoding: How It Works, When to Use It, and Common Pitfalls

Understand Base64 encoding — the mechanism behind data URIs, email attachments, and API payloads. Learn when Base64 is appropriate, when it wastes bandwidth, and how to handle the 33% size overhead.

Key Takeaways

  • Base64 converts binary data into a text string using 64 safe characters (A-Z, a-z, 0-9, +, /).
  • Small inline images**: Data URIs under 2KB save an HTTP request
  • Large files**: 33% overhead adds up — a 1MB file becomes 1.33MB
  • Forgetting the `data:` URI prefix (`data:image/png;base64,...`)

What Base64 Does

Base64 converts binary data into a text string using 64 safe characters (A-Z, a-z, 0-9, +, /). This allows binary data to travel through text-only channels — email (SMTP), JSON APIs, HTML attributes, and URL parameters. The tradeoff is a 33% size increase: 3 bytes of binary become 4 characters of Base64.

Encoding Variants

Variant Characters Padding Use Case
Standard (RFC 4648) A-Z, a-z, 0-9, +, / = Email, MIME
URL-safe (RFC 4648 §5) A-Z, a-z, 0-9, -, _ Optional URLs, filenames
Base64url (no padding) A-Z, a-z, 0-9, -, _ None JWT, compact tokens

When to Use Base64

  • Small inline images: Data URIs under 2KB save an HTTP request
  • Email attachments: MIME requires Base64 for binary content
  • JSON payloads: Embedding binary data in JSON fields
  • HTTP headers: Authentication tokens, encoded parameters

When NOT to Use Base64

  • Large files: 33% overhead adds up — a 1MB file becomes 1.33MB
  • Image optimization: Serve WebP/AVIF files directly instead
  • Binary protocols: gRPC, WebSocket, and HTTP/2 handle binary natively
  • Storage: Store binary files as binary, not Base64 text

Common Pitfalls

  • Forgetting the data: URI prefix (data:image/png;base64,...)
  • Mixing standard and URL-safe alphabets in the same system
  • Not stripping whitespace from Base64 copied from email sources

Encode and decode Base64 with the Peasy encoder — supports all variants with instant preview.