How to sanitize HTML output against XSS
Encode data on output, not input, and use a context-aware encoder so values inserted into HTML, attributes, or script contexts are all safe.
On this page
Introduction
sanitize HTML output against XSS is a practical problem every team hits once raw interpolation executes HTML. The naive fix works for a handful of cases and then silently fails. This tutorial builds a working JavaScript solution you can adapt, grounded in context-aware encoding, a template auto-escaping, and JS context vs HTML context.
We walk through the mechanism first, because copying code without understanding context-aware encoding is how subtle bugs enter. Then we implement a template auto-escaping in JavaScript, handle the JS context vs HTML context cases that break toy examples, and finish with verification and production hardening. Every code block is runnable; every pitfall is one the author has hit in real systems.
The examples target JavaScript because it is where sanitize HTML output against XSS hurts most in practice, but the reasoning transfers to any stack. If your language differs, translate the structure, not the syntax: the context-aware encoding model and the JS context vs HTML context handling are what matter, and they are language-agnostic. Skip nothing; each section assumes the previous one.
Understanding context-aware encoding
context-aware encoding is the foundation. Without it, the rest of the JavaScript code is a pile of incantations. When you understand why context-aware encoding holds, the implementation decisions become obvious instead of arbitrary. Many developers skip this step and pay for it later with debugging sessions that would not be needed if the model were clear.
Concretely, context-aware encoding means you can reason about correctness before writing code. That reasoning is what separates a fix that holds under load from one that passes the unit test and fails in staging. Invest ten minutes here and save hours later.
A useful check: explain context-aware encoding to a colleague in one sentence. If you reach for a whiteboard or hedge with sort of, you do not yet have the model, and the implementation will reflect that fuzziness. Sharpen the sentence first; the JavaScript code writes itself once the invariant is crisp.
Implementing a template auto-escaping
With the model in place, the JavaScript implementation of a template auto-escaping is direct. The code below is intentionally small so you can see every moving part; production adds logging and configuration but the core stays the same.
import { escape } from 'html-entities';
el.innerHTML = '<p>' + escape(user.name) + '</p>';
Read the implementation top to bottom: it sets up the a template auto-escaping precondition, performs the operation, and returns a result you can assert against. The shape of the return value matters for JS context vs HTML context, so do not change it without updating the tests.
Resist the urge to generalise prematurely. A second parameter, a config object, or a plugin hook feels productive but pushes you into JS context vs HTML context territory before you have a single working path. Ship the narrow version, let real usage tell you which axis actually varies, and only then parameterise. The code above is deliberately concrete for that reason.
Handling JS context vs HTML context
The happy path is easy; JS context vs HTML context is where the bugs live. The second code block shows how to handle the case the first example ignored.
// in a JS string context, use JSON.stringify for safety
el.setAttribute('onclick', 'handler(' + JSON.stringify(user.id) + ')');
Notice how the guard for JS context vs HTML context fails closed: when in doubt, it rejects rather than silently accepting bad input. That default-safe stance is what makes the code trustworthy in production, where inputs are never as clean as the documentation promises.
Test the guard from both sides: a clearly valid input that must pass, and a clearly invalid one that must fail with a useful message. The message matters as much as the rejection, because JS context vs HTML context errors that say something went wrong cost an hour of triage; one that names the violated constraint costs thirty seconds. Treat error text as part of the API.
Common pitfalls
- encoding on input losing original data. This is the first thing to check when the code misbehaves; a single test reproducing it prevents regression.
- HTML-encoding in a JS context. It usually surfaces under concurrency or unusual input shapes, so add a concurrent test early.
- trusting a template that does not auto-escape. Performance and correctness both depend on getting this right; profile before assuming.
Each pitfall above has a corresponding test in the verification section. If you hit a bug not listed here, start from context-aware encoding and reason forward — most surprises trace back to a mistaken assumption about the model.
Testing and verification
Verification uses submitting a name with a script tag. The goal is not line coverage but confidence that the sanitize HTML output against XSS behaviour holds for the inputs that matter. Write a test for the happy path, one for JS context vs HTML context, and one for each pitfall above.
Add at least one test that would fail if encoding on input losing original data regressed. Regression tests are cheap insurance: they take a minute to write and they catch the exact bug that already bit you, which is the bug most likely to return after a refactor. Pin the behaviour in code so a future change cannot silently undo the fix.
Production considerations
Before shipping, apply Trusted Types for innerHTML. These are the settings that distinguish a demo from a service: timeouts, limits, observability, and graceful degradation when dependencies falter.
Monitor the sanitize HTML output against XSS path in production and alert on encoding on input losing original data symptoms. The first week of traffic will surface cases your tests missed; treat each as a new test case rather than a hotfix, so the suite grows with reality.
Document the context-aware encoding invariant in a comment at the top of the module, not in a wiki that drifts. The next engineer to touch this code will read that comment before the tests, and a one-line statement of what must always be true is worth more than ten pages of prose scattered across a wiki that nobody updates.
Conclusion
A robust sanitize HTML output against XSS implementation is a correct mental model of context-aware encoding, direct code for a template auto-escaping, explicit handling of JS context vs HTML context, tests that encode the pitfalls, and production settings that keep it alive under load. Build them in that order and you will have code you trust.
Sources: OWASP XSS Output Encoding, html-entities
FAQ
- What is the most common mistake when implementing sanitize HTML output against XSS?
- encoding on input losing original data. Catch it early with a focused test before it reaches production.
- Does this approach scale for large JavaScript workloads?
- Trusted Types for innerHTML. Measure with submitting a name with a script tag rather than assuming.
Report a problem with this articleOpens a pre-filled issue on GitHub.