How to Sanitize User-Generated HTML
Render user-generated content safely: prefer escaping over sanitizing, allowlist tags and attributes when HTML is required, and stop XSS at the sink.
On this page
Introduction
User-generated content is untrusted, and rendering it as HTML is the direct path to cross-site scripting. A comment containing a script tag, an image with an onerror handler, or a link with a javascript: URL all execute in the context of your page if they reach the DOM unescaped, with access to the user’s session and data. The defense depends on whether the content must be HTML at all, and most content that people think must be HTML does not.
This tutorial covers escaping as the default, allowlist sanitizing when rich HTML is truly required, sanitizing at the output sink rather than on input, and testing with real XSS payloads. The examples use a mature sanitizer and an escaping approach, and the reasoning applies to any rendering layer.
Prefer escaping over sanitizing
If the content is plain text that happens to look like HTML, escape it. Escaping replaces the characters that would start a tag or an attribute, so a script tag in a comment renders as visible text and never executes. The browser then treats the whole value as text, and no allowlist and no sanitizer is needed, because there is no HTML to allow.
Most content is text: names, comments, titles, messages. Default to escaping these and you eliminate the entire class. The temptation to allow HTML usually comes from a specific feature, such as formatting in a description. When that need is real, scope the rich rendering to that one field and keep everything else escaped, so the attack surface is one field, not the whole application.
function escapeHtml(s) {
return String(s)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// a comment containing a script tag renders as text, not as a script
const comment = '<script>alert(1)</script>';
element.innerHTML = escapeHtml(comment); // shows the text; does not execute
Allowlist when HTML is required
When rich HTML is a requirement, use a mature sanitizer that parses the HTML and keeps only an allowlist of tags and attributes. The allowlist should be as small as the feature needs: paragraphs, links, lists, emphasis, and nothing that can execute or load. Drop script, style, iframe, object, and anything with an event handler. Reject unknown tags rather than trying to strip them, because a parser-based sanitizer handles the edge cases a regex cannot.
Allow attributes explicitly, and validate their values. An href is allowed only if its scheme is among a safe set, excluding javascript: and data: except where data: of an allowed image type is needed. An image src is validated the same way. Never allow style attributes if you can avoid them, because CSS has its own exfiltration and injection paths, and never allow an attribute whose name starts with on, which is an event handler.
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userHtml, {
ALLOWED_TAGS: ['p', 'a', 'ul', 'ol', 'li', 'strong', 'em', 'code', 'br'],
ALLOWED_ATTR: ['href', 'title'],
ALLOWED_URI_REGEXP: /^(?:https?|mailto):/i, // no javascript:, no data:
});
container.innerHTML = clean;
Sanitize at the sink
Sanitize where the value becomes HTML, on the exact string placed into the DOM or the template. Sanitizing on input and storing the cleaned value seems convenient, but it couples the safety to the storage format: if the content is later composed from several fields, or transformed, or rendered by a different front end, the input-time check may no longer apply. Output-time sanitizing sees what the browser will actually parse.
In a template engine, use the engine’s escaping by default and mark only the sanitized rich field as safe to inject raw. In a client-side framework, bind text content rather than raw HTML, and reserve the raw-HTML binding for the sanitized value alone. In both cases, the invariant is that raw insertion happens only for a value that passed the sanitizer, and that path is easy to find in review.
// escape text; only the sanitized rich field is inserted as HTML
render(template, {
author: escapeHtml(author), // text
body: cleanRichHtml(body), // sanitized, then inserted raw
});
// never: template += '<div>' + userInput + '</div>' with an unescaped userInput
Watch the non-script vectors
Not every XSS payload is a script tag. Event handlers such as onerror on an image or onload on a body attribute execute without a script element. A javascript: URL in an href executes on click. SVG can carry scripts and event handlers, so allowing inline SVG reopens the hole. And an attribute value can be crafted to break out of its quotes if the escaping is incomplete.
Include these in the escaping and the sanitizer configuration. Escape every attribute value, validate URL schemes, disallow inline SVG and MathML unless you truly need them and then sanitize them, and refuse attributes starting with on. The sanitizer’s allowlist enforces this if it is small; when in doubt, allow less.
Test with real payloads
Test the render path with a set of payloads: a plain script tag, an image with an onerror handler, an anchor with a javascript: href, an SVG with a script, an attribute break-out with a quote, and a benign tag like strong that should survive if HTML is allowed. Assert that the dangerous payloads render as text or are stripped, and that the benign one survives when allowed. Assert that no result contains an executable element or an event handler attribute.
node -e '
const clean = require("./sanitize");
const bad = ["<script>alert(1)</script>", "<img src=x onerror=alert(1)>", "<a href=javascript:alert(1)>x</a>"];
for (const b of bad) {
const out = clean(b);
if (/<script|onerror|javascript:/i.test(out)) throw new Error("payload survived: " + out);
}
console.log("all payloads neutralized");'
Common pitfalls
Rendering unescaped user input as HTML, hand-rolled regex sanitizing that misses edge cases, allowing script, style, or inline SVG, allowing href schemes like javascript:, sanitizing once on input and trusting it after a transform, and forgetting event-handler attributes are the recurring mistakes. Escaping by default, a small allowlist with a mature sanitizer, output-time sanitizing, scheme validation, and payload tests address them.
Conclusion
Rendering untrusted content as HTML is the direct path to XSS. Escape by default, and when rich HTML is required, keep a small allowlist with a mature sanitizer, validate URL schemes, exclude scripts, styles, inline SVG, and event handlers, and sanitize at the output sink. Self-check by feeding script, onerror, javascript:, and attribute-break-out payloads and asserting none survives as executable. Then user content can be displayed without becoming code.
Sources: OWASP: Cross site scripting prevention cheat sheet, MDN: Cross-site scripting (XSS), DOMPurify.
FAQ
- Escape or sanitize?
- Escape unless you truly need rich HTML. Escaping converts the text so no tag is interpreted, which is simpler and safer. Sanitizing allows some HTML and is far harder to get right, so use it only when the product requires formatted content and use a mature library.
- Is sanitizing on input enough?
- No. Storage formats change, and content can be composed from several sources; sanitizing once on input can be bypassed by a later transform. Sanitize at the point of output, on the exact string being placed into HTML, so the check applies to what the browser sees.
Report a problem with this articleOpens a pre-filled issue on GitHub.