DOMPurify
repository·main·Indexed 12 days ago
https://github.com/cure53/dompurifyA high-performance, DOM-only XSS sanitizer for HTML, MathML, and SVG. Version 3.4.13. It prevents cross-site scripting attacks by cleaning untrusted markup and works in all modern browsers and Node.js (via jsdom). Features include customizable configuration via ALLOWED_TAGS and KEEP_CONTENT, lifecycle hooks for extending functionality, and support for the Trusted Types API.
What's inside DOMPurify
- DOMPurify is a fast, DOM-only XSS sanitizer for HTML, MathML, and SVG. It takes 'dirty' HTML strings containing potentially malicious code and returns 'clean' HTML by stripping out dangerous elements and attributes. It is designed to prevent XSS (Cross-Site Scripting) attacks while being highly tolerant of valid markup.
Use DOMPurify hooks to extend functionality
mainHooks allow you to execute custom logic at specific stages of the DOMPurify lifecycle. You can add a hook using
DOMPurify.addHook(hookName, callback)and remove it usingDOMPurify.removeHook(hookName).Common hook names mentioned in demos include:
beforeSanitizeAttributes: Triggered before attributes are sanitized.afterSanitizeAttributes: Triggered after attributes are sanitized.uponSanitizeElement: Triggered when an element is being sanitized.uponSanitizeAttribute: Triggered when an attribute is being sanitized.
// Add a hook to convert all text to capitals DOMPurify.addHook('beforeSanitizeAttributes', function (node) { // Set text node content to uppercase if (node.nodeName && node.nodeName === '#text') { node.textContent = node.textContent.toUpperCase(); } }); // Clean HTML string and write into our DIV const clean = DOMPurify.sanitize(dirty); // now let's remove the hook again DOMPurify.removeHook('beforeSanitizeAttributes');Security Warning: Avoid post-sanitization modification
mainA critical security rule: Do not modify the HTML after it has been sanitized.
If you sanitize a string and then perform further manipulations (like using other libraries to change the DOM or manually editing the string), you may inadvertently re-introduce XSS vulnerabilities. Always ensure that any library receiving sanitized markup does not modify the structure in a way that bypasses the security checks.
Automate Trusted Types enforcement with DOMFortify
mainIf you want to apply a Trusted Typesdefaultpolicy across an entire page automatically (sanitizing all HTML sinks likeinnerHTMLincluding third-party code), use DOMFortify. While DOMPurify is a focused sanitizer, DOMFortify acts as the document-wide enforcement layer.Install and use DOMPurify in the browser
mainYou can include DOMPurify directly in your website using
<script>tags.For development (includes source maps):
<script type="text/javascript" src="dist/purify.js"></script>For production (minified):
<script type="text/javascript" src="dist/purify.min.js"></script>Once included, use
DOMPurify.sanitize(dirty)to clean your HTML strings.<script type="text/javascript" src="dist/purify.min.js"></script> <script> const clean = DOMPurify.sanitize(dirty); </script>Use isomorphic-dompurify for easier server/client compatibility
mainIf you encounter difficulties setting up DOMPurify in an isomorphic (universal) environment, the
isomorphic-dompurifypackage provides a simplified wrapper that works in both Node.js and the browser.npm install isomorphic-dompurifyimport DOMPurify from 'isomorphic-dompurify'; const clean = DOMPurify.sanitize('<s>hello</s>');Run DOMPurify on the server with Node.js and jsdom
mainTo run DOMPurify in a Node.js environment, you must provide a DOM implementation. The recommended tool is
jsdom.Warning: Avoid using
happy-domas it is not considered safe for sanitization and may lead to XSS. Always use a recent version ofjsdomto avoid known vulnerabilities in older versions.- Install dependencies:
npm install dompurify jsdom- Initialize DOMPurify with a
jsdomwindow:
import { JSDOM } from 'jsdom'; import DOMPurify from 'dompurify'; const window = new JSDOM('').window; const purify = DOMPurify(window); const clean = purify.sanitize('<b>hello there</b>');Install and use DOMPurify with npm/ESM
mainFor modern JavaScript environments (like Angular or React), install the package via npm and import it directly.
npm install dompurifyimport DOMPurify from 'dompurify'; const clean = DOMPurify.sanitize('<b>hello there</b>');Use DOMPurify inside a custom Trusted Types policy
mainWhen creating your own Trusted Types policy, you must configure DOMPurify to avoid circularity and type mismatches:
- Avoid Type Mismatches: Since
createHTMLexpects a plain string, you must setRETURN_TRUSTED_TYPE: falsewhen callingDOMPurify.sanitizeinside your policy. - Avoid Policy Creation Errors: To prevent DOMPurify from trying to create its own
dompurifypolicy (which might be blocked by your CSP), setTRUSTED_TYPES_POLICY: null.
Warning: Do not pass your own policy object into DOMPurify via
setConfig({ TRUSTED_TYPES_POLICY: myPolicy })if that policy callsDOMPurify.sanitize. This creates infinite recursion, and DOMPurify will throw aTypeErrorto prevent it.// Example: Creating a custom policy that uses DOMPurify window.trustedTypes.createPolicy('my-organization', { createHTML: (input) => DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: false, TRUSTED_TYPES_POLICY: null }), });- Avoid Type Mismatches: Since
Run DOMPurify local tests
mainIf you are contributing to the project or running it in a development environment, you can execute the test suite using npm scripts. The project uses Playwright for browser testing and jsdom for headless testing.
npm run testSubscribe to DOMPurify security updates
mainTo receive notifications regarding security-critical releases (such as fixes for discovered bypasses), you can subscribe to the DOMPurify security mailing list. Note that feature releases are not announced here.
https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-securityUse Trusted Types with DOMPurify
mainIf your environment supports Trusted Types, DOMPurify can integrate with them.
- Internal Policy: DOMPurify creates its own internal policy to sign sanitized HTML.
- Custom Policy: You can provide your own
TRUSTED_TYPES_POLICYin the configuration. This policy must implement bothcreateHTMLandcreateScriptURLhooks. - Return Type: Setting
RETURN_TRUSTED_TYPE: truewill causesanitize()to return a TrustedHTML object instead of a plain string.
Warning: A configured
TRUSTED_TYPES_POLICYcallback must not callDOMPurify.sanitize, as this will cause infinite recursion.