URL-Safe Base64 Encoding
Learn about Base64url encoding, the URL-safe variant of Base64. Understand the character substitutions, padding rules, and where it is used (JWTs, URLs).
Detailed Explanation
Standard Base64 uses the characters +, /, and = which have special meanings in URLs and filenames. URL-safe Base64 (often called Base64url, defined in RFC 4648 Section 5) solves this by replacing these problematic characters:
| Standard Base64 | Base64url |
|---|---|
+ |
- (hyphen) |
/ |
_ (underscore) |
= (padding) |
Often omitted |
Why this matters: If you include standard Base64 in a URL query parameter, the + character gets interpreted as a space, and / gets interpreted as a path separator. URL-encoding them (%2B, %2F) works but makes the string much longer and harder to read. Base64url avoids these issues entirely.
Converting between formats in JavaScript:
// Standard Base64 to Base64url
function toBase64url(base64) {
return base64
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
// Base64url to Standard Base64
function fromBase64url(base64url) {
let base64 = base64url.replace(/-/g, "+").replace(/_/g, "/");
while (base64.length % 4 !== 0) {
base64 += "=";
}
return base64;
}
Padding in Base64url: The padding character = is frequently omitted in Base64url because the decoder can infer the original length from the string length. A Base64url string with length n needs (4 - n % 4) % 4 padding characters to be valid standard Base64. Many implementations (like JWT libraries) always strip padding, while others keep it. Be aware of what your decoder expects.
Where Base64url is used:
- JSON Web Tokens (JWT) use Base64url for the header and payload segments.
- OAuth 2.0 PKCE code verifiers and challenges.
- URL shorteners and link-safe identifiers.
- Amazon S3 ETags and other cloud service identifiers.
Common mistake: Mixing up Base64url and standard Base64. If you decode a JWT segment using atob() without first converting - and _ back to + and /, the decoding will produce incorrect results or fail entirely.
Use Case
Generating PKCE code challenges for OAuth 2.0 authorization flows, where the challenge must be safely included in a URL redirect parameter.