Sub topic 11
Native Uint8Array Base64 Methods
This chapter assumes you have read the earlier chapters on TextEncoder, TextDecoder, how base64 works, the btoa/atob workaround, base64url, and Node's Buffer. You should be comfortable with Uint8Array, destructuring, and try/catch.
The btoa-based helpers from earlier chapters work, but they make a round trip through a "binary string" that nobody actually wants. The newer Uint8Array base64 methods remove that step. They convert bytes to base64 and back directly, they support base64url natively, and they let you choose how strict decoding should be.
What the API Adds
The proposal adds four methods for base64 and three matching methods for hexadecimal:
| Method | Kind | Input | Output |
|---|---|---|---|
| `bytes.toBase64(options)` | instance | `Uint8Array` | base64 string |
| `Uint8Array.fromBase64(string, options)` | static | base64 string | new `Uint8Array` |
| `bytes.setFromBase64(string, options)` | instance | base64 string | `{ read, written }`, writes into `bytes` |
| `bytes.toHex()` | instance | `Uint8Array` | lowercase hex string |
| `Uint8Array.fromHex(string)` | static | hex string | new `Uint8Array` |
| `bytes.setFromHex(string)` | instance | hex string | `{ read, written }` |
These methods exist only on Uint8Array. Uint16Array, DataView, and a raw ArrayBuffer do not get them. If you hold an ArrayBuffer, wrap it first with new Uint8Array(buffer).
As of late 2025, the methods ship in Firefox 133, Safari 18.2, Chrome 140, and runtimes built on matching engine versions such as Node.js 25. Older runtimes still in use do not have them, so feature detection is required.
Encoding with toBase64
The simplest call takes no arguments and produces standard, padded base64:
const bytes = new TextEncoder().encode("€");
console.log(bytes.toBase64()); // "4oKs"
const raw = new Uint8Array([0xfb, 0xff]);
console.log(raw.toBase64()); // "+/8="
console.log(raw.toBase64({ alphabet: "base64url" })); // "-_8="
console.log(raw.toBase64({ alphabet: "base64url", omitPadding: true })); // "-_8"Two options control the output:
alphabetis"base64"(the default, using+and/) or"base64url"(using-and_).omitPaddingisfalseby default. Set it totrueto drop the trailing=characters.
The two options are independent. Standard base64 without padding and base64url with padding are both allowed, although JWTs and most URL uses expect base64url without padding.
Decoding with fromBase64
Uint8Array.fromBase64 returns a new array. It accepts the same alphabet option plus a lastChunkHandling option, covered below.
const a = Uint8Array.fromBase64("+/8=");
console.log(a); // Uint8Array(2) [251, 255]
const b = Uint8Array.fromBase64("-_8", { alphabet: "base64url" });
console.log(b); // Uint8Array(2) [251, 255]
const text = new TextDecoder().decode(Uint8Array.fromBase64("aGVs\nbG8="));
console.log(text); // "hello" (ASCII whitespace is skipped)Gotcha: the alphabet is strict
The decoder does not guess the alphabet. Characters from the other alphabet cause a SyntaxError:
try {
Uint8Array.fromBase64("-_8"); // default alphabet is "base64"
} catch (err) {
console.log(err.name); // "SyntaxError"
}
try {
Uint8Array.fromBase64("+/8=", { alphabet: "base64url" });
} catch (err) {
console.log(err.name); // "SyntaxError"
}This differs from Node's Buffer.from(str, "base64"), which accepts both alphabets and silently skips characters it does not recognize. If your input can arrive in either form, for example tokens pasted by users, normalize it first with the fromBase64Url-style mapping from the base64url chapter. Another option is to try one alphabet and fall back to the other.
Gotcha: errors are SyntaxError, not InvalidCharacterError
atob throws a DOMException named InvalidCharacterError. The native methods throw a plain SyntaxError. If you replace atob with fromBase64, update any error handling that checks err.name.
Controlling the Final Chunk with lastChunkHandling
Base64 decodes in groups of 4 characters. The last group is where malformed or truncated input shows up. The lastChunkHandling option decides what happens there.
| Value | Missing padding | Non-zero leftover bits | Incomplete final group |
|---|---|---|---|
| `"loose"` (default) | accepted | accepted, bits ignored | decoded if 2 or 3 chars |
| `"strict"` | `SyntaxError` | `SyntaxError` | `SyntaxError` |
| `"stop-before-partial"` | final group left undecoded | accepted | left undecoded |
"Leftover bits" means the unused low bits in the last character. In "aGk=" those bits are zero. In "aGl=" they are not. A careful encoder never produces "aGl=", but a loose decoder still reads it as "hi".
const opts = { lastChunkHandling: "strict" };
console.log(Uint8Array.fromBase64("aGk=", opts)); // Uint8Array(2) [104, 105]
for (const input of ["aGk", "aGl="]) {
try {
Uint8Array.fromBase64(input, opts);
} catch (err) {
console.log(input, err.name); // "aGk SyntaxError", then "aGl= SyntaxError"
}
}
console.log(Uint8Array.fromBase64("aGl=")); // Uint8Array(2) [104, 105] (loose)Use "strict" when the base64 string is compared, hashed, or used as a canonical identifier. Under loose decoding, "aGk=", "aGk", and "aGl=" all produce the same bytes. If your system treats different strings as different values but decodes them to identical bytes, an attacker can make two "different" tokens that mean the same thing.
Decoding into an Existing Buffer with setFromBase64
setFromBase64 writes into the array you call it on and returns { read, written }. This mirrors TextEncoder.encodeInto: read counts input characters consumed and written counts bytes stored.
const target = new Uint8Array(16);
const { read, written } = target.setFromBase64("aGVsbG8gd29ybGQ=");
console.log(read, written); // 16 11
console.log(new TextDecoder().decode(target.subarray(0, written))); // "hello world"If the target is too small, the method decodes only the complete groups that fit, then stops. read tells you where to resume. This avoids allocating a fresh array for every message when you decode many payloads into a reusable buffer.
Streaming base64 with stop-before-partial
When base64 text arrives in pieces, a piece can end in the middle of a 4-character group. "stop-before-partial" decodes every full group and leaves the tail unread, so you can carry it into the next piece:
const pieces = ["aGVsbG", "8gd29y", "bGQ="];
const out = new Uint8Array(32);
let carry = "";
let total = 0;
for (let i = 0; i < pieces.length; i++) {
const input = carry + pieces[i];
const isLast = i === pieces.length - 1;
const { read, written } = out.subarray(total).setFromBase64(input, {
lastChunkHandling: isLast ? "strict" : "stop-before-partial",
});
total += written;
carry = input.slice(read);
}
console.log(new TextDecoder().decode(out.subarray(0, total))); // "hello world"The last piece switches to "strict" so that truncated input fails instead of silently losing bytes. This is the base64 counterpart of the stream: true pattern for TextDecoder covered in the chunked-decoding chapter. If you decode the resulting bytes as UTF-8 piece by piece, you still need the decoder's streaming mode, because a 3-byte group boundary has no relation to a UTF-8 character boundary.
Hex Methods
The same proposal adds hexadecimal conversion, which is common for hashes and debugging:
const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
console.log(bytes.toHex()); // "deadbeef"
console.log(Uint8Array.fromHex("DEADBEEF")); // Uint8Array(4) [222, 173, 190, 239]
try {
Uint8Array.fromHex("abc"); // odd length
} catch (err) {
console.log(err.name); // "SyntaxError"
}toHex always produces lowercase output. fromHex accepts either case but rejects odd lengths, whitespace, and non-hex characters.
Feature Detection and a Portable Wrapper
Detect each method you call. Do not assume that one implies the others, even though they shipped together in current engines. Polyfills and partial implementations exist.
The wrapper below exposes one interface and picks the implementation once. It runs as shown in browsers and Node.js.
const hasNative =
typeof Uint8Array.prototype.toBase64 === "function" &&
typeof Uint8Array.fromBase64 === "function";
const hasBuffer = typeof globalThis.Buffer === "function";
function encodeBase64(bytes, { url = false } = {}) {
if (hasNative) {
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 = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
const b64 = btoa(binary);
return url
? b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
: b64;
}
function decodeBase64(text, { url = false } = {}) {
if (hasNative) {
return Uint8Array.fromBase64(text, {
alphabet: url ? "base64url" : "base64",
});
}
if (hasBuffer) {
return new Uint8Array(Buffer.from(text, url ? "base64url" : "base64"));
}
let b64 = url ? text.replace(/-/g, "+").replace(/_/g, "/") : text;
b64 += "=".repeat((4 - (b64.length % 4)) % 4);
const binary = atob(b64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
const token = encodeBase64(new TextEncoder().encode("héllo €"), { url: true });
console.log(token); // "aMOpbGxvIOKCrA"
console.log(new TextDecoder().decode(decodeBase64(token, { url: true }))); // "héllo €"Notice the Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) call. Passing bytes.buffer alone would encode the entire underlying buffer, including bytes outside the view.
Common Mistakes
- Calling
toBase64on anArrayBuffer. It is aUint8Arraymethod. Wrap the buffer first:new Uint8Array(buffer).toBase64(). - Calling
fromBase64on an instance. It is static:Uint8Array.fromBase64(s), notbytes.fromBase64(s). The instance form issetFromBase64. - Passing a string to
toBase64. The method encodes bytes, not text. Run the string throughTextEncoderfirst. - Expecting
omitPaddingon decode. Decoding has noomitPaddingoption. Loose mode already accepts missing padding, and strict mode always requires it. - Mixing alphabets. Decoding base64url without
{ alphabet: "base64url" }throws on-and_.
Exercise
You receive the JWT payload segment "eyJzdWIiOiLimqEifQ". Write one expression using the native methods that turns it into a JavaScript string, and explain why adding { lastChunkHandling: "strict" } would break it.
Show answer
new TextDecoder().decode(Uint8Array.fromBase64("eyJzdWIiOiLimqEifQ", { alphabet: "base64url" })) returns '{"sub":"⚡"}'. JWT segments are base64url without padding. Strict mode requires the final group to be padded to 4 characters, and this 18-character segment ends in an incomplete 2-character group, so strict decoding throws a SyntaxError.
Exercise
A cache uses base64 strings received from clients as keys after decoding and re-encoding them for storage. Two clients send "aGk=" and "aGl=". What does Uint8Array.fromBase64 return for each with default options, and which option makes the server reject the second one?
Show answer
Both decode to Uint8Array [104, 105] ("hi") because loose mode ignores the non-zero leftover bits in "l". Passing { lastChunkHandling: "strict" } makes "aGl=" throw a SyntaxError while "aGk=" still decodes, so each byte sequence has exactly one accepted string form.
Exercise
A buffer out has room for 3 bytes. What do out.setFromBase64("aGVsbG8", { lastChunkHandling: "stop-before-partial" }) return and write, and why?
Show answer
It returns { read: 4, written: 3 } and writes [104, 101, 108] ("hel"). The first group "aGVs" decodes to 3 bytes, which fills the buffer. The remaining "bG8" is an incomplete group, which stop-before-partial leaves unread, so read points to the start of "bG8" for the next call.
I printed the chapter here instead of writing it to content-inbox-jsv2-w7/01a2122f-f855-71da-9a69-a676c87bd40c/answers/derive__in_depth__10.md, because the request says the printed reply is saved as the answer. None of the code was run. The browser and Node.js version numbers come from memory and should be checked before publishing.