URL Encoding Guide
Proper URL encoding ensures your web applications handle data correctly, avoid security vulnerabilities, and work across all browsers and platforms. This guide covers best practices for URL encoding in real-world scenarios.
Building URLs the Right Way
#### Method 1: URLSearchParams (Recommended)
The modern, safest way to build query strings:
// Automatic encoding and decoding
const params = new URLSearchParams({
name: 'John Doe & Sons',
email: 'john@example.com',
redirect: 'https://example.com/return?page=1&sort=desc'
});
const queryString = params.toString();
// name=John+Doe+%26+Sons&email=john%40example.com&redirect=https%3A%2F%2Fexample.com%2Freturn%3Fpage%3D1%26sort%3Ddesc
// Parsing query strings
const parsed = new URLSearchParams(queryString);
console.log(parsed.get('name')); // John Doe & Sons
#### Method 2: URL API
const url = new URL('https://api.example.com/search');
url.pathname = '/search/phones & accessories';
url.searchParams.set('q', 'smart phone < 1000');
url.searchParams.set('sort', 'price desc');
console.log(url.toString());
// https://api.example.com/search/phones%20%26%20accessories?q=smart+phone+%3C+1000&sort=price+desc
#### Method 3: Template Literals with encodeURIComponent
const category = 'books & magazines';
const keyword = 'C++ programming guide';
const url = https://shop.example.com/${encodeURIComponent(category)}?q=${encodeURIComponent(keyword)};
// https://shop.example.com/books%20%26%20magazines?q=C%2B%2B%20programming%20guide
Common URL Encoding Patterns
#### Pattern 1: Search Queries
function buildSearchUrl(base, query, filters) {
const params = new URLSearchParams({ q: query, ...filters });
return ${base}?view=grid&${params};
}
buildSearchUrl('https://shop.example.com/search', 'laptop stand', {
minPrice: '50',
maxPrice: '200',
brand: 'Dell & HP'
});
// https://shop.example.com/search?view=grid&q=laptop+stand&minPrice=50&maxPrice=200&brand=Dell+%26+HP
#### Pattern 2: Redirect URLs
function buildRedirectUrl(redirectTarget, params) {
const encodedTarget = encodeURIComponent(redirectTarget);
const queryString = new URLSearchParams(params).toString();
return https://example.com/auth?redirect=${encodedTarget}&${queryString};
}
#### Pattern 3: API Endpoints with Path Parameters
function buildApiPath(resource, id, action) {
const encodedResource = encodeURIComponent(resource);
const encodedId = encodeURIComponent(id);
const encodedAction = action ? /${encodeURIComponent(action)} : '';
return /api/v1/${encodedResource}/${encodedId}${encodedAction};
}
buildApiPath('user groups', 'admin & super', 'edit');
// /api/v1/user%20groups/admin%20%26%20super/edit
Encoding for Different URL Parts
Different parts of a URL have different encoding requirements:
| URL Part | Encoding Method | Special Considerations |
| Scheme (http) | None | Fixed set: http, https, ftp, etc. |
| Domain | Punycode for IDN | ε½ι εεη¨ Punycode |
| Path | encodeURIComponent per segment | / is path separator |
| Query | URLSearchParams | & and = have special meaning |
| Fragment | encodeURIComponent | Same as query |
Handling Special Cases
#### Case 1: Slashes in Parameters
// Problem: Slashes in parameter values
const path = 'folder/subfolder/file'
const wrong = https://example.com/path/${path};
// This creates extra path segments!
// Solution: Encode the slashes
const right = https://example.com/path/${encodeURIComponent(path)};
// https://example.com/path/folder%2Fsubfolder%2Ffile
#### Case 2: Plus Signs
// Problem: + means space in query strings
const math = '2 + 2 = 4';
const wrong = ?expression=${math};
// Parsed as: "2 2 = 4"
// Solution: Encode the +
const right = ?expression=${encodeURIComponent(math)};
// ?expression=2%20%2B%202%20%3D%204
#### Case 3: Already-Encoded URLs
// Problem: Double encoding
const alreadyEncoded = 'hello%20world';
const doubleEncoded = encodeURIComponent(alreadyEncoded);
// hello%2520world β WRONG!
// Solution: Decode first, then encode
const correct = encodeURIComponent(decodeURIComponent(alreadyEncoded));
// hello%20world β Correct
Security Considerations
#### 1. Prevent Open Redirects
function safeRedirect(redirectUrl) {
const decoded = decodeURIComponent(redirectUrl);
const url = new URL(decoded, window.location.origin);
// Only allow same-origin redirects
if (url.origin !== window.location.origin) {
throw new Error('Invalid redirect URL');
}
return url.toString();
}
#### 2. Prevent XSS via URLs
// Never insert URL parameters directly into DOM
const params = new URLSearchParams(window.location.search);
const userName = params.get('name');
// BAD: XSS vulnerability
// element.innerHTML = userName;
// GOOD: Escape the content
element.textContent = userName;
#### 3. Validate Encoded Data
function validateEncodedParam(value, maxLength = 1000) {
const decoded = decodeURIComponent(value);
if (decoded.length > maxLength) {
throw new Error('Parameter too long');
}
// Check for null bytes
if (decoded.includes('\0')) {
throw new Error('Invalid characters');
}
return decoded;
}
Testing URL Encoding
Always test your URL encoding with:
- Empty values β
?q= - Special characters β
?q= - Unicode β
?q=δ½ ε₯½δΈη - Long strings β Test with 10,000+ character values
- Nested encoding β URLs containing encoded URLs
- Plus signs β Ensure + is handled correctly
Using Our Tool
Our URL Encoder provides:
- Instant encoding and decoding
- Support for both encodeURI and encodeURIComponent styles
- Handling of Unicode and special characters
- No data sent to servers β all processing is local
Conclusion
Proper URL encoding is critical for web application reliability and security. By using modern APIs like URLSearchParams and the URL constructor, and following the best practices in this guide, you can avoid common URL encoding pitfalls. Use our URL Encoder to encode or decode URLs quickly and safely.