Contextual output encoding
Display text as text
Output encoding transforms text for a particular destination so it is interpreted as data rather than markup or executable syntax. In ordinary HTML text, the book title Research & Design <2026> must appear as those characters, not be interpreted as a tag. The application stores the original title and applies the appropriate rendering control at the output boundary.
Use a text-only DOM destination
For an ordinary paragraph in a browser, a text-only API avoids interpreting the title as HTML. This static example needs no network.
<p id="title"></p><script> const title = "Research & Design <2026>"; document.getElementById("title").textContent = title;</script>The paragraph displays Research & Design <2026> literally. The script is trusted application code and the target is an ordinary paragraph, not a script or style element. This example is not a guarantee about other DOM properties.
Server-rendered HTML
For ordinary HTML text produced on the server, a framework with appropriate automatic escaping or a vetted encoder is useful. For example, Python html.escape produces Research & Design <2026> for the title. In HTML text that represents the original characters. Do not apply an HTML text encoder as a universal solution for URLs, JavaScript, CSS or event handlers; each destination has its own rules and some contexts should not accept untrusted content at all.
Avoid mixing rendering policies
When the application intentionally accepts rich markup, plain-text rendering changes the desired behavior. Use a reviewed HTML sanitizer with an explicit allowed policy for that separate feature, and avoid later unsafe modifications. Keep automatic escaping enabled for normal text; avoid encoding already escaped output a second time. A content security policy is an extra defense, not a replacement for safe rendering.
Practice: select a destination
A product title must appear in a paragraph; a product link must select an approved route. Choose textContent for the title and a fixed application route with validated parameters for the link. Explain why escaping the title cannot establish link trust. Source: OWASP Cross Site Scripting Prevention and DOM Based XSS Prevention.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Contextual output encoding — knowledge check
Apply defensive data handling to a fictional bookstore.
A title belongs in an ordinary paragraph. Which API should display it literally?
Which output represents an ampersand in ordinary escaped HTML text?
Can HTML text escaping alone establish that a URL is trusted?
What if a feature intentionally accepts rich HTML?
What is the role of CSP here?