Sub topic 9
base64url for URLs, JWTs, and Filenames
This chapter assumes you already know how base64 groups 3 bytes into 4 characters and pads with =. It also uses the bytesToBase64 and base64ToBytes helpers from the previous chapter, which encode text with TextEncoder and convert the resulting bytes to base64 through a binary string.
Why standard base64 breaks in URLs
The standard base64 alphabet uses 64 characters: A–Z, a–z, 0–9, +, and /. Its padding character is =. In plain text these characters are harmless. In some other places they have special meanings:
| Character | Problem in URLs and filenames |
|---|---|
| `+` | Form-encoded query strings decode it as a space |
| `/` | Treated as a path separator in URLs and file systems |
| `=` | Separates keys from values in query strings |
You could percent-encode the output, so + becomes %2B. That makes the string longer and harder to read, and it is easy to decode one time too many or one time too few. base64url avoids the problem by using a different alphabet.
The base64url alphabet
base64url is defined in RFC 4648. It is identical to base64 except for two characters:
+becomes-/becomes_
Both - and _ are safe in URL paths, query strings, cookies, and filenames. Most formats that use base64url also drop the = padding, because the decoder can work out the original length from the string length. JSON Web Tokens (JWTs) require padding to be omitted.
Converting in both directions
Converting to base64url only takes character replacements. Converting back is harder because you have to restore the padding. A base64 string's length must be a multiple of 4, so you add = until it is.
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=="The final % 4 in fromBase64Url handles the case where the length is already a multiple of 4. Without it, the function would add four = characters.
A worked example: a JWT header
A JWT has three parts separated by dots. The first part is a JSON header encoded as UTF-8 and then as base64url. This example builds that part and decodes it again:
function bytesToBase64(bytes) {
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return btoa(binary);
}
function base64ToBytes(base64) {
const binary = atob(base64);
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
}
const toBase64Url = (b64) =>
b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const fromBase64Url = (b64u) => {
const b64 = b64u.replace(/-/g, "+").replace(/_/g, "/");
return b64 + "=".repeat((4 - (b64.length % 4)) % 4);
};
const header = { alg: "HS256", typ: "JWT" };
const encoded = toBase64Url(
bytesToBase64(new TextEncoder().encode(JSON.stringify(header)))
);
console.log(encoded); // "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
const decoded = JSON.parse(
new TextDecoder().decode(base64ToBytes(fromBase64Url(encoded)))
);
console.log(decoded.alg); // "HS256"
// Bytes that produce + and / in standard base64
const raw = new Uint8Array([0xfb, 0xff]);
console.log(bytesToBase64(raw)); // "+/8="
console.log(toBase64Url(bytesToBase64(raw))); // "-_8"Common errors
- Passing base64url straight to
atob.atobaccepts only the standard alphabet, so it throwsInvalidCharacterErrorwhen it sees-or_. Convert the string withfromBase64Urlfirst. - Forgetting to strip padding. Some systems reject
=in tokens, and an=left in a query string can be misread as a key/value separator. - Accepting impossible lengths. A string whose length gives a remainder of 1 when divided by 4 is never valid base64. Padding cannot fix it, so reject it instead of decoding it.
- Mixing alphabets. If a string contains both
+and-, it is corrupt. Strict parsers should reject it.
Exercise
A base64url string is 10 characters long. How many = characters does fromBase64Url add, and why?
Show answer
It adds 2. Dividing 10 by 4 leaves a remainder of 2, and (4 - 2) % 4 = 2, so two = bring the length to 12, which is a multiple of 4.
Exercise
Why does atob("-_8") throw, and what call would decode it correctly?
Show answer
The characters - and _ are not in the standard base64 alphabet that atob accepts. Calling atob(fromBase64Url("-_8")) works because it decodes "+/8=", which gives the bytes 0xfb and 0xff.