Sub topic 10
Base64 in Node.js with Buffer
This chapter assumes you already know three things from earlier chapters. JavaScript strings are UTF-16 code units. UTF-8 turns code points into one to four bytes. Base64 maps each group of 3 bytes to 4 characters, with = padding at the end. Browsers need the btoa workaround to do this, but Node.js has a built-in tool for it: Buffer.
What Buffer Is
Buffer is Node's byte container. It is a subclass of Uint8Array, so any API that accepts a Uint8Array also accepts a Buffer, including TextDecoder. What Buffer adds is a set of methods that convert between bytes and strings. You choose the conversion by passing an encoding name.
Encoding and Decoding
// Node.js
const text = "héllo €";
const buf = Buffer.from(text, "utf8");
console.log(text.length); // 7 (UTF-16 code units)
console.log(buf.length); // 10 (UTF-8 bytes)
console.log(Buffer.byteLength(text)); // 10, without allocating a Buffer
const b64 = buf.toString("base64");
console.log(b64); // "aMOpbGxvIOKCrA=="
const urlSafe = buf.toString("base64url");
console.log(urlSafe); // "aMOpbGxvIOKCrA" (no padding)
console.log(Buffer.from(b64, "base64").toString("utf8")); // "héllo €"
console.log(Buffer.from(urlSafe, "base64url").toString("utf8")); // "héllo €"The UTF-8 step happens inside Buffer.from, so Unicode text never causes an InvalidCharacterError. The "base64url" encoding swaps + and / for - and _ and leaves out the padding, which means you don't need the manual replace helpers.
These encoding names are the ones you will use most:
| Encoding | Meaning when decoding a string | Meaning when encoding to a string |
|---|---|---|
| `utf8` (default) | String to UTF-8 bytes | UTF-8 bytes to string |
| `base64` | Base64 text to bytes | Standard alphabet, with padding |
| `base64url` | Base64 text to bytes | URL alphabet, no padding |
| `latin1` | One byte per character, U+0000 to U+00FF | Each byte becomes one character |
| `hex` | Pairs of hex digits to bytes | Lowercase hex |
Common Errors
Expecting malformed base64 to throw
Node's base64 decoder is lenient. It accepts both alphabets, treats padding as optional, ignores whitespace, and stops at the first character that can't be decoded instead of raising an error.
console.log(Buffer.from("+/8=", "base64")); // <Buffer fb ff>
console.log(Buffer.from("-_8", "base64")); // <Buffer fb ff>
console.log(Buffer.from("aGk!!!", "base64").toString()); // "hi", no errorReading buf.buffer directly
Node allocates small Buffers from a shared memory pool, often 8 KB in size. As a result, buf.buffer can be much larger than the Buffer itself and can contain unrelated data. When you need the underlying ArrayBuffer, slice it using byteOffset and byteLength:
const small = Buffer.from("hi");
const exact = small.buffer.slice(small.byteOffset, small.byteOffset + small.byteLength);
console.log(exact.byteLength); // 2Copying when you meant to share
Buffer.from(uint8array) copies the bytes. To wrap an existing Uint8Array without copying, pass its buffer, offset, and length:
const u8 = new TextEncoder().encode("€");
const view = Buffer.from(u8.buffer, u8.byteOffset, u8.byteLength);
console.log(view.toString("base64")); // "4oKs"Because view shares memory with u8, writing to one changes the other.
Exercise
You receive the token "-_8" from a URL and call Buffer.from(token, "base64") instead of using "base64url". What bytes do you get, and why does this not fail?
Show answer
You get <Buffer fb ff>. Node's base64 decoder accepts both the standard and URL-safe alphabets and treats padding as optional, so "-_8" decodes the same way "+/8=" does. The same leniency means invalid input also decodes without an error, so validate tokens explicitly when correctness matters.
Exercise
Write one expression that returns the base64url form of the UTF-8 bytes of the string "ok?" in Node.js.
Show answer
Buffer.from("ok?", "utf8").toString("base64url"), which evaluates to "b2s_".