URL Encoding Security
Improper URL encoding is a common source of security vulnerabilities. Understanding these risks is essential for web developers.
Injection Attacks
Without proper encoding, attackers can inject malicious content:
// VULNERABLE: Direct string concatenation
const userInput = "'; DROP TABLE users; --";
const url = /api/search?q=${userInput};
// Could lead to SQL injection if backend doesn't sanitize
// SAFE: Proper encoding
const url = /api/search?q=${encodeURIComponent(userInput)};
XSS via URLs
URLs in HTML attributes need careful handling:
// VULNERABLE
const link = <a href="${userUrl}">Click</a>;
// Attacker could inject: javascript:alert('xss')
// SAFE: Validate URL scheme
function isSafeUrl(url) {
try {
const parsed = new URL(url);
return ['http:', 'https:'].includes(parsed.protocol);
} catch {
return false;
}
}
Open Redirect Vulnerabilities
// VULNERABLE: Unvalidated redirect
app.get('/redirect', (req, res) => {
res.redirect(req.query.url); // Attacker: ?url=https://evil.com
});
// SAFE: Whitelist allowed domains
const allowedDomains = ['example.com', 'api.example.com'];
function isAllowedRedirect(url) {
try {
const parsed = new URL(url);
return allowedDomains.includes(parsed.hostname);
} catch {
return false;
}
}
Best Practices
- Always use
encodeURIComponentfor user input in URLs - Use the URL API instead of string concatenation
- Validate URL schemes (http/https only)
- Whitelist allowed redirect domains
- Never trust URL parameters without validation