isomorphic-dompurify

repository·master·Indexed 20 days ago

https://github.com/kkomelin/isomorphic-dompurify

A universal wrapper around the DOMPurify library that enables HTML sanitization on both the client (browser) and the server (Node.js). It uses jsdom under the hood for server-side environments and provides a consistent API including sanitize, addHook, setConfig, and a clearWindow function to manage memory in long-running Node.js processes.

Tokens
2.3K
Snippets
13
Records
14
Agent score
68%

What's inside isomorphic-dompurify

  1. Manage memory on the server with clearWindow()

    master

    In long-running Node.js processes, the internal jsdom window accumulates DOM state, which can lead to memory growth and slowdowns. To prevent this, use clearWindow() to periodically release resources.

    Important Notes:

    • clearWindow() closes the current jsdom window and creates a fresh one.
    • After calling clearWindow(), any hooks or configuration set via addHook or setConfig must be re-applied.
    • In browser builds, clearWindow() is a no-op.
    import { sanitize, clearWindow } from "isomorphic-dompurify";
    
    // Sanitize as usual
    const clean = sanitize(dirtyString);
    
    // Release jsdom resources periodically (e.g., after a request or batch)
    clearWindow();
  2. Use isomorphic-dompurify for HTML sanitization

    master

    You can use the library via a default import or named imports. The sanitize function accepts a dirty string and an optional configuration object (following the standard DOMPurify config).

    import DOMPurify from "isomorphic-dompurify";
    
    // Basic usage
    const clean = DOMPurify.sanitize(dirtyString);
    
    // Usage with config
    const cleanWithConfig = DOMPurify.sanitize(dirtyString, { USE_PROFILES: { html: true } });
    
    // Using named imports
    import { sanitize } from "isomorphic-dompurify";
    const cleanNamed = sanitize(dirtyString);
  3. Use isomorphic-dompurify for HTML sanitization

    master

    The isomorphic-dompurify package provides a way to use the dompurify API in environments where a DOM is not natively available (like Node.js) by using jsdom under the hood.

    You can use the default export DOMPurify or individual exported functions like sanitize to clean HTML strings.

    import DOMPurify from 'isomorphic-dompurify';
    
    const dirty = '<img src=x onerror=alert(1)>';
    const clean = DOMPurify.sanitize(dirty);
    // or using the standalone export
    import { sanitize } from 'isomorphic-dompurify';
    const clean2 = sanitize(dirty);
  4. Troubleshoot ERR_REQUIRE_ESM in CommonJS environments

    master

    If you encounter ERR_REQUIRE_ESM in CommonJS environments (like Next.js on Vercel) when using isomorphic-dompurify v3.0.0+, it is likely caused by jsdom@28 pulling in an ESM-only dependency.

    Workaround: Pin jsdom to version 25.0.1 using your package manager's overrides feature.

  5. Create a custom DOMPurify instance with a specific window

    master

    The default export can be called as a factory function. This allows you to bind a DOMPurify instance to a specific window object, which is useful for testing or sandboxed environments using libraries like jsdom.

    import DOMPurify from "isomorphic-dompurify";
    import { JSDOM } from "jsdom";
    
    const purify = DOMPurify(new JSDOM().window);
    const clean = purify.sanitize(dirtyString);
  6. Use TypeScript types with isomorphic-dompurify

    master

    The library re-exports hook-related types from dompurify, allowing you to type your addHook callbacks without redeclaring signatures.

    Available type re-exports include:

    • Config
    • DOMPurify
    • DocumentFragmentHook
    • ElementHook
    • HookName
    • NodeHook
    • RemovedAttribute
    • RemovedElement
    • UponSanitizeAttributeHook
    • UponSanitizeAttributeHookEvent
    • UponSanitizeElementHook
    • UponSanitizeElementHookEvent
    • WindowLike
    import { addHook, type NodeHook } from "isomorphic-dompurify";
    
    const stripTargetBlank: NodeHook = function (node) {
      if ("target" in node) (node as Element).removeAttribute("target");
    };
    
    addHook("afterSanitizeAttributes", stripTargetBlank);
  7. Configure DOMPurify with setConfig and clearConfig

    master

    Global configuration can be managed using setConfig and clearConfig to control which tags, attributes, or styles are allowed during sanitization.

    import { setConfig, clearConfig } from 'isomorphic-dompurify';
    
    setConfig({ ALLOWED_TAGS: ['b', 'i', 'em', 'strong'] });
    clearConfig();
  8. Sanitize HTML with sanitize()

    master

    The sanitize function takes a dirty HTML string (or other input) and an optional configuration object, returning a sanitized version of the input. It is a direct proxy to the core DOMPurify.sanitize method.

    import { sanitize } from 'isomorphic-dompurify';
    
    const clean = sanitize('<div onclick="alert(1)">Hello</div>', { ALLOWED_TAGS: ['div'] });
  9. Reset the internal DOM environment with clearWindow()

    master

    Because isomorphic-dompurify maintains an internal jsdom instance to provide the DOM environment, you can use clearWindow() to close the current window and create a fresh one. This is useful for preventing memory leaks or resetting the state of the underlying DOM.

    import { clearWindow } from 'isomorphic-dompurify';
    
    // Closes the current JSDOM window and initializes a new one
    clearWindow();
  10. Use the browser-side DOMPurify API

    master

    When using isomorphic-dompurify in a browser environment, you can import the default export or use the named exports for a more direct API. The named exports are pre-bound to the DOMPurify instance, allowing you to call them without worrying about the this context.

    Key exported functions include:

    • sanitize: Cleans HTML strings.
    • addHook, removeHook, removeHooks, removeAllHooks: Manage lifecycle hooks for the sanitization process.
    • setConfig, clearConfig: Manage the global configuration.
    • isSupported: Checks if the current environment supports DOMPurify.
    import { sanitize, addHook, setConfig } from 'isomorphic-dompurify';
    
    // Basic usage
    const clean = sanitize('<img src=x onerror=alert(1)>');
    
    // Configuring
    setConfig({ ALLOWED_TAGS: ['b', 'i'] });
    
    // Using hooks
    addHook('uponSanitizeElement', (node) => {
      // logic here
    });
  11. Manage DOMPurify hooks with addHook and removeHook

    master

    You can extend the sanitization process by adding hooks at specific entry points (e.g., uponSanitizeElement).

    • addHook(entryPoint, hookFunction): Registers a new hook.
    • removeHook(entryPoint): Removes a specific hook.
    • removeHooks(entryPoint): Removes all hooks for a specific entry point.
    • removeAllHooks(): Removes all registered hooks.
    import { addHook, removeHook } from 'isomorphic-dompurify';
    
    addHook('uponSanitizeElement', (node) => {
      // custom logic
    });
    
    removeHook('uponSanitizeElement');