Sub topic 10
Base64 in Node.js with Buffer
This chapter assumes you already know how UTF-8 maps code points to bytes, how Uint8Array holds bytes, and how base64 groups 3 bytes into 4 characters. It also assumes you have seen the browser workaround that sends bytes through a binary string before calling btoa. Node.js does not need that workaround. Its Buffer class converts between text, bytes, and base64 directly. It does have its own gotchas, and this chapter covers them.
What Buffer Is
Buffer is Node's built-in byte container. Since Node 4 it has been a subclass of Uint8Array, so any API that accepts a Uint8Array also accepts a Buffer. On top of the typed array, Buffer adds methods that take an encoding name. An encoding name is a string such as "utf8" or "base64" that tells Node how to interpret or produce text.
const buf = Buffer.from("héllo €", "utf8");
console.log(buf instanceof Uint8Array); // true
console.log(buf.length); // 10 (bytes, not characters)
console.log(Buffer.byteLength("héllo €", "utf8")); // 10, computed without allocating
console.log(buf); // <Buffer 68 c3 a9 6c 6c 6f 20 e2 82 ac>Buffer.byteLength is useful when you need the UTF-8 size of a string, for example for a Content-Length header, and don't need the bytes themselves.
The Encoding Names
All text conversions go through two methods. Buffer.from(string, encoding) reads a string as the given encoding and produces bytes. buf.toString(encoding) writes bytes out as a string in that encoding.
| Encoding name | What the string side holds | Typical use |
|---|---|---|
| `"utf8"` (alias `"utf-8"`) | Unicode text | Default for files, JSON, HTTP bodies |
| `"base64"` | Standard base64 with `+`, `/`, and `=` padding | MIME, data URLs, most APIs |
| `"base64url"` | URL-safe alphabet with `-` and `_`, no padding on output | JWTs, URL parameters, filenames |
| `"hex"` | Two hex digits per byte | Hashes, debugging |
| `"latin1"` (alias `"binary"`) | One character per byte, U+0000 to U+00FF | Interop with `btoa`-style binary strings |
| `"utf16le"` | Raw UTF-16 code units, little-endian | Windows APIs, some file formats |
"utf8" is the default for both methods. Buffer.from("€") and buf.toString() therefore treat the string as UTF-8. Writing the encoding explicitly still makes code easier to read.
The "base64url" encoding arrived in Node 15.7 and was backported to 14.18. On older versions you must translate the alphabet by hand, as shown in the base64url chapter.
Round-Tripping Text Through Base64
Converting Unicode text to base64 takes two steps: text to UTF-8 bytes, then bytes to base64. With Buffer, both steps fit on one line.
const text = "héllo €";
const b64 = Buffer.from(text, "utf8").toString("base64");
console.log(b64); // "aMOpbGxvIOKCrA=="
const back = Buffer.from(b64, "base64").toString("utf8");
console.log(back === text); // true
const urlSafe = Buffer.from(text, "utf8").toString("base64url");
console.log(urlSafe); // "aMOpbGxvIOKCrA" (padding dropped)
console.log(Buffer.from(urlSafe, "base64url").toString("utf8")); // "héllo €"Converting between the two alphabets also takes one line, because you can decode with one encoding name and encode with the other:
const standard = Buffer.from([0xfb, 0xff]).toString("base64");
console.log(standard); // "+/8="
const asUrl = Buffer.from(standard, "base64").toString("base64url");
console.log(asUrl); // "-_8"
console.log(Buffer.from(asUrl, "base64url").toString("base64")); // "+/8="There is no chunking loop and no spread-argument limit to worry about. toString("base64") runs in native code and handles buffers of many megabytes in a single call.
Gotcha: Decoding Is Forgiving
Node's base64 decoder never throws. Its documented behavior includes the following:
- Whitespace (spaces, tabs, newlines) is skipped, so MIME-style base64 wrapped at 76 columns decodes correctly.
- The
"base64"decoder also accepts the URL-safe characters-and_, and the"base64url"decoder accepts+and/. The two decoders are effectively the same. - Missing padding is allowed.
- Characters outside the alphabet do not cause an error. Decoding stops or skips, and you get whatever bytes it managed to recover.
console.log(Buffer.from("aGk=", "base64").toString()); // "hi"
console.log(Buffer.from("aG k\n=", "base64").toString()); // "hi" (whitespace ignored)
console.log(Buffer.from("aGk", "base64").toString()); // "hi" (no padding needed)
console.log(Buffer.from("-_8", "base64")); // <Buffer fb ff> (URL-safe chars accepted)
// No exception, even for input that is clearly not base64
const junk = Buffer.from("this is not base64!", "base64");
console.log(junk.length > 0); // true: some bytes came out anywayThis forgiving behavior is convenient for trusted input. It is a liability when base64 arrives from outside your system, such as a signature, a key, or a token field, because corrupt or tampered data turns quietly into the wrong bytes. Validate such input before decoding it.
function decodeBase64Strict(input) {
if (input.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(input)) {
throw new TypeError("Invalid base64 characters or length");
}
const buf = Buffer.from(input, "base64");
// Reject non-canonical encodings, such as nonzero leftover bits before "="
if (buf.toString("base64") !== input) {
throw new TypeError("Non-canonical base64");
}
return buf;
}
console.log(decodeBase64Strict("aGk=").toString()); // "hi"
for (const bad of ["aGk", "aG k=", "aGl="]) {
try {
decodeBase64Strict(bad);
} catch (err) {
console.log(bad, "->", err.message);
}
}
// "aGk" -> Invalid base64 characters or length
// "aG k=" -> Invalid base64 characters or length
// "aGl=" -> Non-canonical base64The round-trip check catches a subtle case. "aGl=" and "aGk=" both decode to "hi", because the last character carries 2 leftover bits that the decoder throws away. A strict check accepts only the canonical form, so each byte sequence has exactly one valid encoding.
Gotcha: Shared Memory and the Buffer Pool
To make small allocations fast, Node carves small buffers, including those created by Buffer.from(string), out of a shared pre-allocated ArrayBuffer that is usually 8 KiB. A Buffer is therefore often a window into a larger region of memory.
const small = Buffer.from("hi", "utf8");
console.log(small.length); // 2
console.log(small.buffer.byteLength); // usually 8192: the whole pool
console.log(small.byteOffset); // where "hi" starts inside the poolThe pool matters when you hand small.buffer to an API that expects an ArrayBuffer, such as crypto.subtle, a DataView, or postMessage. That API sees the entire pool, including other buffers' data. Copy out only your bytes:
const exact = small.buffer.slice(
small.byteOffset,
small.byteOffset + small.byteLength
);
console.log(exact.byteLength); // 2Going the other way, Buffer.from(uint8array) copies the bytes. To get base64 from a large Uint8Array without copying it, wrap the same memory:
const u8 = new TextEncoder().encode("€uro");
const view = Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength); // no copy
console.log(view.toString("base64")); // "4oKsdXJv"Two more differences from plain Uint8Array can surprise you:
buf.slice()returns a view that shares memory, whileUint8Array.prototype.slice()returns a copy. Node now deprecatesBuffer#slicein favor ofsubarray, which shares memory on both types. Usesubarraywhen you want a view andUint8Array.prototype.slice.call(buf)orBuffer.from(buf)when you want a copy.JSON.stringify(buf)produces{"type":"Buffer","data":[...]}rather than an object with numeric keys. To send bytes in JSON, encode them as a base64 string first.
What About btoa and atob in Node?
Node 16 added global btoa and atob for browser compatibility. They behave exactly as in the browser, including the Latin-1 limitation, and Node's documentation marks them as legacy. In Node-only code, prefer Buffer. In code shared between browsers and Node, use the native Uint8Array base64 methods covered in the next chapter, with a fallback where they are missing.
| Task | Node.js with Buffer | Notes |
|---|---|---|
| Text to base64 | `Buffer.from(s, "utf8").toString("base64")` | Any Unicode, any size |
| base64 to text | `Buffer.from(b64, "base64").toString("utf8")` | Forgiving on both steps |
| Strict decode | Validate, then decode and round-trip compare | Use `fatal` `TextDecoder` for the text step |
| Standard to URL-safe | `Buffer.from(b64, "base64").toString("base64url")` | Output has no padding |
| `Uint8Array` to base64 without copy | `Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength)` | Watch `byteOffset` |
Exercise
A webhook handler receives a header X-Signature: ZGVhZGJlZWY and calls Buffer.from(header, "base64"). A colleague says the missing = padding will cause an exception. Are they right? Would decodeBase64Strict from this chapter accept the value, and what would you change if your service must accept unpadded input but still reject garbage?
Show answer
They are wrong: Node's decoder accepts missing padding and returns the 8 bytes of "deadbeef". decodeBase64Strict would reject the value because its length (11) is not a multiple of 4. To accept unpadded input strictly, first restore the padding with input + "=".repeat((4 - (input.length % 4)) % 4) and reject any input whose length mod 4 is 1, since no valid encoding has that length. Then run the strict regex and the canonical round-trip check on the padded string.
Exercise
This code is meant to hash only the bytes of "hi", but the digest changes from run to run. Explain why and fix it: const b = Buffer.from("hi"); const digest = await crypto.subtle.digest("SHA-256", b.buffer);
Show answer
Buffer.from("hi") allocates from Node's shared pool, so b.buffer is the whole pool ArrayBuffer, usually 8192 bytes, and its other contents vary. crypto.subtle.digest hashes all of it. Pass the Buffer itself, which is a Uint8Array view whose bounds the API respects (crypto.subtle.digest("SHA-256", b)), or pass an exact copy: b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength).
Exercise
Write one expression that converts the base64url token "4oKsdXJv" to the original string, and one that converts the string "€uro" to standard padded base64.
Show answer
Buffer.from("4oKsdXJv", "base64url").toString("utf8") returns "€uro". Buffer.from("€uro", "utf8").toString("base64") returns "4oKsdXJv". The bytes are 6 long, so no padding is needed and both alphabets give the same output here.