Base64 Use Cases: Where It Is Used in Practice
By AZ Utils Editorial · · 10 min read
Base64 shows up in more places than most developers realise — quietly powering email attachments, embedded images, authentication headers and tokens. Understanding where and why Base64 is used helps you recognise it instantly, use it appropriately, and avoid the cases where it does more harm than good. This guide walks through the most important real-world Base64 use cases with examples.
It is written for developers and engineers who want practical, applied knowledge of when to reach for Base64.
Why Encode Binary as Text at All?
The common thread across every use case is the same: a system that is fundamentally text-based needs to carry binary data. Email bodies, JSON documents, URLs, HTTP headers and HTML attributes were all designed for text. Base64 lets binary ride safely inside them by re-expressing it with 64 printable characters. With that idea in mind, the use cases practically explain themselves.
In short: Base64 is used wherever binary data must travel through a text-only channel — email attachments, data URIs, JWTs, HTTP Basic Auth and binary fields inside JSON are the most common examples.
1. Data URIs (Embedding Images and Assets)
A data URI embeds a file's bytes directly into HTML or CSS as Base64, removing the need for a separate HTTP request:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." alt="icon">
/* CSS background */
.logo { background: url("data:image/svg+xml;base64,PHN2Zy..."); }
This is ideal for tiny, frequently used assets like icons — it saves a round trip and avoids a flash of missing image. The trade-off is the 33% size increase and the fact that inlined assets cannot be cached separately, so reserve data URIs for small files.
2. Email Attachments (MIME)
Email was designed for 7-bit ASCII, so binary attachments — images, PDFs, documents — are Base64-encoded by the MIME standard before being placed in the message body:
Content-Type: application/pdf; name="invoice.pdf"
Content-Transfer-Encoding: base64
JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL...
This is arguably the original reason Base64 became ubiquitous, and it still underpins every attachment you send.
3. JSON Web Tokens (JWTs)
A JWT is three Base64url-encoded parts joined by dots: header.payload.signature. The header and payload are JSON, encoded with the URL-safe alphabet so the token can sit in URLs and headers:
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMiLCJuYW1lIjoiQWRhIn0.SflKxwRJ...
header (base64url) payload (base64url) signature
Crucially, Base64url here is encoding, not encryption — anyone can decode the payload and read its claims. That has important security implications, covered in Base64 Security Considerations.
4. HTTP Basic Authentication
Basic Auth puts the user's credentials into a header as Base64 of username:password:
Authorization: Basic YWRhOnNlY3JldA==
// decodes to "ada:secret"
Because this is trivially decodable, Basic Auth is only safe over HTTPS, which encrypts the whole request in transit. The Base64 here is purely for safe transport of the colon-separated string, not for secrecy.
5. Binary Data Inside JSON
JSON has no binary type, so when you need to put a file, image thumbnail or cryptographic blob inside a JSON payload, you Base64-encode it into a string field:
{
"filename": "avatar.png",
"contentType": "image/png",
"data": "iVBORw0KGgoAAAANSUhEUgAAAAUA..."
}
This keeps the payload valid JSON and easy to parse, at the cost of the usual size overhead. For large files, prefer a separate upload endpoint and send only a URL in the JSON.
6. Other Common Places
- PEM keys and certificates wrap Base64-encoded binary between
-----BEGIN-----and-----END-----markers. - Embedded web fonts can be inlined as Base64 in CSS.
- Opaque tokens and IDs are often Base64url-encoded so they are URL-safe.
- Webhooks and config sometimes pass small binary settings as Base64 strings.
To inspect or produce any of these by hand, use our Base64 Encoder/Decoder.
7. PEM: Keys and Certificates
Cryptographic keys and certificates are binary structures (DER-encoded), but they are almost always stored and shared in PEM format, which is simply Base64 of that binary wrapped in human-readable header and footer lines:
-----BEGIN CERTIFICATE-----
MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYD...
...many wrapped Base64 lines...
-----END CERTIFICATE-----
The Base64 here makes the key safe to paste into config files, environment variables and emails without the binary getting mangled. When a tool complains about an "invalid PEM," the cause is frequently a copy-paste error that corrupted the Base64 body or dropped the header/footer lines.
8. Storing Binary in Databases and Logs
When a data store or pipeline only handles text comfortably, small binary values are sometimes Base64-encoded into a text column or log field. This is convenient — the value becomes a plain string you can copy, diff and search — but it carries the usual 33% overhead and is less efficient than a native binary/BLOB column. As a rule: use a real binary column for substantial data, and reserve Base64-in-text for small values where portability beats efficiency. Be especially careful not to Base64-encode secrets into logs, where they become trivially recoverable by anyone with log access.
Data URIs: The Performance Trade-offs
Data URIs are the most over-used Base64 case, so they deserve a closer look. Inlining an asset removes one network request, which can help for a handful of tiny, critical icons. But it has real costs:
- Size. The asset grows by ~33%, and it cannot be compressed as effectively as separate binary files in some cases.
- No separate caching. An inlined image is re-downloaded every time the HTML or CSS changes, instead of being cached independently by the browser.
- Render-blocking CSS. Large Base64 blobs in a stylesheet bloat it and can delay rendering.
The guideline: inline only very small, above-the-fold assets (a logo, a couple of icons); serve everything else as normal cacheable files, ideally in a modern format.
A Quick Decision Guide
| Situation | Use Base64? |
|---|---|
| Tiny icon in CSS/HTML | Yes — data URI |
| Large image or video | No — serve as a cacheable file |
| Email attachment | Yes — required by MIME |
| Token in a URL/header | Yes — Base64url |
| Small binary field in a JSON API | Yes — with size limits |
| Large file upload via API | No — use multipart/binary upload |
| Storing a secret | No — encode is not encrypt |
Base64 in Web API Requests and Responses
Beyond JWTs, Base64 shows up throughout day-to-day API design. A few common patterns are worth recognising:
- Cursor-based pagination. APIs frequently return an opaque
nextCursorthat is really a Base64url-encoded blob describing the current position. Encoding it keeps the internal structure hidden and URL-safe, so clients treat it as a black box and simply pass it back. - Binary fields in JSON. Because JSON has no binary type, request and response bodies carry small binary values — a file's bytes, a signature, a thumbnail — as Base64 strings, usually alongside a content-type field so the receiver knows how to interpret them.
- Idempotency and signature headers. HMAC signatures and other binary header values are Base64-encoded so they fit cleanly into HTTP headers, which are text.
- ETags and tokens. Opaque identifiers are often Base64url so they survive being placed in URLs and headers.
When you design an API that accepts Base64 fields, always enforce a maximum length and validate the decoded content, because an attacker controls what arrives. We return to that in Base64 Security Considerations.
Base64 in Image and Document Pipelines
Image- and document-processing services often pass small assets around as Base64. A serverless function that generates a thumbnail might return it as a Base64 data string the front-end can display immediately; a PDF-generation API might accept an embedded logo as Base64 so the whole request is a single self-contained JSON document. This keeps systems loosely coupled and avoids extra round trips for small assets. The same ceiling applies as everywhere else: it works beautifully for icons, signatures and thumbnails, and badly for full-resolution photos or multi-megabyte documents, where the 33% overhead and memory cost of holding the whole asset as a string become a real problem. For those, hand off a URL and let the client fetch the binary directly.
9. Configuration, Environment Variables and Kubernetes Secrets
Configuration systems often need to carry values that contain awkward characters — multi-line certificates, JSON key files, binary credentials. Environment variables, in particular, dislike newlines. A common pattern is to Base64-encode the whole value into a single safe line:
# Encode a multi-line service-account file into one env-safe line
GOOGLE_CREDENTIALS=$(base64 -w0 service-account.json)
# ...and decode it back at runtime
echo "$GOOGLE_CREDENTIALS" | base64 -d > /tmp/sa.json
Kubernetes takes this further: the values in a Secret object are stored Base64-encoded. This is a frequent source of a dangerous misunderstanding — Base64 in a Kubernetes Secret is encoding, not encryption. Anyone who can read the Secret can decode the value instantly. Real protection comes from encryption-at-rest and access controls, not from the Base64 layer. The encoding is only there so binary values can live in a text-based manifest.
10. CI/CD Pipelines
Continuous-integration systems store secrets and files as plain-text variables, so binary artefacts — signing certificates, provisioning profiles, key files — are routinely Base64-encoded to fit. You encode the file once, paste the single-line string into the pipeline's secret store, and decode it back to a file during the build:
# Store: base64 the certificate, paste output into CI secret CERT_P12
base64 -w0 signing.p12
# Build step: reconstruct the file
echo "$CERT_P12" | base64 -d > signing.p12
This keeps binary inputs out of version control while still letting the pipeline reconstruct them on demand. The same security caveat applies: anyone with access to the pipeline's secrets can decode the value, so the protection is the secret store's access control, not the encoding.
11. Mobile, QR Codes and Deep Links
Small pieces of binary data sometimes need to ride inside a URL — a deep link, a QR code, a push-notification payload. Base64url is the natural fit because it is URL-safe and compact. A QR code might encode a Base64url token that the app decodes on scan; a deep link might carry a short encoded state blob. The key constraint here is size: URLs and QR codes have practical length limits, and Base64's 33% overhead eats into them quickly, so this works only for genuinely small payloads. For anything larger, pass an identifier and fetch the real data from a server.
Common Mistakes
- Base64-encoding large files into data URIs or JSON. The 33% bloat and loss of caching hurt performance — use real binary transfers for big assets.
- Putting secrets in a JWT payload. It is only Base64url-encoded, so the payload is readable by anyone.
- Relying on Basic Auth without HTTPS. The credentials are effectively in the clear.
- Using the wrong alphabet. Standard Base64 in a URL can break because of
+and/; use Base64url.
A Mental Model for Choosing Base64
Across all of these use cases, a single mental model keeps you out of trouble. Picture the journey your data needs to take and ask three questions in order. First: is the data binary, and does it need to pass through a text-only channel? If not — if the channel already handles binary, or the data is already text that just needs escaping — Base64 is not the answer, and a binary transfer or URL encoding fits better. Second: is the payload small? Base64's roughly one-third size increase is negligible for an icon, a token or a thumbnail, but it becomes a genuine performance and memory problem for large images, documents or files, which belong in a separate upload referenced by URL. Third: am I trying to protect the data? If so, stop — Base64 is the wrong tool, and you need encryption, hashing or access control instead.
Run those three checks and almost every real situation sorts itself cleanly. A tiny inline icon: binary, text channel, small, not secret — Base64 via a data URI is ideal. A multi-megabyte product photo in an API: binary and text channel, but large — send a URL instead. A password in a config file: the moment "protect" enters the picture, Base64 is disqualified and encryption takes over. The use cases differ on the surface, but they are all answered by the same short line of reasoning, which is why seasoned developers reach for Base64 confidently in some places and instinctively avoid it in others.
The reason this matters is that the failures around Base64 are rarely about getting the encoding wrong — libraries handle that flawlessly. They are about applying it in the wrong situation: bloating a page with a huge data URI, or worse, mistaking encoding for protection. A clear mental model prevents both.
Best Practices
- Inline only small assets. Data URIs are great for icons, poor for photos.
- Use Base64url for URLs, filenames and tokens.
- Pair Base64 with TLS for anything sensitive — it provides no confidentiality itself.
- Send large binaries out-of-band (separate upload) and reference them by URL in JSON.
- Set the correct MIME type in data URIs so browsers render them properly.
Frequently Asked Questions
What is Base64 commonly used for?
Common uses include email attachments (MIME), data URIs that embed images in HTML/CSS, JSON Web Tokens, HTTP Basic Authentication headers, PEM keys and putting binary data inside JSON.
Should I embed images as Base64 data URIs?
Only for small, frequently used assets like icons. Larger images suffer from the 33% size increase and cannot be cached separately, so a normal image URL is usually better.
Why are JWTs Base64-encoded?
JWTs use Base64url so their JSON header and payload can travel safely in URLs and HTTP headers. Note this is encoding, not encryption — the payload is readable by anyone.
Is Base64 in HTTP Basic Auth secure?
No, not on its own. The credentials are only Base64-encoded, which is trivially reversible. Basic Auth is only safe over HTTPS, which encrypts the request in transit.
How do I store binary data in JSON?
Base64-encode the binary into a string field, since JSON has no binary type. For large files, store them separately and reference a URL instead.
When should I avoid Base64?
Avoid it for large files where binary transfer is possible, and never use it as a security measure — it provides no confidentiality.
Summary
Base64's use cases all come down to one need: carrying binary safely through text-based channels. That makes it the backbone of email attachments, data URIs, JWTs, Basic Auth and binary-in-JSON. The same properties that make it useful — universal, reversible, text-friendly — also define its limits: it adds about a third to the size and offers zero secrecy. Use it for small payloads and safe transport, pair it with real encryption and TLS for anything sensitive, and keep large binaries out of it.
If there is one habit to take away, it is to pause before encoding and ask whether the data is small and genuinely needs to travel as text. That single question separates the cases where Base64 shines — icons, tokens, attachments, certificates, small JSON fields — from the cases where it quietly hurts, like inlining large images or pushing big files through an API as strings. Get that judgement right and Base64 becomes one of the most useful, low-friction tools in your toolkit; get it wrong and it becomes a performance tax or a false sense of security. The encoding itself is never the hard part — choosing where to apply it is.
👉 Encode or decode Base64 now →
Related Resources
- What Is Base64? — the fundamentals
- How Base64 Encoding Works — the algorithm
- Base64 Security Considerations — encoding is not encryption
- Base64 Encoder/Decoder — the tool