Sub topic 14
Picking the Right Tool for Your Environment
This chapter assumes you have read the earlier chapters, or already know the material they cover:
- JavaScript strings are UTF-16 code units, and UTF-8 is a byte encoding.
TextEncoderandTextDecoderconvert between strings andUint8Array.- Base64 groups 3 bytes into 4 characters and pads with
=. btoaandatobonly accept Latin-1, so you have to pass them a binary string.- base64url, Node's
Buffer, and the nativeUint8Arraybase64 methods.
None of these tools is new here. This chapter is about deciding which one to use. That decision depends on where your code runs, what kind of data you have, how large it is, and how strictly you have to validate input you don't trust.
Separate the Two Problems
Most encoding bugs happen when two separate conversions get treated as one:
- Text ↔ bytes. This step turns a string into UTF-8 bytes and back. It is always
TextEncoderandTextDecoder, orBufferwith"utf8"in Node. - Bytes ↔ base64. This step turns arbitrary bytes into ASCII text that survives JSON, URLs, headers, and email, and back again.
If you start with text and need base64, you run both steps in order: string → bytes → base64. If you start with binary data, such as a file, a hash, or a cryptographic key, you skip step 1. If you ever pass a JavaScript string straight to a base64 function, ask yourself which encoding turned that string into bytes. If you can't answer, you have a bug.
The Options Side by Side
| Tool | Where it runs | Handles any bytes | base64url built in | Invalid input on decode | Large data |
|---|---|---|---|---|---|
| `TextEncoder` / `TextDecoder` | Browsers, workers, Node, Deno, Bun | Text only (UTF-8) | n/a | Lenient by default; throws with `fatal: true` | Good; `encodeInto` and `stream` avoid extra copies |
| `btoa` / `atob` | Browsers, workers, Node 16+, Deno, Bun | Only through a binary string | No, map the characters by hand | `atob` throws `InvalidCharacterError` | Slow; builds an intermediate string |
| `Buffer` | Node, Bun, Deno (through `node:buffer`) | Yes | Yes (`"base64url"`) | Silently skips invalid characters | Fast |
| `toBase64` / `fromBase64` | Recent browsers and runtimes | Yes | Yes (`alphabet` option) | Throws `SyntaxError`; `lastChunkHandling` controls padding strictness | Fast; `setFromBase64` can decode into an existing buffer |
The Invalid input on decode column matters more than people expect. The same malformed string can throw in one tool, decode partially in another, and decode to garbage in a third.
const bad = "aGk*"; // '*' is not a base64 character
try {
atob(bad);
} catch (err) {
console.log("atob:", err.name); // "InvalidCharacterError"
}
if (typeof Buffer === "function") {
// Node skips the '*' and decodes what remains
console.log("Buffer:", Buffer.from(bad, "base64").toString()); // "hi"
}
if (typeof Uint8Array.fromBase64 === "function") {
try {
Uint8Array.fromBase64(bad);
} catch (err) {
console.log("fromBase64:", err.name); // "SyntaxError"
}
}Environment-by-Environment Guidance
Browsers and Web Workers
Use TextEncoder and TextDecoder for text in every case. For base64, prefer Uint8Array.prototype.toBase64 and Uint8Array.fromBase64 when they exist. These methods reached browsers recently, so check that the feature is present instead of assuming it. The fallback is the binary-string bridge built on btoa and atob, using chunked String.fromCharCode to stay within argument-count limits.
If you're encoding something large, such as a multi-megabyte file the user picked, think about whether you need base64 at all. fetch can send a Blob, ArrayBuffer, or FormData directly, and that avoids the 33% size overhead of base64 and the memory spike from the intermediate string.
Node.js
Buffer is the native tool, and it handles both steps: Buffer.from(str, "utf8") and buf.toString("base64url"). It is a subclass of Uint8Array, so you can pass it to any API that expects one. If your code also runs in browsers, write it against Uint8Array, TextEncoder, and the native base64 methods where possible, and use Buffer only inside Node-specific modules.
Deno, Bun, and Edge Runtimes
These runtimes provide the web APIs (TextEncoder, atob, btoa), and most also offer some form of Buffer compatibility. Edge platforms that follow WinterCG/WinterTC conventions often don't expose Buffer globally. Feature-detect instead of checking the runtime's name.
Gotchas When Mixing Buffer and Uint8Array
A Buffer can be a view into a larger shared memory pool. Node allocates small buffers from an 8 KB pool, so buf.buffer often contains bytes that belong to other buffers.
// Node.js
const buf = Buffer.from("hi", "utf8");
console.log(buf.buffer.byteLength > buf.length); // usually true (pooled)
const wrong = new Uint8Array(buf.buffer); // whole pool!
const right = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
const copy = new Uint8Array(buf); // independent copy
console.log(wrong.length, right.length, copy.length); // e.g. 8192 2 2slice also behaves differently. Buffer.prototype.slice returns a view that shares memory, while Uint8Array.prototype.slice returns a copy. Use subarray when you want a view and slice on a plain Uint8Array when you want a copy. The behavior then stays the same whichever type you are holding.
A Portable Helper Module
The functions below choose the best available implementation once. They expose a single interface that takes a Uint8Array and returns base64 or base64url. You can run them unchanged in a browser console or in Node.
const hasNativeBase64 =
typeof Uint8Array.prototype.toBase64 === "function" &&
typeof Uint8Array.fromBase64 === "function";
const hasBuffer = typeof globalThis.Buffer === "function";
function toUrlAlphabet(b64) {
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function fromUrlAlphabet(b64url) {
const b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
return b64 + "=".repeat((4 - (b64.length % 4)) % 4);
}
function bytesToBase64(bytes, { url = false } = {}) {
if (hasNativeBase64) {
return bytes.toBase64(
url ? { alphabet: "base64url", omitPadding: true } : {}
);
}
if (hasBuffer) {
const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return buf.toString(url ? "base64url" : "base64");
}
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
const b64 = btoa(binary);
return url ? toUrlAlphabet(b64) : b64;
}
function base64ToBytes(input, { url = false } = {}) {
if (hasNativeBase64) {
return Uint8Array.fromBase64(input, {
alphabet: url ? "base64url" : "base64",
});
}
if (hasBuffer) {
return new Uint8Array(Buffer.from(input, url ? "base64url" : "base64"));
}
const binary = atob(url ? fromUrlAlphabet(input) : input);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function textToBase64(text, options) {
return bytesToBase64(new TextEncoder().encode(text.toWellFormed()), options);
}
function base64ToText(input, options) {
const strict = new TextDecoder("utf-8", { fatal: true });
return strict.decode(base64ToBytes(input, options));
}
// Round trip
const token = textToBase64("héllo € 👋", { url: true });
console.log(token);
console.log(base64ToText(token, { url: true })); // "héllo € 👋"Some notes on the design:
textToBase64callstoWellFormed()so that any lone surrogate is replaced with U+FFFD visibly in your own code, instead of silently inside the encoder. If you'd rather reject such input, checkisWellFormed()and throw. Be aware thattoWellFormedis itself fairly new. On older engines, remove that call;TextEncoderstill produces valid UTF-8.base64ToTextusesfatal: true. If decoded base64 isn't valid UTF-8, the input was probably corrupted or tampered with, and insertingU+FFFDwould hide that.- The branches validate malformed base64 differently, as the earlier comparison showed. If the input comes from outside your system, validate it before calling
base64ToBytes, for example with/^[A-Za-z0-9_-]*$/for unpadded base64url.
Quick Decision Rules
| Situation | Use |
|---|---|
| String to bytes for `fetch`, `crypto.subtle`, WebSocket | `new TextEncoder().encode(str)` |
| Encoding repeatedly into a preallocated buffer | `TextEncoder.encodeInto` |
| Bytes from a network stream to text | `TextDecoder` with `{ stream: true }` or `TextDecoderStream` |
| Validating that uploaded bytes are UTF-8 | `TextDecoder` with `{ fatal: true }` |
| JWT segments, URL parameters, filenames | base64url without padding |
| Node-only server code | `Buffer` with `"base64"` / `"base64url"` |
| Cross-environment library | Feature-detected helper as above |
| Pure-ASCII string you control, quick debugging | `btoa` / `atob` directly |
| Large binary uploads | Send a `Blob` or `ArrayBuffer`; avoid base64 |
Exercise
A Node service receives a base64url token, decodes it with Buffer.from(token, "base64"), and accepts the result. An attacker sends a token containing a few * characters. What happens, and how would you fix it?
Show answer
Buffer silently skips the invalid * characters and decodes the rest, so the malformed token is accepted instead of rejected. Using "base64" instead of "base64url" also goes unnoticed, because Node accepts - and _ in both. To fix it, check the token against /^[A-Za-z0-9_-]+$/ before decoding, or re-encode the decoded bytes with toString("base64url") and reject the token if the result differs from the input.
Exercise
You run const buf = Buffer.from("abc"); crypto.subtle.digest("SHA-256", buf.buffer);. The hash doesn't match the expected SHA-256 of "abc". Why?
Show answer
buf.buffer is the whole underlying ArrayBuffer, which is often Node's shared 8 KB pool, so the digest is computed over far more than the 3 bytes. Pass buf itself (a Uint8Array view), or new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).
Exercise
In the portable helper, why does base64ToText use a TextDecoder with fatal: true, while textToBase64 calls toWellFormed instead of throwing?
Show answer
On the way in, the program owns the string, and replacing a lone surrogate with U+FFFD is a deliberate, visible repair. On the way out, the bytes come from outside, and invalid UTF-8 means corruption or tampering. Throwing reports the problem; silently substituting U+FFFD would hide it.