What is Sanitization?

Sanitization is cleaning untrusted input so it is safe for the place it is going, for example removing dangerous HTML before rendering it, so the data can be used without enabling attacks like XSS.

Sanitising vs escaping vs validating

  • Validation rejects input that does not match what you expect (an email, a number between 1 and 100). Do it on the server (the client can be bypassed) and ideally also on the client for UX.
  • Escaping converts special characters so they are treated as text in a specific context (< becomes &lt; in HTML). This is the default defence and what frameworks do for you.
  • Sanitising keeps some markup but removes the dangerous parts. You need it when users are allowed to submit rich content (comments with bold and links, markdown rendered to HTML, WYSIWYG editors).

How to sanitise HTML properly

  • Use a mature library such as DOMPurify (browser and Node via jsdom), or sanitize-html on the server.
  • The Sanitizer API (element.setHTML(html)) is built into newer browsers, but check support before relying on it.
  • Use an allow-list of tags and attributes. Block-lists always miss something (new tags, odd encodings, SVG, MathML).
  • Strip event-handler attributes (on*) and dangerous URL schemes (javascript:).
  • Sanitise as close to output as possible, and re-sanitise if the data could have changed.

Other contexts need their own treatment

  • SQL: parameterised queries, never string concatenation.
  • Shell commands: avoid passing user input; use argument arrays.
  • File names and paths: block ../ traversal.
  • URLs: parse with URL and allow-list protocols and hosts.

Code example

js
1// Minimal allow-list HTML sanitiser for demonstration (use DOMPurify in production)
2const ALLOWED_TAGS = new Set(["B", "I", "EM", "STRONG", "A", "P", "UL", "LI", "BR"]);
3const ALLOWED_ATTRS = { A: ["href", "title"] };
4
5function sanitize(dirty) {
6 const template = document.createElement("template");
7 template.innerHTML = dirty; // parsed inertly: scripts don't run, images don't load
8
9 const clean = (node) => {
10 for (const child of [...node.children]) {
11 if (!ALLOWED_TAGS.has(child.tagName)) {
12 child.replaceWith(...child.childNodes); // drop the tag, keep its text
13 continue;
14 }
15 for (const attr of [...child.attributes]) {
16 const allowed = ALLOWED_ATTRS[child.tagName]?.includes(attr.name);
17 const safeHref = attr.name !== "href" || /^(https?:|mailto:)/i.test(attr.value.trim());
18 if (!allowed || !safeHref) child.removeAttribute(attr.name);
19 }
20 if (child.tagName === "A") child.setAttribute("rel", "noopener noreferrer");
21 clean(child);
22 }
23 };
24 clean(template.content);
25 return template.innerHTML;
26}
27
28const input = `<p onclick="steal()">Hi <b>there</b> <img src=x onerror=alert(1)>
29<a href="javascript:alert(1)">bad</a> <a href="https://example.com" style="x">good</a><script>alert(1)</script></p>`;
30const output = sanitize(input);
31console.log(output);
32console.log(/onclick|onerror|javascript:|<script|<img/i.test(output)); // false - dangerous parts removed
33
34document.body.innerHTML = output; // now safe to render

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app