DOMPurify: The XSS Sanitizer That Just Works
Intro
If you've ever needed to safely render user-generated HTML without opening the door to cross-site scripting (XSS) attacks, you know the pain. String-based regex filters are brittle, and overly strict sanitizers often break legitimate content.
Enter DOMPurify—a battle-tested, DOM-aware sanitizer that strips malicious markup while preserving what’s safe. With over 15.5k GitHub stars and backing from security experts at Cure53, it’s become the go-to solution for projects like GitHub, WordPress, and more.
What It Does
DOMPurify is a JavaScript library that:
- Sanitizes HTML, SVG, and MathML by parsing content as real DOM (not regex hacks).
- Removes XSS payloads while keeping safe markup intact.
- Works client-side and server-side (Node.js + jsdom).
- Supports configurable allow/block lists, hooks, and Trusted Types.
Example:
const clean = DOMPurify.sanitize('<img src=x onerror=alert(1)>');
// Output: <img src="x">
Why It’s Cool
1. Tolerant by Design
Unlike regex-based sanitizers, DOMPurify understands context. It won’t choke on malformed HTML (like unclosed tags) and handles edge cases most tools miss (e.g., SVG filters, javascript: URIs).
2. Blazing Fast
By leveraging the browser’s native DOM parser, it’s faster than most alternatives. Benchmarks show it’s 10–100x faster than string-based sanitizers.
3. Highly Configurable
Need to allow custom elements or restrict protocols? DOMPurify’s got you:
DOMPurify.sanitize(dirtyHtml, {
ALLOWED_TAGS: ['b', 'q', 'custom-element'],
FORBID_ATTR: ['style', 'on*']
});
4. Security-First
Built by XSS researchers, it’s designed to thwart bypasses. Cure53 even runs a bug bounty program for vulnerabilities.
How to Try It
-
Install:
npm install dompurifyOr drop it directly in the browser:
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script> -
Demo: Play with the interactive demo to see it in action.
Final Thoughts
DOMPurify isn’t just another sanitizer—it’s the rare tool that balances security with practicality. Whether you’re building a CMS, forum, or anything handling untrusted HTML, it’s worth baking into your stack.
Pro tip: Pair it with Trusted Types for even stronger XSS protection in modern browsers.
Got a horror story about broken sanitizers? DOMPurify might just be the fix. 🛠️
@GithubProjects What were the chances that I came across this earlier and used it and you guys post about it? 😅
@_uDonny 😂