Skip to main content
Back to Blog

Base64 Encoding: What It Is and How It Works

What Base64 is, when to use it for APIs and data URIs, and how to encode or decode without losing data or breaking character sets.

Kashyap Thakar
7 min
EncodingDataSecurity
Base64 Encoding: What It Is and How It Works

Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format. It's essential for sending files like images or PDFs over protocols that are designed for text, such as JSON APIs or email.

How It Works

Base64 operates by breaking binary data into 6-bit chunks. Since 2^6 is 64, each chunk can be represented by one of 64 characters:

  • A-Z (26 characters)
  • a-z (26 characters)
  • 0-9 (10 characters)
  • + and / (2 characters)

This ensures that the resulting string contains only safe, printable characters.

Common Use Cases

  • Data URIs: Embedding small images directly into HTML/CSS to reduce HTTP requests.
  • Email Attachments: MIME uses Base64 to encode file attachments.
  • Basic Authentication: HTTP Basic Auth encodes username:password in Base64.

The Trade-off

Base64 encoding increases the size of the data by approximately 33%. This is because every 3 bytes of binary data become 4 bytes of text. Therefore, it's not recommended for very large files, but it's perfect for small assets and tokens.

Base64 Variants

While standard Base64 uses + and / as the 63rd and 64th characters, there are variants for different use cases:

  • Base64URL: Uses - and _ instead of + and /, making it safe for URLs and filenames. Commonly used in JWTs and OAuth tokens.
  • Base64 with padding: Standard Base64 uses = characters for padding to ensure the output length is a multiple of 4.
  • Base64 without padding: Some implementations omit padding, but this can cause compatibility issues.

Encoding Process Step-by-Step

Understanding how Base64 encoding works helps you debug issues:

  1. Take the binary data and split it into 6-bit chunks
  2. Each 6-bit chunk represents a number from 0-63
  3. Map each number to its corresponding Base64 character (A-Z, a-z, 0-9, +, /)
  4. If the input length isn't divisible by 3, add padding with = characters
Input: "Hi"
Binary: 01001000 01101001 (16 bits)
Split into 6-bit chunks: 010010 000110 100100 (padding needed)
Decimal: 18, 6, 36
Base64: S, G, k
With padding: "SGk="

When NOT to Use Base64

While Base64 is versatile, it's not always the right choice:

  • Large files: The 33% size increase makes it inefficient for files over a few megabytes. Use direct binary transfer instead.
  • Compression: gzip can win back most of the 33% overhead (in a quick test on 1 MB of random bytes, the gzipped Base64 was about 0.4% larger than the raw data), but that is CPU spent undoing the encoding. Compress the raw binary instead if you can.
  • High-throughput paths: Encoding and decoding add CPU and memory work on every request, on top of the larger payload.
  • Encryption: Base64 is encoding, not encryption. It provides no security - anyone can decode it.

Security Considerations

It's important to remember that Base64 encoding is not encryption. It's a way to represent binary data as text, but it provides no security. Anyone can decode a Base64 string just as easily as you encoded it.

Never use Base64 to "hide" sensitive information like passwords or API keys. If you need security, use proper authenticated encryption such as AES-GCM.

Standard vs. URL-Safe Alphabet

The alphabet and padding rules are defined in RFC 4648, which specifies both the standard alphabet (section 4) and the URL and filename safe alphabet (section 5). The only difference is two characters, but it matters the moment a token ends up in a query string or a path. The bytes 0xFB 0xFF 0xFE show it clearly:

const raw = Buffer.from([0xfb, 0xff, 0xfe]);
raw.toString("base64");     // "+//+"
raw.toString("base64url");  // "-__-"

A literal + in a query string is decoded as a space by many servers, and / splits a path, so standard Base64 inside a URL must be percent-encoded or swapped for the URL-safe form. JWTs use Base64URL without padding, which is why you will never see = at the end of a JWT segment (see the JWT guide).

How Padding Works and Output Size

Base64 consumes input in groups of 3 bytes (24 bits) and emits 4 characters. If the last group is short, the encoder pads the output with = so the length is a multiple of 4:

