What is contextual output encoding and why is it important?
The same data needs different encoding depending on where it lands (HTML body vs attribute vs JavaScript vs URL vs CSS) — encode for the wrong context and the output is still exploitable.
* Contextual output encoding — the same data needs a different escape depending on where it lands; the wrong context leaves it exploitable. *
Contextual encoding means encoding output appropriately for where it will be used.
Server-side encoding (for JS context):
var input = "<%= Encoder.encodeForJS(untrustedData) %>";
Client-side encoding (for HTML context):
document.writeln(ESAPI4JS.encodeForHTML(input));
Why context matters — wrong encoding = still vulnerable:
| Output Context | Encoding Needed | Example |
|---|---|---|
| HTML body | HTML entity encoding | < → < |
| HTML attribute | Attribute encoding | " → " |
| JavaScript | JS escaping | ' → \' |
| URL parameter | URL encoding | & → %26 |
| CSS | CSS escaping | \ → \\ |
Common mistake: HTML-encoding data that ends up inside a <script> tag — HTML entities aren't decoded in JS context, so the encoding does nothing useful.
See: OWASP XSS Prevention Cheat Sheet | OWASP DOM Based XSS Prevention
Go deeper:
OWASP XSS Prevention Cheat Sheet — the context-by-context encoding rules (HTML body / attribute / JS / URL / CSS).