DEV Community

Cover image for Base64 Encoding Explained - A Practical Guide for Developers
Moksh Gupta
Moksh Gupta

Posted on • Originally published at devtoollab.com

Base64 Encoding Explained - A Practical Guide for Developers

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:

  1. Split binary data into 3-byte groups (24 bits)
  2. Divide into four 6-bit chunks
  3. 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
Enter fullscreen mode Exit fullscreen mode

For binary files in Node.js:

const fs = require('fs');
const data = fs.readFileSync('image.png');
const base64 = data.toString('base64');
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)