"a"   -> YQ==   (1 byte,  2 padding chars)
"ab"  -> YWI=   (2 bytes, 1 padding char)
"abc" -> YWJj   (3 bytes, no padding)

The output length is always 4 * ceil(n / 3) characters for n input bytes, so a 3 MB file becomes a 4 MB string. The padding carries no information, which is why Base64URL as used in JWTs drops it. A decoder can recover the missing characters from the length. If a library rejects your input with an "invalid length" error, missing padding is the first thing to check.

The UTF-8 Pitfall with btoa and atob

In browsers, btoa() and atob() work on "binary strings" where every character must fit in a single byte (code points 0 to 255). Text outside that range throws, and text inside it is silently encoded as Latin-1, not UTF-8:

btoa("café");   // "Y2Fm6Q==" (Latin-1 bytes, not UTF-8)
btoa("€");      // throws InvalidCharacterError

The first result looks fine but will decode to garbage in any system that assumes UTF-8. The reliable approach is to convert text to UTF-8 bytes first and decode the same way on the way back:

const bytes = new TextEncoder().encode("€ café ✓");
const b64 = btoa(String.fromCharCode(...bytes));
// "4oKsIGNhZsOpIOKckw=="

const back = Uint8Array.from(atob(b64), (ch) => ch.charCodeAt(0));
new TextDecoder().decode(back);  // "€ café ✓"

In Node.js, Buffer.from(text, "utf8").toString("base64") does this for you. For large binary data, avoid spreading a huge array into String.fromCharCode, which can exceed the engine's argument limit. Build the string in chunks instead.

Data URIs and HTTP Basic Auth in Practice

A data URI has the form data:[mediatype];base64,<data>. It saves a request but the payload cannot be cached separately from the document that contains it, and it inflates your HTML or CSS by a third. Keep it to icons and tiny images. Larger assets are better served as normal files.

Basic Auth sends Authorization: Basic <base64(user:password)>. The classic example from the spec (RFC 7617), Aladdin:open sesame, encodes to QWxhZGRpbjpvcGVuIHNlc2FtZQ==. This is only formatting. Anyone who can see the header can read the password, so Basic Auth is acceptable only over HTTPS.

Debugging Checklist

  • Garbled characters after decoding: the text was encoded as Latin-1 or another charset but decoded as UTF-8 (or the reverse).
  • Invalid character errors: the string contains - or _ (URL-safe) but the decoder expects the standard alphabet, or it contains whitespace and line breaks that some decoders reject.
  • Invalid length errors: padding was stripped. Add = until the length is a multiple of 4.
  • Plus signs turned into spaces: the value passed through a form or query string unescaped. Use Base64URL or percent-encode it with the URL Encoder.
  • Doubled encoding: a value starting with ZXlK is usually Base64 of something that already started with eyJ, meaning it was encoded twice.

For the URL side of this, see Understanding URL Encoding and Decoding. If you need a one-way fingerprint rather than a reversible encoding, read Hashing Algorithms Explained.

Try It Yourself

Need to decode a mysterious string or encode an image for your CSS? Check out our Base64 Encoder and Base64 Decoder tools. They handle both text and file encoding/decoding, making it easy to work with Base64 in your projects.

These tools are particularly useful for:

  • Creating data URIs for embedding images in HTML/CSS
  • Debugging API responses that contain Base64-encoded data

Frequently Asked Questions

Is Base64 encryption?

No. Base64 has no key and no secret, so decoding is a mechanical reversal that anyone can perform. Treat a Base64 string as plain text with a different alphabet, and use real encryption if the data must stay confidential.

Why does Base64 end with equals signs?

The = characters are padding. They fill the final group to 4 characters when the input length is not a multiple of 3: one missing byte gives two =, two missing bytes gives one.

What is the difference between Base64 and Base64URL?

Base64URL replaces + with - and / with _ so the result can sit safely in URLs and filenames, and it often omits padding. The data it represents is identical.

How much bigger does Base64 make my data?

About one third bigger: every 3 bytes become 4 characters, plus padding. Line breaks, as used in MIME email, add a little more.

Written by

Spotted a mistake? Let me know