hast utility to sanitize nodes

Downloads in past


3814.1.0a month ago7 years agoMinified + gzip package size for hast-util-sanitize in KB


!Buildbuild-badgebuild !Coveragecoverage-badgecoverage !Downloadsdownloads-badgedownloads !Sizesize-badgesize !Sponsorssponsors-badgecollective !Backersbackers-badgecollective !Chatchat-badgechat
hast utility to make trees safe.


*   [`sanitize(tree[, schema])`](#sanitizetree-schema)
*   [`Schema`](#schema)

What is this?

This package is a utility that can make a tree that potentially contains dangerous user content safe for use. It defaults to what GitHub does to clean unsafe markup, but you can change that.

When should I use this?

This package is needed whenever you deal with potentially dangerous user content.
The plugin rehype-sanitizerehype-sanitize wraps this utility to also sanitize HTML at a higher-level (easier) abstraction.


This package is ESM onlyesm. In Node.js (version 14.14+, 16.0+), install with npm:
npm install hast-util-sanitize

In Deno with esm.shesmsh:
import {sanitize} from 'https://esm.sh/hast-util-sanitize@4'

In browsers with esm.shesmsh:
<script type="module">
  import {sanitize} from 'https://esm.sh/hast-util-sanitize@4?bundle'


import {u} from 'unist-builder'
import {h} from 'hastscript'
import {sanitize} from 'hast-util-sanitize'
import {toHtml} from 'hast-util-to-html'

const tree = h('div', {onmouseover: 'alert("alpha")'}, [
    {href: 'jAva script:alert("bravo")', onclick: 'alert("charlie")'},
  u('text', '\n'),
  h('script', 'alert("charlie")'),
  u('text', '\n'),
  h('img', {src: 'x', onerror: 'alert("delta")'}),
  u('text', '\n'),
  h('iframe', {src: 'javascript:alert("echo")'}),
  u('text', '\n'),
  h('math', h('mi', {'xlink:href': 'data:x,<script>alert("foxtrot")</script>'}))

const unsanitized = toHtml(tree)
const sanitized = toHtml(sanitize(tree))


<div onmouseover="alert("alpha")"><a href="jAva script:alert("bravo")" onclick="alert("charlie")">delta</a>
<img src="x" onerror="alert("delta")">
<iframe src="javascript:alert("echo")"></iframe>
<math><mi xlink:href="data:x,<script>alert("foxtrot")</script>"></mi></math></div>


<img src="x">



This package exports the identifiers sanitize and defaultSchema. There is no default export.

sanitize(tree[, schema])

Sanitize a tree.
A new, sanitized, tree (Nodenode).


Sanitation schema that defines if and how nodes and properties should be cleaned. The default schema is exported as defaultSchema, which defaults to GitHub style sanitation. If any top-level key isn’t given, it defaults to GitHub’s style too.
For a thorough sample, see the code for defaultSchemadefault-schema.
To extend the standard schema with a few changes, clone defaultSchema like so:
import {h} from 'hastscript'
import deepmerge from 'deepmerge' // You can use `structuredClone` in modern JS.
import {sanitize, defaultSchema} from 'hast-util-sanitize'

const schema = deepmerge(defaultSchema, {attributes: {'*': ['className']}})

const tree = sanitize(h('div', {className: ['foo']}), schema)

// `tree` still has `className`.
// {
//   type: 'element',
//   tagName: 'div',
//   properties: {className: ['foo']},
//   children: []
// }
Map of tag names to allowed property namesname (Record<string, Array<string>>).
The special '*' key defines property namesname allowed on all elementselement.
One special value, 'data*', can be used to allow all data properties.
attributes: {
  a: ['href'],
  img: ['src', 'longDesc'],
  // …
  '*': [
    // …

Instead of a single string (such as type), which allows any property valuevalue of that property namename, it’s also possible to provide an array (such as ['type', 'checkbox'] or ['className', /^hljs-/]), where the first entry is the property name, and all other entries are property values allowed (or regular expressions that are tested with values). This is how the default GitHub schema allows only disabled checkbox inputs:
attributes: {
  // …
  input: [
    ['type', 'checkbox'],
    ['disabled', true]
  // …

This also plays well with properties that accept space- or comma-separated values, such as class. Say you wanted to allow certain classes on span elements for syntax highlighting, that can be done like this:
// …
span: [
  ['className', 'token', 'number', 'operator']
// …
Map of tag names to required property namesname and their default property valuevalue (Record<string, Record<string, *>>). If the defined keys do not exist in an elementelement’s propertiesproperties, they are added and set to the specified value.
Note that properties are first checked based on the schema at attributes, so properties could be removed by that step and then added again through required.
required: {
  input: {type: 'checkbox', disabled: true}
List of allowed tag names (Array<string>).
tagNames: [
  // …
Map of protocols to allow in property valuesvalue (Record<string, Array<string>>).
protocols: {
  href: ['http', 'https', 'mailto'],
  // …
  longDesc: ['http', 'https']
Map of tag names to their required ancestorancestor elementselement (Record<string, Array<string>>).
ancestors: {
  li: ['ol', 'ul'],
  // …
  tr: ['table']
List of allowed property namesname which can clobber (Array<string>).
clobber: ['name', 'id']
Prefix to use before potentially clobbering property namesname (string).
clobberPrefix: 'user-content-'
Names of elementselement to strip from the treetree (Array<string>).
By default, unsafe elements are replaced by their childrenchild. Some elements, should however be entirely stripped from the tree.
strip: ['script']
Whether to allow commentscomment (boolean, default: false).
allowComments: true
Whether to allow doctypesdoctype (boolean, default: false).
allowDoctypes: true


This package is fully typed with TypeScript. It exports the additional type Schema.


Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 14.14+ and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.


By default, hast-util-sanitize will make everything safe to use. But when used incorrectly, deviating from the defaults can open you up to a cross-site scripting (XSS)xss attack.
Use hast-util-sanitize after the last unsafe thing: everything after it could be unsafe (but is fine if you do trust it).


— rehype plugin


See contributing.mdcontributing in syntax-tree/.githubhealth for ways to get started. See support.mdsupport for ways to get help.
This project has a code of conductcoc. By interacting with this repository, organization, or community you agree to abide by its terms.


MITlicense © Titus Wormerauthor