Output Encoding and Escaping Fundamentals
What you'll learn: How to neutralize XSS payloads by encoding or escaping untrusted data based on where it appears in your web page.
The Core Problem
Even after filtering and validation, malicious scripts can slip through if you place user input directly into HTML, JavaScript, CSS, or URLs without proper encoding. Each of these contexts interprets special characters differently—what's safe in HTML might be dangerous in JavaScript.
What is Output Encoding?
Output encoding (also called escaping) transforms potentially dangerous characters into safe representations that won't be interpreted as code. Think of it like putting quotation marks around someone's words when you're quoting them—you're preserving the content while making it clear it's data, not your own statement.
Context-Aware Encoding
The golden rule: encode based on where the data lands.
-
HTML Context: Convert
<to<,>to>,"to", etc. This prevents tags from forming. -
JavaScript Context: Escape quotes, backslashes, and control characters. A string
user's inputbecomesuser\'s inputinside JavaScript strings. -
CSS Context: Escape characters that could break out of style declarations or inject properties. Hexadecimal encoding is often used.
-
URL Context: Percent-encode special characters like spaces (
%20), ampersands (%26), and quotes to prevent URL manipulation or injection.
Why This Matters
If you HTML-encode data but place it inside a JavaScript string, it won't help—the JavaScript interpreter doesn't care about <. You must use JavaScript-specific escaping. Wrong context = failed defense.
Key Takeaway:
Output encoding must match the context where data is inserted—HTML encoding for HTML, JavaScript escaping for JavaScript, and so on—to effectively neutralize XSS payloads.