Sub topic 11
Native Uint8Array Base64 Methods
This chapter assumes you know how base64 groups 3 bytes into 4 characters, how the base64url alphabet differs from standard base64, and how the btoa/atob helpers from earlier chapters work. It covers the built-in methods that replace those helpers in newer runtimes.
What the Native Methods Do
Recent JavaScript engines add base64 methods directly to Uint8Array. They work on bytes, not strings, so they never have the Latin-1 problem that btoa has. You also don't need the binary-string step.
| Method | Kind | Purpose |
|---|---|---|
| `bytes.toBase64(options)` | instance | Bytes to a base64 string |
| `Uint8Array.fromBase64(str, options)` | static | Base64 string to a new `Uint8Array` |
| `bytes.setFromBase64(str, options)` | instance | Decode into an existing array |
| `bytes.toHex()` / `Uint8Array.fromHex(str)` | both | The same conversions for hexadecimal |
const bytes = new TextEncoder().encode("€");
console.log(bytes.toBase64()); // "4oKs"
const decoded = Uint8Array.fromBase64("4oKs");
console.log(new TextDecoder().decode(decoded)); // "€"
console.log(bytes.toHex()); // "e282ac"Alphabet and Padding Options
toBase64 accepts two options:
alphabetis either"base64"(the default) or"base64url".omitPaddingisfalseby default. Set it totrueto drop the trailing=characters.
The following bytes produce the +, /, and = characters, so you can see each option change the output:
const data = new Uint8Array([0xfb, 0xff]);
console.log(data.toBase64()); // "+/8="
console.log(data.toBase64({ alphabet: "base64url" })); // "-_8="
console.log(data.toBase64({ alphabet: "base64url", omitPadding: true })); // "-_8"fromBase64 also takes alphabet. If you leave it out, the method expects standard base64, and a base64url string containing - or _ throws a SyntaxError. Pass { alphabet: "base64url" } when you decode tokens.
Strictness with lastChunkHandling
The most common mistake is assuming fromBase64 rejects all imperfect input. By default it is lenient about the final chunk. The lastChunkHandling option controls this:
"loose"(default): missing padding is accepted."strict": padding is required, and any unused bits in the last character must be zero."stop-before-partial": decoding stops before an incomplete final chunk and leaves it unread.
console.log(Uint8Array.fromBase64("aGk")); // Uint8Array [104, 105]
try {
Uint8Array.fromBase64("aGk", { lastChunkHandling: "strict" });
} catch (err) {
console.log(err.name); // "SyntaxError"
}ASCII whitespace inside the input is skipped. Any other character outside the chosen alphabet throws a SyntaxError.
Decoding into an Existing Buffer
setFromBase64 writes into a Uint8Array you already have, which avoids allocating a new array. Like TextEncoder.encodeInto, it returns how many characters it read and how many bytes it wrote.
const target = new Uint8Array(8);
const { read, written } = target.setFromBase64("aGVsbG8=");
console.log(read); // 8
console.log(written); // 5
console.log(new TextDecoder().decode(target.subarray(0, written))); // "hello"If the target is too small, the method decodes only the complete chunks that fit, and read tells you where to resume.
Feature Detection and Fallback
These methods are recent additions. Shipped versions of Firefox, Safari, and Chrome have them, but older browsers and many Node.js versions do not. Check that the method exists before you call it.
function encodeBase64(bytes) {
if (typeof Uint8Array.prototype.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);
}
console.log(encodeBase64(new TextEncoder().encode("héllo €"))); // "aMOpbGxvIOKCrA=="Exercise
You receive the JWT segment "-8" and call Uint8Array.fromBase64("-8"). What happens, and how do you fix it?
Show answer
It throws a SyntaxError because "-" and "" are not in the default standard alphabet. Call Uint8Array.fromBase64("-8", { alphabet: "base64url" }), which returns Uint8Array [251, 255]. The missing padding is accepted because lastChunkHandling defaults to "loose".
Exercise
How would you make fromBase64 reject "aGk" because its padding is missing?
Show answer
Pass { lastChunkHandling: "strict" }. That setting requires "aGk=" and throws a SyntaxError for "aGk".