Isomorphic DOMPurify Wrapper

3.9.0 · active · verified Sun Apr 19

isomorphic-dompurify provides a universal wrapper for the DOMPurify library, enabling its seamless use across both client-side browser environments and server-side Node.js applications. Its primary function is to abstract away the environment-specific initialization details required by DOMPurify, which necessitates a DOM tree to operate. On the server, it leverages `jsdom` to create a fake DOM environment, making the API identical to client-side usage. The package is currently at version 3.9.0 and experiences a regular release cadence, primarily driven by updates to its core dependency, DOMPurify, and other development dependencies. A key differentiator is its automatic handling of `jsdom` setup and teardown for server-side XSS sanitization, along with utilities for memory management in long-running Node.js processes. This library is crucial for applications built with frameworks like Next.js that require consistent sanitization logic irrespective of the rendering environment.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic HTML sanitization, applying global configuration, and crucial server-side memory management using `clearWindow()`.

import DOMPurify, { sanitize, clearWindow } from "isomorphic-dompurify";

// 1. Basic sanitization: Works identically on client and server.
const dirtyHtml = `
  <img src="x" onerror="alert('XSS!')">
  <a href="javascript:alert('Evil!')">Click me</a>
  <p>Hello, <script>alert('world');</script> user!</p>
`;
const cleanHtml = sanitize(dirtyHtml, { USE_PROFILES: { html: true } });
console.log('Sanitized HTML:', cleanHtml);
// Expected: <img src="x"><a href="">Click me</a><p>Hello,  user!</p>

// 2. Using DOMPurify directly for configuration or hooks.
// On the client, this uses the browser's global window.
// On the server, it uses an internally managed JSDOM window.
DOMPurify.setConfig({ ALLOW_DATA_ATTR: false });
const cleanHtmlWithConfig = DOMPurify.sanitize('<div data-test="1">Test</div>');
console.log('Sanitized with config (no data attr):', cleanHtmlWithConfig);
// Expected: <div>Test</div>

// 3. Server-side memory management: Crucial for long-running Node.js processes.
// Calling clearWindow() releases JSDOM resources and creates a fresh internal window.
if (typeof window === 'undefined') { // Check if in Node.js environment
  clearWindow();
  console.log('Server-side JSDOM instance cleared for memory management.');
  // After clearing, DOMPurify and sanitize continue to work with a fresh instance.
  const reSanitized = sanitize('<span>Clean again.</span>');
  console.log('Re-sanitized after clearWindow:', reSanitized);
}

view raw JSON →