Sub topic 9
base64url for URLs, JWTs, and Filenames
This chapter assumes you have read the earlier chapters on how base64 groups 3 bytes into 4 characters, and on converting a Uint8Array to base64 through a binary string with btoa and atob. You should be comfortable with regular expressions and with TextEncoder and TextDecoder. Node's Buffer and the native Uint8Array.prototype.toBase64 method also support base64url, and later chapters cover them. This chapter builds the variant by hand so you can see where each part comes from.
Why standard base64 breaks outside plain text
The standard base64 alphabet uses A–Z, a–z, 0–9, + and /, and it pads with =. Three of those characters have special meanings in other places:
| Character | Problem in URLs | Problem in filenames |
|---|---|---|
| `+` | Form-style query parsing (`application/x-www-form-urlencoded`, `URLSearchParams`) reads it as a space | Usually allowed |
| `/` | Splits a path into segments | Is the directory separator on Unix, and Windows treats it as one too |
| `=` | Separates a key from its value in query strings | Allowed, but awkward in shell scripts |
The + problem causes the most damage because nothing reports an error. The value just comes back changed:
const token = "a+b/cw==";
const url = new URL("https://example.com/verify?t=" + token);
console.log(url.searchParams.get("t")); // "a b/cw==" (the + became a space)The server receives a b/cw==, the decode fails or yields different bytes, and the bug shows up only for tokens that happen to contain +. In practice that means it appears in production and almost never in testing.
The base64url alphabet
RFC 4648, section 5, defines "base64url" as the same encoding with two characters replaced:
| Index | Standard base64 | base64url |
|---|---|---|
| 0–61 | `A–Z a–z 0–9` | `A–Z a–z 0–9` (unchanged) |
| 62 | `+` | `-` |
| 63 | `/` | `_` |
| padding | `=` | usually omitted |
The bit layout does not change. Each 6-bit group maps to the same index, and only the symbol at index 62 or 63 is different. Because of that, converting between the two forms is a simple character substitution and needs no re-encoding.
The RFC allows padding in base64url, but most formats built on it drop it. JWT (RFC 7515) requires padding to be removed. Drop it by default, and keep it only when a spec explicitly asks for it.
Restoring padding and why length mod 4 can never be 1
Unpadded base64 encodes n bytes into ceil(4n / 3) characters. The remainder n % 3 decides how the output ends:
| `n % 3` | Characters in last group | Unpadded length `% 4` | Padding to add |
|---|---|---|---|
| 0 | 4 | 0 | none |
| 1 | 2 | 2 | `==` |
| 2 | 3 | 3 | `=` |
A remainder of 1 never appears. A single leftover character carries only 6 bits, which is not enough to finish a byte. If a base64url string has length % 4 === 1, it was truncated or corrupted, so reject it instead of padding it. The expression (4 - (len % 4)) % 4 gives 0, 2 or 1 for the valid remainders.
Complete browser helpers
The helpers below build on the chunked binary-string bridge from the earlier chapter. They run unchanged in browsers, Deno, Bun, and Node 16 or later, all of which provide global btoa and atob.
function bytesToBase64(bytes) {
let binary = "";
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function bytesToBase64Url(bytes) {
return bytesToBase64(bytes)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
function base64UrlToBytes(input) {
if (!/^[A-Za-z0-9_-]*$/.test(input)) {
throw new SyntaxError("Invalid base64url character");
}
if (input.length % 4 === 1) {
throw new SyntaxError("Invalid base64url length");
}
const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
const padded = base64 + "=".repeat((4 - (base64.length % 4)) % 4);
return base64ToBytes(padded);
}
// 0xfb 0xff uses indexes 62 and 63, so it shows both swapped characters
const bytes = new Uint8Array([0xfb, 0xff]);
console.log(bytesToBase64(bytes)); // "+/8="
console.log(bytesToBase64Url(bytes)); // "-_8"
console.log(base64UrlToBytes("-_8")); // Uint8Array(2) [251, 255]The validation regex is intentionally strict. It rejects =, +, / and whitespace, so input in the wrong format fails with a clear error instead of being decoded silently. If you need to accept both forms, for example from an old client that sends standard base64, normalise the input explicitly before calling the helper. Do not loosen the regex.
Encoding Unicode text as base64url
Text always passes through UTF-8 first. Passing a string straight to btoa fails on any character above U+00FF, as shown earlier in this tutorial.
function textToBase64Url(text) {
return bytesToBase64Url(new TextEncoder().encode(text));
}
function base64UrlToText(input) {
const decoder = new TextDecoder("utf-8", { fatal: true });
return decoder.decode(base64UrlToBytes(input));
}
const encoded = textToBase64Url("Zoë → café");
console.log(base64UrlToText(encoded)); // "Zoë → café"The fatal: true option matters when the input comes from outside your code. A tampered token should throw an error. It should not decode into a string full of U+FFFD replacement characters that later code then treats as valid.
Reading a JWT
A JSON Web Token (JWT) has three base64url segments joined by dots: header.payload.signature. The header and payload are UTF-8 JSON. The signature is raw bytes. The example below builds an unsigned token so it runs without any secret key, and then decodes it.
function encodeJson(value) {
return textToBase64Url(JSON.stringify(value));
}
function decodeJwtUnverified(token) {
const parts = token.split(".");
if (parts.length !== 3) {
throw new SyntaxError("A JWT has exactly three segments");
}
const [header, payload] = parts.slice(0, 2).map((p) => JSON.parse(base64UrlToText(p)));
return { header, payload, signature: base64UrlToBytes(parts[2]) };
}
const token = [
encodeJson({ alg: "none", typ: "JWT" }),
encodeJson({ sub: "123", name: "Zoë", exp: 1924992000 }),
"", // alg "none" has an empty signature
].join(".");
console.log(token.includes("=") || token.includes("+") || token.includes("/")); // false
const { header, payload, signature } = decodeJwtUnverified(token);
console.log(header.alg, payload.name, signature.length); // "none" "Zoë" 0The signature is computed over the exact ASCII text header.payload as it appears in the token. Do not decode the segments and encode them again before verifying. Even if the JSON round-trips, key order or whitespace may change, and the signature will no longer match.
Random tokens and identifiers
Session IDs, password-reset links and CSRF tokens need URL-safe randomness. A common pattern is 32 random bytes encoded as base64url:
function randomToken(byteLength = 32) {
const bytes = crypto.getRandomValues(new Uint8Array(byteLength));
return bytesToBase64Url(bytes);
}
const t = randomToken();
console.log(t.length); // 43, since ceil(32 * 4 / 3) = 43 with no padding
console.log(/^[A-Za-z0-9_-]+$/.test(t)); // trueYou can place this token in a path segment, a query string, or a cookie without any escaping.
Filenames: safe characters, two more traps
Base64url contains no /, so it cannot create a path traversal. Two problems remain:
- Case-insensitive filesystems. The default macOS volume and Windows NTFS treat
aBandAbas the same name. Base64url depends on case, so two different hashes can map to the same file. For content-addressed filenames on these systems, use hex (0-9a-f) or lowercase base32. Both are longer, but they do not depend on case. - A leading
-. A file named-rfor-abccan be read as a command-line option, as inrm -abc. Prefix the name, for examplef_plus the encoded value, or always pass--before filenames in scripts.
Choosing between base64url and percent-encoding
You can also keep standard base64 and wrap it in encodeURIComponent:
| Approach | Example for `0xfb 0xff` | Length | Notes |
|---|---|---|---|
| base64url | `-_8` | 3 | Compact, no escaping, needs a conversion step |
| standard base64 + `encodeURIComponent` | `%2B%2F8%3D` | 10 | Works anywhere, but each `+`, `/` and `=` grows to 3 characters |
| standard base64 as-is | `+/8=` | 4 | Breaks in query strings |
Use base64url when you control both ends or when a spec requires it: JWT, JWK, WebAuthn, PKCE code_challenge, and data embedded in URLs. Use percent-encoding when the other side expects standard base64 and you only need to carry it through a URL.
Edge cases worth testing
- Empty input.
bytesToBase64Url(new Uint8Array())returns"", andbase64UrlToBytes("")returns an empty array. Make sure your callers treat an empty token as invalid where that matters. - Non-canonical trailing bits.
"-_9"and"-_8"decode to the same two bytes becauseatobdiscards the unused low bits. Never compare tokens by their encoded strings after decoding and re-encoding. Compare the bytes, preferably in constant time for secrets. - Mixed input. A value that contains both
-and/is neither valid base64 nor valid base64url. Reject it. - Whitespace.
atobstrips ASCII whitespace, but the strict regex above rejects it. Decide on purpose whether a pasted token with a newline should be accepted.
Exercise
A client sends the base64url string "SGVsbG8gV29ybGQ" (15 characters). How much padding must you add before passing it to a strict standard base64 decoder, and how many bytes does it decode to?
Show answer
15 % 4 is 3, so add one "=" to make 16 characters. A final group of 3 characters carries 2 bytes, so the result is 3 full groups (9 bytes) plus 2 bytes, or 11 bytes. It is the text "Hello World".
Exercise
Your password-reset links fail for about one user in four. The token is standard base64 placed in "?token=...", and the server reads it with URLSearchParams. What is the likely cause, and what are two fixes?
Show answer
Some tokens contain "+", which form-style query parsing turns into a space, so the server decodes different bytes. One fix is to generate the token as base64url so it never contains "+", "/" or "=". The other is to keep standard base64 and wrap it in encodeURIComponent when building the URL, so "+" travels as "%2B".
Exercise
Why does base64UrlToBytes reject inputs whose length mod 4 is 1 instead of adding "===" padding?
Show answer
One leftover character carries only 6 bits, which cannot complete a byte. Valid unpadded encodings always end with 0, 2 or 3 characters in the last group. A remainder of 1 means the string was truncated or corrupted, and padding it would hide the error.