Sub topic 3
base64url for URLs, JWTs, and Filenames
This chapter assumes you already know how to use TextEncoder and TextDecoder, and how to make base64 Unicode-safe by passing btoa one character per byte.
base64url
Standard base64 uses +, /, and =. All three have special meaning in URLs and file paths. base64url is the variant used in JWTs and URL parameters. It replaces + with - and / with _, and it usually drops the = padding. To decode base64url, map those characters back and restore the padding.
function toBase64Url(base64) {
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function fromBase64Url(base64url) {
const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
return base64 + "=".repeat((4 - (base64.length % 4)) % 4);
}
console.log(toBase64Url("a+b/cw==")); // "a-b_cw"
console.log(fromBase64Url("a-b_cw")); // "a+b/cw=="Node.js Buffer
Buffer is a subclass of Uint8Array that converts between UTF-8 text and both base64 variants directly.
const urlSafe = Buffer.from("héllo €", "utf8").toString("base64url");
console.log(Buffer.from(urlSafe, "base64url").toString("utf8")); // "héllo €"Native Uint8Array methods
Newer runtimes add toBase64 and Uint8Array.fromBase64. Check that they exist before you call them.
if (typeof Uint8Array.prototype.toBase64 === "function") {
const bytes = new TextEncoder().encode("€");
console.log(bytes.toBase64({ alphabet: "base64url", omitPadding: true })); // "4oKs"
console.log(new TextDecoder().decode(Uint8Array.fromBase64("4oKs"))); // "€"
}Decoding chunks
A network chunk can end partway through a multi-byte character. If you pass { stream: true }, the decoder keeps the incomplete bytes until the next chunk arrives. A final call with no arguments flushes whatever is left.
const decoder = new TextDecoder();
let text = decoder.decode(new Uint8Array([0xe2, 0x82]), { stream: true });
text += decoder.decode(new Uint8Array([0xac]), { stream: true });
text += decoder.decode();
console.log(text); // "€"Lone surrogates
A lone surrogate is half of a UTF-16 surrogate pair with no partner. TextEncoder replaces it with U+FFFD without any warning. To catch this, call isWellFormed() before encoding. To repair the string yourself, call toWellFormed().
const broken = "a\uD800b";
console.log(broken.isWellFormed()); // false
console.log(broken.toWellFormed() === "a\uFFFDb"); // trueChoosing an approach
| Environment | Recommended tool |
|---|---|
| Node.js | `Buffer` with `"base64"` or `"base64url"` |
| Runtime with `toBase64` | `Uint8Array` native methods |
| Older browsers | TextEncoder plus `btoa`/`atob` helpers |
Exercise
A JWT segment is "eyJhIjoxfQ". What must you do before passing it to atob?
Show answer
Replace "-" with "+" and "_" with "/" (this segment has neither), then add padding until the length is a multiple of 4. Here that gives "eyJhIjoxfQ==".