URL-Safe Base64: When and Why to Use It
URL-Safe Base64 Explained
Standard Base64 uses characters that have special meanings in URLs. URL-safe Base64 solves this problem.
The Problem with Standard Base64
Standard Base64 uses these special characters:
- + (plus) - represents a space in URLs
- / (slash) - used as a path separator
- = (equals) - used for query parameters
When you put standard Base64 in a URL, these characters get URL-encoded:
+becomes%2B/becomes%2F=becomes%3D
This makes URLs longer and harder to read.
URL-Safe Base64 Solution
URL-safe Base64 (also called Base64url) makes simple substitutions:
+is replaced with-(minus)/is replaced with_(underscore)=padding is often omitted
Comparison Example
Original text: "Hello World!"
Standard Base64:
`` SGVsbG8gV29ybGQh
`
URL-Safe Base64:
` SGVsbG8gV29ybGQh
`
Another example with special characters:
Original: ">>>???"
Standard Base64:
` Pj4+Pz8/
`
URL-Safe Base64:
` Pj4-Pz8_
`
When to Use Each
Use Standard Base64 for:
- Email attachments (MIME)
- Data URIs in HTML/CSS
- Database storage
- General binary-to-text conversion
Use URL-Safe Base64 for:
- JWT tokens
- URL query parameters
- Filename encoding
- Cookie values
- Any data that goes in a URL
Implementation in JavaScript
Encode to URL-Safe Base64:
`javascript
function toBase64Url(str) {
return btoa(str)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
`
Decode from URL-Safe Base64:
`javascript
function fromBase64Url(str) {
str = str.replace(/-/g, '+').replace(/_/g, '/');
while (str.length % 4) str += '=';
return atob(str);
}
`
JWT and URL-Safe Base64
JWTs specifically use URL-safe Base64 (without padding) because tokens are often passed in URLs:
` https://api.example.com/data?token=eyJhbGciOiJIUzI1NiJ9...
``
The header and payload of a JWT are Base64url encoded JSON objects.
Best Practices