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
npm install rehype rehype-sanitizeimport {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))<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
onclickandonerrorevent handlers; - removed the
hrefwith ajavascript: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:
| Field | Controls |
|---|---|
tagNames | Which elements may appear. |
attributes | Which properties each element may have, optionally limited to specific values; '*' applies to all elements. |
protocols | Allowed URL schemes per property (for example href: http, https, mailto). |
strip | Elements removed along with their content (by default script). |
clobber / clobberPrefix | Properties whose values get a prefix to prevent DOM clobbering. |
required, ancestors | Forced 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:
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))<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
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))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 addrehype-rawbefore sanitizing. Never passallowDangerousHtmltorehype-stringifyfor 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.