DOMPurify
DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:
DOMPurify is a JavaScript library that strips malicious code from untrusted HTML before it is shown on a webpage, protecting users from cross-site scripting attacks with a single function call.
DOMPurify is a JavaScript library that cleans up HTML before your website displays it, blocking a class of web attacks called XSS (cross-site scripting), where someone slips malicious code into content like a user comment so it runs in other visitors' browsers. You hand DOMPurify a string of untrusted HTML and it hands back a sanitized version with the dangerous bits removed.
It is fast and easy to drop in. After including the script, sanitizing is one line: DOMPurify.sanitize(dirty). It accepts HTML, SVG and MathML by default, and you can narrow it down — for example, allow only plain HTML — through a profile setting. The cleaned result can then be written into the page normally. Internally it relies on the browser's own DOM engine to parse and inspect the content, which is what keeps it quick and accurate; the project calls itself a DOM-only, super-fast, uber-tolerant XSS sanitizer. Hooks let you customise the sanitization, and a removed property lists what was stripped, intended for curiosity rather than security decisions.
DOMPurify runs in all modern browsers and also on the server with Node.js, but server use requires a DOM library such as jsdom, and the maintainers strongly recommend keeping that dependency current because older versions can reintroduce XSS holes. Tools like happy-dom are flagged as not currently safe to pair with it. Reach for DOMPurify whenever your app has to render HTML that came from somewhere you don't fully control: user-submitted content, third-party feeds, rich-text editors, or API responses. It is written by a security firm and inspired the browser-native HTML Sanitizer API. The full README is longer than what was provided.
Where it fits
- Sanitize user-submitted comments or rich-text editor output before rendering them in a web page.
- Clean HTML fetched from a third-party API or RSS feed before injecting it into the DOM.
- Protect a Node.js server-side rendering pipeline from XSS in untrusted incoming content.
- Allow only safe formatting tags while stripping scripts and event handlers from user input.