Developer Tools

Using Base64 in JSON REST APIs the Right Way

7 min read
By
Using Base64 in JSON REST APIs the Right Way

Pexels

## The Binary Problem in JSON

JSON has strings, numbers, booleans, arrays, objects, and null. It does not have a byte type. So when your API needs to return a binary blob — a generated PDF, a thumbnail, a signature, a hash — you have two choices.

Return a URL and make the client fetch the bytes separately. Or encode the bytes as a Base64 string and return them inline. The second option is one round trip, no extra endpoint, no CORS. It is also the source of a surprising number of bugs.

I have seen both approaches go wrong. The URL approach fails when the storage bucket goes down and the client has a JSON response pointing to a 404. The Base64 approach fails when a developer forgets the MIME type and the client tries to open a PDF as a JPEG. Both are fixable. The key is knowing which trade you are making.

Encode JSON to Base64

The pattern is simple: turn the binary field into Base64 before you serialize the JSON:

javascript const pdfBytes = generatePdf(); const payload = { id: "doc_123", mime: "application/pdf", data: pdfBytes.toString("base64") }; const json = JSON.stringify(payload);

The data field is now a plain JSON string. Any client can parse it. No binary corruption, no escaped control characters, no encoding headaches in the transport layer. The JSON is valid JSON everywhere.

Decode a Base64 JSON Response

On the client, parse the JSON, then decode the Base64 field back to bytes:

javascript const res = await fetch("/api/documents/123"); const payload = await res.json(); const bytes = Uint8Array.from( atob(payload.data), c => c.charCodeAt(0) ); const blob = new Blob([bytes], { type: payload.mime });

The MIME type travels alongside the data. That is not a convenience — it is required. Base64 alone tells you nothing about what the bytes represent. Without the MIME type, the client is guessing.

A Real API Payload

Here is what a thumbnail endpoint might return:

json { "id": "img_8821", "width": 200, "height": 200, "mime": "image/webp", "data": "UklGRiQAAABXRUJQVlA4ICgAAACwA..." }

The client knows the dimensions, the type, and the bytes. One request, one response, one image rendered. Compare that to a URL-only response that needs a second fetch and a second round of headers. For a dashboard that loads 20 thumbnails, that is 20 saved requests.

The Size Tax, Quantified

Base64 inflates bytes by 4/3. A 300 KB image becomes a 400 KB string. That string is then JSON-escaped and sent over HTTP, where it may be gzipped back down — but the JSON parse on the client still has to handle the full 400 KB string in memory before it can decode.

For small payloads under a few hundred KB, this is a fine trade. For a 5 MB video, you are shipping 6.66 MB of Base64 and forcing the client to hold it all in memory before decoding. At that scale, a presigned upload URL and a separate binary endpoint win. The line is somewhere around 1-2 MB. Below it, inline is simpler. Above it, use a URL.

Common API Mistakes

**No MIME type.** Returning { "data": "..." } with no type forces the client to guess or sniff. Always include mime or content_type. This is the most common mistake, and it is the easiest to fix.

**Mixing text and binary in one field.** If a field can be either a UTF-8 string or Base64 bytes, clients have to detect which. Pick one. If you need both, use two fields. Ambiguity in an API contract is always a bug waiting to happen.

**Trusting the length.** A Base64 string with a stray newline in the middle is valid-looking but will fail to decode. Validate lengths are a multiple of 4 (after stripping whitespace) on receive. Better: strip whitespace before validating.

**Forgetting padding.** Some serializers strip the trailing = padding. Some clients do not re-add it. Standardize on padded output, or document that your API strips it. Inconsistency here causes intermittent decode failures that are miserable to debug.

When to Use Base64 in JSON

- Small binary blobs under a few hundred KB. - One-shot responses where a second fetch would add latency. - Webhooks and callbacks where you control both ends and want atomic payloads. - Embedding hashes, signatures, or small previews inline.

When Not to Use It

- Large media files. Use a URL. - Streaming. Base64 is not a stream format. - Anything secret. Base64 is not encryption — see Base64 is not encryption for why hiding data behind Base64 buys you nothing.

A Note on JWTs

JSON Web Tokens use Base64 in a specific way — three Base64 segments joined by dots. If you are debugging auth, the decode JWT tokens by hand post walks through that format in detail. The JWT spec uses URL-safe Base64, which avoids the + and / characters that cause problems in URLs and headers.

Quick Reference

- Encode: bytes.toString("base64") before JSON.stringify. - Decode: Uint8Array.from(atob(field), c => c.charCodeAt(0)) after JSON.parse. - Always carry the MIME type alongside the data. - Size: ~33% larger than the raw bytes. - Best for small blobs; worst for large media.

Try it with the NovelCrypt Base64 encoder, and for the URL-safe variant that avoids + and / problems, read URL-safe Base64 encoding.,

Frequently Asked Questions

How do I encode binary data in a JSON API response?

Convert the binary bytes to a Base64 string with bytes.toString('base64') before JSON.stringify, and include the MIME type in a separate field. The client parses the JSON and decodes the Base64 field back to bytes.

How do I decode a Base64 field from a JSON response?

Parse the JSON with JSON.parse, then convert the Base64 string to bytes with atob (browser) or Buffer.from(b64, 'base64') (Node). Use the MIME type from the response to reconstruct the file correctly.

Should I use Base64 in JSON for large files?

No. Base64 adds about 33% to the size and forces the client to hold the whole string in memory. For large files, return a URL and let the client fetch the binary separately, or use a presigned upload endpoint.

Try NovelCrypt Tools

Experience military-grade encryption for your sensitive data. Create self-destructing messages, encrypt files, or explore our experimental lab tools.

Explore NovelCrypt