Skip to main content

Command Palette

Search for a command to run...

Base64 Encoding Explained - What Every Developer Should Know

Updated
2 min read
Base64 Encoding Explained - What Every Developer Should Know

Base64 is everywhere in modern web development - from image embedding to JWT tokens. Yet many developers use it without fully understanding what it does or why. This guide breaks it down clearly and concisely.

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 /. Padding with = ensures output lengths are always 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. Binary input is split into 3-byte (24-bit) chunks

  2. Each 24-bit group is divided into four 6-bit values

  3. Each 6-bit value maps to a character in the Base64 alphabet

If the input is not divisible by 3, = padding is added to complete the final group.

Common Use Cases

  • Embedding images - Small images get converted to Data URLs, eliminating extra HTTP requests

  • API responses - Binary files like PDFs or images are often returned as Base64 strings inside JSON

  • HTTP Basic Auth - Credentials are Base64-encoded in the Authorization header

  • JWT tokens - Header, payload, and signature are all Base64url-encoded

Quick Implementation Reference

JavaScript

btoa('hello')       // encode
atob('aGVsbG8=')    // decode

For Unicode strings, use btoa(unescape(encodeURIComponent(str))).

Python

import base64
base64.b64encode(b'hello')
base64.b64decode('aGVsbG8=')

PHP

base64_encode('hello');
base64_decode('aGVsbG8=');

Standard vs URL-Safe Variant

The standard Base64 uses + and /, which break URL query strings. The URL-safe variant replaces + with - and / with _, and drops the = padding. This is what JWT and most modern APIs use.

What Developers Often Get Wrong

Base64 is not encryption. It provides zero security. Anyone can decode it instantly. Never use it to hide sensitive data.

It increases file size by ~33%. Encoding 1 MB of binary produces roughly 1.37 MB of text. For large assets, this overhead is worth avoiding.

Conclusion

Base64 is a practical encoding tool, not a security measure. Knowing when to use it - and when to avoid it - is a small but useful part of any developer's toolkit.

References

More from this blog

Moksh's blog

39 posts