Sanitize HTML safely with rehype-sanitize

Use rehype-sanitize to neutralize XSS in user content: schemas, plugin order, DOM clobbering and the mistakes to avoid.

If your site displays HTML that someone else wrote, such as comments, Markdown from users or content pulled from an API, that HTML can contain scripts. Cross-site scripting (XSS) lets an attacker run code in your visitors' browsers. rehype-sanitize removes the dangerous parts while keeping ordinary formatting.

Parsing is not sanitizing. A plain rehype pipeline keeps <script> elements and onclick attributes exactly as they were. Safety only comes from rehype-sanitize (or an equivalent).

The basic setup

Terminal
npm install rehype rehype-sanitize
sanitize-basic.mjs
import {rehype} from 'rehype'
import rehypeSanitize from 'rehype-sanitize'

const untrusted = `<p onclick="steal()">Hello <a href="javascript:alert(1)">click</a></p>
<img src="photo.jpg" alt="Photo" onerror="alert(2)">
<script>alert(3)</script>`

const file = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeSanitize)
  .process(untrusted)

console.log(String(file))
Output node sanitize-basic.mjs
<p>Hello <a>click</a></p>
<img src="photo.jpg" alt="Photo">

With no options, rehype-sanitize uses defaultSchema, modeled on what GitHub allows in user content. What it did here:

  • removed the onclick and onerror event handlers;
  • removed the href with a javascript: URL, keeping the link text;
  • removed the <script> element including its content.

How the schema works

The schema is an allowlist. Anything not explicitly allowed is removed. Its main fields are:

FieldControls
tagNamesWhich elements may appear.
attributesWhich properties each element may have, optionally limited to specific values; '*' applies to all elements.
protocolsAllowed URL schemes per property (for example href: http, https, mailto).
stripElements removed along with their content (by default script).
clobber / clobberPrefixProperties whose values get a prefix to prevent DOM clobbering.
required, ancestorsForced property values, and elements that are only allowed inside certain parents.

Extending the default schema

Do not start from an empty schema; start from defaultSchema and add the minimum you need:

sanitize-schema.mjs
import {rehype} from 'rehype'
import rehypeSanitize, {defaultSchema} from 'rehype-sanitize'

// Start from the default (GitHub-style) schema and allow one extra class.
const schema = {
  ...defaultSchema,
  attributes: {
    ...defaultSchema.attributes,
    div: [...(defaultSchema.attributes.div || []), ['className', 'callout']]
  }
}

const file = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeSanitize, schema)
  .process('<div class="callout danger">Careful!</div>')

console.log(String(file))
Output node sanitize-schema.mjs
<div class="callout">Careful!</div>

Writing ['className', 'callout'] allows the class attribute only with the value callout; other classes are dropped. Be very careful with style, <iframe>, <form> and SVG; each of them reopens attack surface.

DOM clobbering and the user-content- prefix

HTML elements with an id or name become properties on window and document. An attacker who can write <img name="getElementById"> can confuse scripts on your page. That is why the default schema prefixes those values with user-content-. It also explains a common surprise: heading ids created before sanitizing get the prefix too.

Order relative to other plugins

sanitize-order.mjs
import {rehype} from 'rehype'
import rehypeSanitize from 'rehype-sanitize'
import rehypeSlug from 'rehype-slug'

const html = '<h2>Intro</h2><p onclick="x()">Text</p>'

// Sanitize first, then add trusted ids: ids stay clean.
const sanitizeFirst = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeSanitize)
  .use(rehypeSlug)
  .process(html)

// Add ids first, then sanitize: the ids get the clobber prefix.
const slugFirst = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeSlug)
  .use(rehypeSanitize)
  .process(html)

console.log('sanitize, then slug:', String(sanitizeFirst))
console.log('slug, then sanitize:', String(slugFirst))
Output node sanitize-order.mjs
sanitize, then slug: <h2 id="intro">Intro</h2><p>Text</p>
slug, then sanitize: <h2 id="user-content-intro">Intro</h2><p>Text</p>

The safe pattern is: sanitize what the author wrote, then let trusted plugins add markup. Plugins that add ids, classes for highlighting or link attributes should run after sanitizing, or their output must be allowed in the schema. The complete pipeline in Markdown to safe HTML follows this pattern.

Common mistakes

  • Sanitizing only in the browser. Anyone can call your API directly. Sanitize on the server, where the content is stored or rendered.
  • Raw HTML from Markdown is invisible. With allowDangerousHtml, embedded HTML stays a raw string unless you add rehype-raw before sanitizing. Never pass allowDangerousHtml to rehype-stringify for untrusted content.
  • Allowing too much. Each extra tag or attribute is a decision. Allow values, not just names, where you can.
  • Treating it as the only defense. Add a Content Security Policy as well. This website, for example, sends a CSP that blocks inline scripts.

Test it

Write tests with known payloads: event handlers, javascript: URLs in mixed case and with entities, SVG and MathML tricks, <base>, <meta http-equiv="refresh">. Parse the output and check that no dangerous element or attribute remains, rather than searching the string. The HTML Sanitizer on this site was tested against 23 such payloads and lets you see what gets removed.

Sources and further reading

Use ↑ ↓ to move, Enter to open.