Base64 is often described as “text encoding”, but that description hides the exact boundary where most bugs happen.
Base64 does not preserve characters, fonts, or Unicode code points. It converts bytes into a safe ASCII alphabet. UTF-8 is what converts human-readable text into bytes. If you skip that first conversion, non-Latin text can fail immediately or survive visibly long enough to corrupt data later.
The one-line failure
The browser function btoa() accepts a string whose code units are in the 0–255 range. It is effectively encoding a binary string into Base64, not encoding arbitrary JavaScript text as UTF-8.
Running this in Node.js 24.17.0:
btoa("你好");
// InvalidCharacterError: Invalid character
The character “你” is a valid Unicode character but is outside that binary-string contract. A common workaround is to iterate over characters and call charCodeAt(0). That is also unsafe: UTF-16 surrogate pairs and characters above one byte do not map one-to-one to UTF-8 bytes.
The correct operation is explicit:
const text = "你好";
const bytes = new TextEncoder().encode(text);
const base64 = Buffer.from(bytes).toString("base64");
console.log(bytes); // Uint8Array(6) [228, 189, 160, 229, 165, 189]
console.log(base64); // 5L2g5aW9
“你好” is two Unicode code points, six UTF-8 bytes, and eight Base64 characters. Each of those counts describes a different layer.
Decode bytes first, then decode text
The inverse operation has the same boundary. atob() returns a binary string, not decoded UTF-8 text. Passing that binary string directly to user-facing code can appear harmless for ASCII and fail for everything else.
Use a byte buffer in the browser:
function base64ToUtf8(value) {
const normalized = value
.replace(/-/g, "+")
.replace(/_/g, "/")
.padEnd(Math.ceil(value.length / 4) * 4, "=");
const binary = atob(normalized);
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
}
base64ToUtf8("5L2g5aW9"); // "你好"
fatal: true is important. Without it, malformed input may be replaced with the Unicode replacement character instead of raising an error. Silent replacement makes a visible preview look “mostly fine” while the original bytes have already been lost.
For user-supplied data, catch the exception and show a byte-level error rather than claiming that the Base64 itself is syntactically invalid. There are two independent checks:
Does the string conform to the expected Base64 alphabet and padding?
Do the decoded bytes form valid UTF-8 for the requested text output?
They can fail independently.
Base64 and Base64URL are related, not interchangeable
Standard Base64 uses +, /, and usually =. Base64URL replaces those symbols with - and _, commonly omits padding, and is safer in URLs and JWT segments.
const value = Buffer.from("hello?~你好", "utf8").toString("base64url");
console.log(value); // aGVsbG8_fuS9oOWlvQ
const decoded = Buffer.from(value, "base64url").toString("utf8");
console.log(decoded); // hello?~你好
Do not feed a Base64URL token to an API that requires standard Base64 without normalizing it, and do not append padding blindly before checking the alphabet. A decoder should state which alphabet it accepts and reject the wrong one loudly.
A data URL contains more than Base64
An image data URL looks like this:
data:image/png;base64,iVBORw0KGgo...
The MIME prefix is metadata. It is not part of the encoded bytes. Bugs are common at this exact boundary:
Passing the entire data URL to a raw byte decoder produces invalid image bytes.
Removing the prefix but keeping URL-safe substitutions can produce a corrupt image.
Decoding text with atob() and writing that text as a “binary” file stores the Base64 characters themselves rather than the image bytes.
Trusting the MIME prefix without checking the file signature can label a JPEG as a PNG.
For a browser blob, decode Base64 into a Uint8Array, construct a Blob from the bytes, and only then create an object URL. The MIME type should come from verified metadata, not from the filename alone.
Large inputs change the failure mode
Small examples hide performance and memory problems. Base64 expands the payload by roughly one third before overhead, and the intermediate binary string can temporarily use another copy of the data.
If a pasted value is large, avoid spreading the entire byte array into String.fromCharCode(...bytes); engines impose argument-count limits. Build or stream the binary string in bounded chunks, or use a runtime API that encodes a byte buffer directly.
The same rule applies to files: validate a size limit before encoding, avoid repeated string concatenation in a loop, and release large intermediate buffers when the operation finishes.
A practical verification checklist
Before trusting an encode/decode path:
Round-trip ASCII, CJK text, emoji and combining characters.
Assert the decoded UTF-8 byte length, not only the visible string.
Test empty input and one-byte input, where padding behavior changes.
Test standard Base64 and Base64URL separately.
Reject malformed padding and disallowed characters deliberately.
Verify the first bytes for PNG, JPEG and PDF instead of trusting only a MIME label.
Compare a downloaded file with its source using a hash when correctness matters.
The useful mental model is a pipeline:
characters → UTF-8 bytes → Base64 text → transport/storage
characters ← UTF-8 bytes ← Base64 text ← transport/storage
Every arrow needs an explicit implementation. Once those layers are separated, most “Base64 corrupted my text” bugs become reproducible boundary errors rather than mysterious browser behavior.
You can inspect the same round trips locally with the JsonMind Base64 encoder and decoder. It runs in the browser and exposes the encoded value without sending the input to a server.
The author maintains JsonMind. The test outputs above were generated locally with Node.js 24.17.0.