URL Context Encoding
You'll learn how to safely encode user input when building URLs and href attributes to prevent injection attacks.
What is URL Context Encoding?
When you construct URLs or set href attributes using user-supplied data, you must encode that input to prevent attackers from injecting malicious schemes, redirects, or JavaScript. URL context encoding transforms special characters into their percent-encoded equivalents (like spaces becoming %20) so the browser interprets them as data, not executable code.
Why It's Critical
Without proper encoding, an attacker could craft input like:
javascript:alert(document.cookie)
If you naively insert this into an href, clicking the link executes JavaScript. Similarly, unencoded parameters in query strings can break your URL structure or lead to open redirects.
The Two Key Functions
-
encodeURIComponent(): Use this for encoding values within a URL (query parameters, path segments). It encodes most special characters including/,?,&,=. -
encodeURI(): Use this for encoding a full URL, preserving URL structure characters like://,/,?.
Safe Pattern Example
// User input
const username = "john doe";
const userId = "123&admin=true";
// Safe URL construction
const profileURL = `https://example.com/users/${encodeURIComponent(username)}?id=${encodeURIComponent(userId)}`;
// Result: https://example.com/users/john%20doe?id=123%26admin%3Dtrue
Notice how the & becomes %26, preventing it from being interpreted as a parameter separator.
Think of It Like This
URL encoding is like putting quotes around special characters in a sentence—it tells the browser "treat this as literal text, not as a command."
Key Takeaway: Always use encodeURIComponent() when inserting user input into URL parameters or path segments to prevent injection attacks and ensure URL integrity.