Why window.btoa() Throws InvalidCharacterError on UTF-8 Text
JavaScript strings are represented internally as sequences of 16-bit UTF-16 code units. Legacy browser functions btoa() and atob() were designed in the late 1990s around ISO-8859-1 (Latin1), treating each 16-bit code unit as a single byte (0x00–0xFF).
As soon as a user enters an accented character outside Latin1 (such as Turkish 'ş' or 'ğ'), CJK characters, smart quotes, or an emoji ('🚀'), its UTF-16 code unit exceeds 0xFF and btoa() throws a fatal DOMException.
The standards-compliant solution converts the string into raw UTF-8 bytes via TextEncoder() before Base64 encoding, and reverses the process with TextDecoder('utf-8', { fatal: true }) after Base64 decoding.
export function utf8ToBase64(text: string): string {
const bytes = new TextEncoder().encode(text);
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary);
}
export function base64ToUtf8(b64: string): string {
const binary = atob(b64);
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
}Standard Base64 (RFC 4648 §4) vs. URL-Safe Base64url (§5)
Standard Base64 maps 6-bit groups (0–63) onto A–Z, a–z, 0–9, '+', and '/', appending '=' characters to pad output length to a multiple of 4. Unfortunately, '+', '/', and '=' all carry reserved meanings inside URLs and HTML form submissions: '+' is decoded as a space in query strings, '/' separates path segments, and '=' separates keys from values.
Whenever embedding tokens, state hashes, or cryptographic nonces inside URLs, filenames, or HTTP headers (such as JWTs or OAuth PKCE code challenges), use Base64url (RFC 4648 Section 5), which replaces '+' with '-', '/' with '_', and strips trailing '=' padding.
encodeURIComponent() vs. encodeURI(): Preventing Query Injection
JavaScript provides two distinct percent-encoding functions that serve fundamentally different roles. encodeURI() assumes its input is an entire navigable URL (https://example.com/search?q=hello world) and therefore leaves URI structural delimiters (:, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, =) unescaped.
If you pass a user-controlled query parameter value into encodeURI()—for instance, a search term containing "R&D=true"—the raw '&' and '=' remain unescaped, injecting an extra query parameter into your backend request! Always use encodeURIComponent() (or the native URLSearchParams API) for individual parameter keys and values.
Bandwidth Overhead and Transport Trade-Offs
Because Base64 represents every 3 bytes (24 bits) of binary input as 4 ASCII characters (32 bits), it adds a deterministic 33.3% size overhead before compression. For large binary uploads (images, PDFs, audio), multipart/form-data or presigned binary PUT streams are significantly faster and consume far less memory than JSON-wrapped Base64 strings.
Web Encoding Schemes Compared: Purpose, Alphabet, and Security
| Scheme | Output Overhead | URL-Safe Directly? | Confidentiality | Ideal Use Case |
|---|---|---|---|---|
| Standard Base64 | +33% | No (+, /, = break URLs) | Zero (public encoding) | MIME email, Basic Auth, inline binary |
| Base64url (RFC 4648 §5) | +33% | Yes (- and _) | Zero (public encoding) | JWTs, OAuth PKCE, #hash state links |
| encodeURIComponent | 0% to +200% | Yes (%XX triplets) | Zero (public encoding) | Query string keys/values, path slugs |
| HTML Entity Escape | Minimal | N/A (HTML context) | Prevents HTML/XSS injection | Rendering untrusted text in markup |
Production Engineering Checklist
- Always pair btoa()/atob() with TextEncoder and TextDecoder so multi-byte Unicode characters never crash or corrupt.
- Use Base64url (- and _, unpadded) instead of standard Base64 whenever placing encoded payloads in URLs.
- Use URLSearchParams or encodeURIComponent() for query values—never encodeURI().
- Never confuse Base64 encoding with encryption; Base64 offers zero secrecy.
Frequently Asked Questions
Why do '+' characters turn into spaces when decoding query parameters?
HTML's application/x-www-form-urlencoded specification encodes spaces as '+' whereas RFC 3986 URI percent-encoding uses '%20'. URLSearchParams handles '+' as space automatically, whereas decodeURIComponent() leaves '+' literal unless normalized first.
Why does a valid Base64 string never have length % 4 === 1?
Even a single input byte (8 bits) requires two 6-bit Base64 characters (12 bits) to represent all 8 bits, so unpadded Base64 lengths modulo 4 can only ever be 0, 2, or 3—never 1.