Sub topic 14
Picking the Right Tool for Your Environment
This chapter assumes you have read the earlier chapters. You should know how TextEncoder and TextDecoder work, why btoa needs a binary string, what base64url is, and what Node's Buffer and the native Uint8Array base64 methods do. Here those pieces come together into one decision process and one portable helper.
Two separate questions
Every encoding task asks two independent questions:
- Text to bytes or bytes to text? Use TextEncoder and TextDecoder. They work the same way in browsers, Web Workers, Node.js, Deno, and Bun, so you rarely need an alternative.
- Bytes to base64 or base64 to bytes? The best tool depends on the runtime, which is why this chapter exists.
If you keep the two questions apart, you avoid the most common bug: passing a Unicode string straight to btoa.
Decision table
| Situation | Recommended tool | Notes |
|---|---|---|
| Any runtime, string to UTF-8 bytes | `TextEncoder.encode` / `encodeInto` | Always UTF-8 |
| Any runtime, bytes to string | `TextDecoder` | Add `fatal: true` for untrusted input |
| Bytes arriving in chunks | `TextDecoder` with `stream: true` | Flush with a final `decode()` |
| Runtime has `Uint8Array.prototype.toBase64` | `toBase64` / `Uint8Array.fromBase64` | Strict decoding, base64url built in |
| Node.js without native methods | `Buffer` with `"base64"` or `"base64url"` | Lenient decoding |
| Older browsers | `btoa`/`atob` with binary-string helpers | Convert in chunks for large data |
| Strings that may hold lone surrogates | `toWellFormed()` before encoding | Or reject them with `isWellFormed()` |
A portable helper
The module below tests for each feature in order of preference. Its functions always accept and return a plain Uint8Array, so callers never need to know which implementation ran.
export function encodeBase64(bytes) {
if (typeof bytes.toBase64 === "function") {
return bytes.toBase64();
}
if (typeof Buffer !== "undefined") {
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
.toString("base64");
}
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return btoa(binary);
}
export function decodeBase64(base64) {
if (typeof Uint8Array.fromBase64 === "function") {
return Uint8Array.fromBase64(base64);
}
if (typeof Buffer !== "undefined") {
const buf = Buffer.from(base64, "base64");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
}
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
const bytes = new TextEncoder().encode("héllo €");
const b64 = encodeBase64(bytes);
console.log(b64); // "aMOpbGxvIOKCrA=="
console.log(new TextDecoder().decode(decodeBase64(b64))); // "héllo €"Two details in this code matter more than they look:
- Wrapping
Bufferwith offsets. Node allocates small buffers from a shared memory pool, sobuf.buffercan be much larger than the data itself. PassingbyteOffsetandbyteLengthgives a view of exactly the right bytes. - Returning a plain
Uint8Array.Buffer.prototype.slicereturns a view that shares memory, whileUint8Array.prototype.slicereturns a copy. If you hand callers aBufferin one runtime and aUint8Arrayin another, the same code behaves differently.
Common mistakes
- Calling
btoa(text)on user-supplied text. It works until someone types a character outside Latin-1, such as€. - Mixing base64 and base64url. A JWT segment will not decode with a plain
atobuntil you map-and_back and restore the padding. - Measuring payload size with
string.lengthinstead of the encoded byte length. - Feature-detecting once at build time instead of at runtime. Bundled code often runs in more environments than you tested.
Exercise
In the Node branch of decodeBase64, why not return Buffer.from(base64, "base64") directly, or use new Uint8Array(buf.buffer) without the offsets?
Show answer
Returning the Buffer would give callers a Uint8Array subclass whose slice method shares memory instead of copying, so code would behave differently from the other branches. Using buf.buffer without byteOffset and byteLength could expose unrelated bytes from Node's shared buffer pool, because small Buffers are views into a larger ArrayBuffer.
Exercise
You are signing data in a script that must run in an older browser and in Node.js. You need base64url output without padding. Which steps do you combine?
Show answer
Encode the text with TextEncoder. Call encodeBase64, which uses Buffer in Node and btoa with a binary string in the browser. Then turn the result into base64url by replacing + with -, / with _, and removing trailing = characters. In Node you could call Buffer's "base64url" encoding directly instead.