Gathering detailed insights and metrics for sanitize-html
Gathering detailed insights and metrics for sanitize-html
Gathering detailed insights and metrics for sanitize-html
Gathering detailed insights and metrics for sanitize-html
@types/sanitize-html
TypeScript definitions for sanitize-html
xss
Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist
dompurify
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It's written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Firefox and Chrome - as well as almost anything else usin
rehype-sanitize
rehype plugin to sanitize HTML
Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance
npm install sanitize-html
Typescript
Module System
Node Version
NPM Version
55.4
Supply Chain
99.5
Quality
85.9
Maintenance
100
Vulnerability
100
License
Updated on 06 Dec 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
45.2%
Compared to previous day
Last week
4.2%
Compared to previous week
Last month
2.8%
Compared to previous month
Last year
29.9%
Compared to previous year
sanitize-html provides a simple HTML sanitizer with a clear API.
sanitize-html is tolerant. It is well suited for cleaning up HTML fragments such as those created by CKEditor and other rich text editors. It is especially handy for removing unwanted CSS when copying and pasting from Word.
sanitize-html allows you to specify the tags you want to permit, and the permitted
attributes for each of those tags. If an attribute is a known non-boolean value,
and it is empty, it will be removed. For example checked
can be empty, but href
cannot.
If a tag is not permitted, the contents of the tag are not discarded. There are some exceptions to this, discussed below in the "Discarding the entire contents of a disallowed tag" section.
The syntax of poorly closed p
and img
elements is cleaned up.
href
attributes are validated to ensure they only contain http
, https
, ftp
and mailto
URLs. Relative URLs are also allowed. Ditto for src
attributes.
Allowing particular urls as a src
to an iframe tag by filtering hostnames is also supported.
HTML comments are not preserved.
Additionally, sanitize-html
escapes ALL text content - this means that ampersands, greater-than, and less-than signs are converted to their equivalent HTML character references (&
--> &
, <
--> <
, and so on). Additionally, in attribute values, quotation marks are escaped as well ("
--> "
).
sanitize-html is intended for use with Node.js and supports Node 10+. All of its npm dependencies are pure JavaScript. sanitize-html is built on the excellent htmlparser2
module.
sanitize-html is not written in TypeScript and there is no plan to directly support it. There is a community supported typing definition, @types/sanitize-html
, however.
1npm install -D @types/sanitize-html
If esModuleInterop=true
is not set in your tsconfig.json
file, you have to import it with:
1import * as sanitizeHtml from 'sanitize-html';
When using TypeScript, there is a minimum supported version of >=4.5 because of a dependency on the htmlparser2
types.
Any questions or problems while using @types/sanitize-html
should be directed to its maintainers as directed by that project's contribution guidelines.
Think first: why do you want to use it in the browser? Remember, servers must never trust browsers. You can't sanitize HTML for saving on the server anywhere else but on the server.
But, perhaps you'd like to display sanitized HTML immediately in the browser for preview. Or ask the browser to do the sanitization work on every page load. You can if you want to!
1npm install sanitize-html
or
yarn add sanitize-html
The primary change in the 2.x version of sanitize-html is that it no longer includes a build that is ready for browser use. Developers are expected to include sanitize-html in their project builds (e.g., webpack) as they would any other dependency. So while sanitize-html is no longer ready to link to directly in HTML, developers can now more easily process it according to their needs.
Once built and linked in the browser with other project Javascript, it can be used to sanitize HTML strings in front end code:
1import sanitizeHtml from 'sanitize-html'; 2 3const html = "<strong>hello world</strong>"; 4console.log(sanitizeHtml(html)); 5console.log(sanitizeHtml("<img src=x onerror=alert('img') />")); 6console.log(sanitizeHtml("console.log('hello world')")); 7console.log(sanitizeHtml("<script>alert('hello world')</script>"));
Install module from console:
1npm install sanitize-html
Import the module:
1// In ES modules 2import sanitizeHtml from 'sanitize-html'; 3 4// Or in CommonJS 5const sanitizeHtml = require('sanitize-html');
Use it in your JavaScript app:
1const dirty = 'some really tacky HTML'; 2const clean = sanitizeHtml(dirty);
That will allow our default list of allowed tags and attributes through. It's a nice set, but probably not quite what you want. So:
1// Allow only a super restricted set of tags and attributes 2const clean = sanitizeHtml(dirty, { 3 allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ], 4 allowedAttributes: { 5 'a': [ 'href' ] 6 }, 7 allowedIframeHostnames: ['www.youtube.com'] 8});
Boom!
1allowedTags: [ 2 "address", "article", "aside", "footer", "header", "h1", "h2", "h3", "h4", 3 "h5", "h6", "hgroup", "main", "nav", "section", "blockquote", "dd", "div", 4 "dl", "dt", "figcaption", "figure", "hr", "li", "main", "ol", "p", "pre", 5 "ul", "a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn", 6 "em", "i", "kbd", "mark", "q", "rb", "rp", "rt", "rtc", "ruby", "s", "samp", 7 "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", "caption", 8 "col", "colgroup", "table", "tbody", "td", "tfoot", "th", "thead", "tr" 9], 10nonBooleanAttributes: [ 11 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 12 'allow', 'alt', 'as', 'autocapitalize', 'autocomplete', 13 'blocking', 'charset', 'cite', 'class', 'color', 'cols', 14 'colspan', 'content', 'contenteditable', 'coords', 'crossorigin', 15 'data', 'datetime', 'decoding', 'dir', 'dirname', 'download', 16 'draggable', 'enctype', 'enterkeyhint', 'fetchpriority', 'for', 17 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 18 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 19 'http-equiv', 'id', 'imagesizes', 'imagesrcset', 'inputmode', 20 'integrity', 'is', 'itemid', 'itemprop', 'itemref', 'itemtype', 21 'kind', 'label', 'lang', 'list', 'loading', 'low', 'max', 22 'maxlength', 'media', 'method', 'min', 'minlength', 'name', 23 'nonce', 'optimum', 'pattern', 'ping', 'placeholder', 'popover', 24 'popovertarget', 'popovertargetaction', 'poster', 'preload', 25 'referrerpolicy', 'rel', 'rows', 'rowspan', 'sandbox', 'scope', 26 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 27 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', 28 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 29 'value', 'width', 'wrap', 30 // Event handlers 31 'onauxclick', 'onafterprint', 'onbeforematch', 'onbeforeprint', 32 'onbeforeunload', 'onbeforetoggle', 'onblur', 'oncancel', 33 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 34 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy', 35 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', 36 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 37 'ondrop', 'ondurationchange', 'onemptied', 'onended', 38 'onerror', 'onfocus', 'onformdata', 'onhashchange', 'oninput', 39 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 40 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 41 'onloadstart', 'onmessage', 'onmessageerror', 'onmousedown', 42 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 43 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', 44 'onpageshow', 'onpaste', 'onpause', 'onplay', 'onplaying', 45 'onpopstate', 'onprogress', 'onratechange', 'onreset', 'onresize', 46 'onrejectionhandled', 'onscroll', 'onscrollend', 47 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 48 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 49 'ontimeupdate', 'ontoggle', 'onunhandledrejection', 'onunload', 50 'onvolumechange', 'onwaiting', 'onwheel' 51], 52disallowedTagsMode: 'discard', 53allowedAttributes: { 54 a: [ 'href', 'name', 'target' ], 55 // We don't currently allow img itself by default, but 56 // these attributes would make sense if we did. 57 img: [ 'src', 'srcset', 'alt', 'title', 'width', 'height', 'loading' ] 58}, 59// Lots of these won't come up by default because we don't allow them 60selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], 61// URL schemes we permit 62allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ], 63allowedSchemesByTag: {}, 64allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], 65allowProtocolRelative: true, 66enforceHtmlBoundary: false, 67parseStyleAttributes: true
Sure:
1const clean = sanitizeHtml(dirty, {
2 allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ])
3});
If you do not specify allowedTags
or allowedAttributes
, our default list is applied. So if you really want an empty list, specify one.
Simple! Instead of leaving allowedTags
or allowedAttributes
out of the options, set either
one or both to false
:
1allowedTags: false, 2allowedAttributes: false
Very simple! Set nonBooleanAttributes
to []
.
1nonBooleanAttributes: []
Also very simple! Set nonBooleanAttributes
to ['*']
.
Note: This will break common valid cases like checked
and selected
, so this is
unlikely to be what you want. For most ordinary HTML use, it is best to avoid making
this change.
1nonBooleanAttributes: ['*']
Also simple! Set allowedTags
to []
and allowedAttributes
to {}
.
1allowedTags: [], 2allowedAttributes: {}
If you set disallowedTagsMode
to discard
(the default), disallowed tags are discarded. Any text content or subtags are still included, depending on whether the individual subtags are allowed.
If you set disallowedTagsMode
to completelyDiscard
, disallowed tags and any content they contain are discarded. Any subtags are still included, as long as those individual subtags are allowed.
If you set disallowedTagsMode
to escape
, the disallowed tags are escaped rather than discarded. Any text or subtags are handled normally.
If you set disallowedTagsMode
to recursiveEscape
, the disallowed tags are escaped rather than discarded, and the same treatment is applied to all subtags, whether otherwise allowed or not.
When configuring the attribute in allowedAttributes
simply use an object with attribute name
and an allowed values
array. In the following example sandbox="allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-scripts"
would become sandbox="allow-popups allow-scripts"
:
1allowedAttributes: { 2 iframe: [ 3 { 4 name: 'sandbox', 5 multiple: true, 6 values: ['allow-popups', 'allow-same-origin', 'allow-scripts'] 7 } 8 ] 9}
With multiple: true
, several allowed values may appear in the same attribute, separated by spaces. Otherwise the attribute must exactly match one and only one of the allowed values.
If you're incorporating SVG elements like linearGradient
into your content and notice that they're not rendering as expected due to case sensitivity issues, it's essential to prevent sanitize-html
from converting element and attribute names to lowercase. This situation often arises when SVGs fail to display correctly because their case-sensitive tags, such as linearGradient
and attributes like viewBox
, are inadvertently lowercased.
To address this, ensure you set lowerCaseTags: false
and lowerCaseAttributeNames: false
in the parser options of your sanitize-html configuration. This adjustment stops the library from altering the case of your tags and attributes, preserving the integrity of your SVG content.
1allowedTags: [ 'svg', 'g', 'defs', 'linearGradient', 'stop', 'circle' ], 2allowedAttributes: false, 3parser: { 4 lowerCaseTags: false, 5 lowerCaseAttributeNames: false 6}
You can use the *
wildcard to allow all attributes with a certain prefix:
1allowedAttributes: { 2 a: [ 'href', 'data-*' ] 3}
Also you can use the *
as name for a tag, to allow listed attributes to be valid for any tag:
1allowedAttributes: { 2 '*': [ 'href', 'align', 'alt', 'center', 'bgcolor' ] 3}
If you wish to allow specific CSS classes on a particular element, you can do so with the allowedClasses
option. Any other CSS classes are discarded.
This implies that the class
attribute is allowed on that element.
1// Allow only a restricted set of CSS classes and only on the p tag 2const clean = sanitizeHtml(dirty, { 3 allowedTags: [ 'p', 'em', 'strong' ], 4 allowedClasses: { 5 'p': [ 'fancy', 'simple' ] 6 } 7});
Similar to allowedAttributes
, you can use *
to allow classes with a certain prefix, or use *
as a tag name to allow listed classes to be valid for any tag:
1allowedClasses: { 2 'code': [ 'language-*', 'lang-*' ], 3 '*': [ 'fancy', 'simple' ] 4}
Furthermore, regular expressions are supported too:
1allowedClasses: { 2 p: [ /^regex\d{2}$/ ] 3}
If allowedClasses
for a certain tag is false
, all the classes for this tag will be allowed.
Note: It is advised that your regular expressions always begin with
^
so that you are requiring a known prefix. A regular expression with neither^
nor$
just requires that something appear in the middle.
If you wish to allow specific CSS styles on a particular element, you can do that with the allowedStyles
option. Simply declare your desired attributes as regular expression options within an array for the given attribute. Specific elements will inherit allowlisted attributes from the global (*
) attribute. Any other CSS classes are discarded.
You must also use allowedAttributes
to activate the style
attribute for the relevant elements. Otherwise this feature will never come into play.
When constructing regular expressions, don't forget ^
and $
. It's not enough to say "the string should contain this." It must also say "and only this."
URLs in inline styles are NOT filtered by any mechanism other than your regular expression.
1const clean = sanitizeHtml(dirty, { 2 allowedTags: ['p'], 3 allowedAttributes: { 4 'p': ["style"], 5 }, 6 allowedStyles: { 7 '*': { 8 // Match HEX and RGB 9 'color': [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/], 10 'text-align': [/^left$/, /^right$/, /^center$/], 11 // Match any number with px, em, or % 12 'font-size': [/^\d+(?:px|em|%)$/] 13 }, 14 'p': { 15 'font-size': [/^\d+rem$/] 16 } 17 } 18 });
<html></html>
tagsSome text editing applications generate HTML to allow copying over to a web application. These can sometimes include undesirable control characters after terminating html
tag. By default sanitize-html will not discard these characters, instead returning them in sanitized string. This behaviour can be modified using enforceHtmlBoundary
option.
Setting this option to true will instruct sanitize-html to discard all characters outside of html
tag boundaries -- before <html>
and after </html>
tags.
1enforceHtmlBoundary: true
sanitize-html is built on htmlparser2
. By default the only option passed down is decodeEntities: true
. You can set the options to pass by using the parser option.
Security note: changing the parser
settings can be risky. In particular, decodeEntities: false
has known security concerns and a complete test suite does not exist for every possible combination of settings when used with sanitize-html
. If security is your goal we recommend you use the defaults rather than changing parser
, except for the lowerCaseTags
option.
1const clean = sanitizeHtml(dirty, { 2 allowedTags: ['a'], 3 parser: { 4 lowerCaseTags: true 5 } 6});
See the htmlparser2 wiki for the full list of possible options.
What if you want to add or change an attribute? What if you want to transform one tag to another? No problem, it's simple!
The easiest way (will change all ol
tags to ul
tags):
1const clean = sanitizeHtml(dirty, {
2 transformTags: {
3 'ol': 'ul',
4 }
5});
The most advanced usage:
1const clean = sanitizeHtml(dirty, { 2 transformTags: { 3 'ol': function(tagName, attribs) { 4 // My own custom magic goes here 5 return { 6 tagName: 'ul', 7 attribs: { 8 class: 'foo' 9 } 10 }; 11 } 12 } 13});
You can specify the *
wildcard instead of a tag name to transform all tags.
There is also a helper method which should be enough for simple cases in which you want to change the tag and/or add some attributes:
1const clean = sanitizeHtml(dirty, {
2 transformTags: {
3 'ol': sanitizeHtml.simpleTransform('ul', {class: 'foo'}),
4 }
5});
The simpleTransform
helper method has 3 parameters:
1simpleTransform(newTag, newAttributes, shouldMerge)
The last parameter (shouldMerge
) is set to true
by default. When true
, simpleTransform
will merge the current attributes with the new ones (newAttributes
). When false
, all existing attributes are discarded.
You can also add or modify the text contents of a tag:
1const clean = sanitizeHtml(dirty, { 2 transformTags: { 3 'a': function(tagName, attribs) { 4 return { 5 tagName: 'a', 6 text: 'Some text' 7 }; 8 } 9 } 10});
For example, you could transform a link element with missing anchor text:
1<a href="http://somelink.com"></a>
To a link with anchor text:
1<a href="http://somelink.com">Some text</a>
You can provide a filter function to remove unwanted tags. Let's suppose we need to remove empty a
tags like:
1<a href="page.html"></a>
We can do that with the following filter:
1sanitizeHtml(
2 '<p>This is <a href="http://www.linux.org"></a><br/>Linux</p>',
3 {
4 exclusiveFilter: function(frame) {
5 return frame.tag === 'a' && !frame.text.trim();
6 }
7 }
8);
The frame
object supplied to the callback provides the following attributes:
tag
: The tag name, i.e. 'img'
.attribs
: The tag's attributes, i.e. { src: "/path/to/tux.png" }
.text
: The text content of the tag.mediaChildren
: Immediate child tags that are likely to represent self-contained media (e.g., img
, video
, picture
, iframe
). See the mediaTags
variable in src/index.js
for the full list.tagPosition
: The index of the tag's position in the result string.You can also process all text content with a provided filter function. Let's say we want an ellipsis instead of three dots.
1<p>some text...</p>
We can do that with the following filter:
1sanitizeHtml(
2 '<p>some text...</p>',
3 {
4 textFilter: function(text, tagName) {
5 if (['a'].indexOf(tagName) > -1) return //Skip anchor tags
6
7 return text.replace(/\.\.\./, '…');
8 }
9 }
10);
Note that the text passed to the textFilter
method is already escaped for safe display as HTML. You may add markup and use entity escape sequences in your textFilter
.
If you would like to allow iframe tags but want to control the domains that are allowed through, you can provide an array of hostnames and/or array of domains that you would like to allow as iframe sources. This hostname is a property in the options object passed as an argument to the sanitize-html function.
These arrays will be checked against the html that is passed to the function and return only src
urls that include the allowed hostnames or domains in the object. The url in the html that is passed must be formatted correctly (valid hostname) as an embedded iframe otherwise the module will strip out the src from the iframe.
Make sure to pass a valid hostname along with the domain you wish to allow, i.e.:
1allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], 2allowedIframeDomains: ['zoom.us']
You may also specify whether or not to allow relative URLs as iframe sources.
1allowIframeRelativeUrls: true
Note that if unspecified, relative URLs will be allowed by default if no hostname or domain filter is provided but removed by default if a hostname or domain filter is provided.
Remember that the iframe
tag must be allowed as well as the src
attribute.
For example:
1const clean = sanitizeHtml('<p><iframe src="https://www.youtube.com/embed/nykIhs12345"></iframe><p>', { 2 allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 3 allowedClasses: { 4 'p': [ 'fancy', 'simple' ], 5 }, 6 allowedAttributes: { 7 'iframe': ['src'] 8 }, 9 allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] 10});
will pass through as safe whereas:
1const clean = sanitizeHtml('<p><iframe src="https://www.youtube.net/embed/nykIhs12345"></iframe><p>', { 2 allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 3 allowedClasses: { 4 'p': [ 'fancy', 'simple' ], 5 }, 6 allowedAttributes: { 7 'iframe': ['src'] 8 }, 9 allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] 10});
or
1const clean = sanitizeHtml('<p><iframe src="https://www.vimeo/video/12345"></iframe><p>', { 2 allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 3 allowedClasses: { 4 'p': [ 'fancy', 'simple' ], 5 }, 6 allowedAttributes: { 7 'iframe': ['src'] 8 }, 9 allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] 10});
will return an empty iframe tag.
If you want to allow any subdomain of any level you can provide the domain in allowedIframeDomains
1// This iframe markup will pass through as safe. 2const clean = sanitizeHtml('<p><iframe src="https://us02web.zoom.us/embed/12345"></iframe><p>', { 3 allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 4 allowedClasses: { 5 'p': [ 'fancy', 'simple' ], 6 }, 7 allowedAttributes: { 8 'iframe': ['src'] 9 }, 10 allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], 11 allowedIframeDomains: ['zoom.us'] 12});
Similarly to iframes you can allow a script tag on a list of allowlisted domains
1const clean = sanitizeHtml('<script src="https://www.safe.authorized.com/lib.js"></script>', { 2 allowedTags: ['script'], 3 allowedAttributes: { 4 script: ['src'] 5 }, 6 allowedScriptDomains: ['authorized.com'], 7})
You can allow a script tag on a list of allowlisted hostnames too
1const clean = sanitizeHtml('<script src="https://www.authorized.com/lib.js"></script>', {
2 allowedTags: ['script'],
3 allowedAttributes: {
4 script: ['src']
5 },
6 allowedScriptHostnames: [ 'www.authorized.com' ],
7})
By default, we allow the following URL schemes in cases where href
, src
, etc. are allowed:
1[ 'http', 'https', 'ftp', 'mailto' ]
You can override this if you want to:
1sanitizeHtml(
2 // teeny-tiny valid transparent GIF in a data URL
3 '<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" />',
4 {
5 allowedTags: [ 'img', 'p' ],
6 allowedSchemes: [ 'data', 'http' ]
7 }
8);
You can also allow a scheme for a particular tag only:
1allowedSchemes: [ 'http', 'https' ], 2allowedSchemesByTag: { 3 img: [ 'data' ] 4}
And you can forbid the use of protocol-relative URLs (starting with //
) to access another site using the current protocol, which is allowed by default:
1allowProtocolRelative: false
Normally, with a few exceptions, if a tag is not allowed, all of the text within it is preserved, and so are any allowed tags within it.
The exceptions are:
style
, script
, textarea
, option
If you wish to replace this list, for instance to discard whatever is found
inside a noscript
tag, use the nonTextTags
option:
1nonTextTags: [ 'style', 'script', 'textarea', 'option', 'noscript' ]
Note that if you use this option you are responsible for stating the entire list. This gives you the power to retain the content of textarea
, if you want to.
The content still gets escaped properly, with the exception of the script
and
style
tags. Allowing either script
or style
leaves you open to XSS
attacks. Don't do that unless you have good reason to trust their origin.
sanitize-html will log a warning if these tags are allowed, which can be
disabled with the allowVulnerableTags: true
option.
Instead of discarding, or keeping text only, you may enable escaping of the entire content:
1disallowedTagsMode: 'escape'
This will transform <disallowed>content</disallowed>
to <disallowed>content</disallowed>
Valid values are: 'discard'
(default), 'completelyDiscard'
(remove disallowed tag's content), 'escape'
(escape the tag) and 'recursiveEscape'
(to escape the tag and all its content).
If you set disallowedTagsMode
to discard
, disallowed tags are discarded but but the inner content of disallowed tags is kept.
1disallowedTagsMode: 'discard'
This will transform <disallowed>content</disallowed>
to content
If you set disallowedTagsMode
to completelyDiscard
, disallowed tags and any content they contain are discarded. Any subtags are still included, as long as those individual subtags are allowed.
1disallowedTagsMode: 'completelyDiscard'
This will transform <disallowed>content <allowed>content</allowed> </disallowed>
to <allowed>content</allowed>
if you set disallowedTagsMode
to recursiveEscape
, disallowed tag and its children will be escaped even for allowed tags
1disallowedTagsMode: `recursiveEscape`
This will transform <disallowed>hello<p>world</p></disallowed>
to <disallowed>hello<p>world</p></disallowed>
Instead of discarding faulty style attributes, you can allow them by disabling the parsing of style attributes:
1parseStyleAttributes: false
This will transform <div style="invalid-prop: non-existing-value">content</div>
to <div style="invalid-prop: non-existing-value">content</div>
instead of stripping it: <div>content</div>
By default the parseStyleAttributes option is true.
When you disable parsing of the style attribute (parseStyleAttributes: false
) and you pass in options for the allowedStyles property, an error will be thrown. This combination is not permitted.
we recommend sanitizing content server-side in a Node.js environment, as you cannot trust a browser to sanitize things anyway. Consider what a malicious user could do via the network panel, the browser console, or just by writing scripts that submit content similar to what your JavaScript submits. But if you really need to run it on the client in the browser, you may find you need to disable parseStyleAttributes. This is subject to change as it is an upstream issue with postcss, not sanitize-html itself.
You can limit the depth of HTML tags in the document with the nestingLimit
option:
1nestingLimit: 6
This will prevent the user from nesting tags more than 6 levels deep. Tags deeper than that are stripped out exactly as if they were disallowed. Note that this means text is preserved in the usual ways where appropriate.
sanitize-html was created at P'unk Avenue for use in ApostropheCMS, an open-source content management system built on Node.js. If you like sanitize-html you should definitely check out ApostropheCMS.
Feel free to open issues on github.
Stable Version
1
7.5/10
Summary
Sanitize-html Vulnerable To REDoS Attacks
Affected Versions
< 2.7.1
Patched Versions
2.7.1
6
5.3/10
Summary
sanitize-html Information Exposure vulnerability
Affected Versions
< 2.12.1
Patched Versions
2.12.1
6.1/10
Summary
Cross-Site Scripting in sanitize-html
Affected Versions
< 1.2.3
Patched Versions
1.2.3
0/10
Summary
Cross-Site Scripting in sanitize-html
Affected Versions
<= 1.11.1
Patched Versions
1.11.4
5.3/10
Summary
Improper Input Validation in sanitize-html
Affected Versions
< 2.3.1
Patched Versions
2.3.1
5.3/10
Summary
Improper Input Validation in sanitize-html
Affected Versions
< 2.3.2
Patched Versions
2.3.2
6.1/10
Summary
Cross-Site Scripting in sanitize-html
Affected Versions
< 1.4.3
Patched Versions
1.4.3
Reason
all changesets reviewed
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
7 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 8
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-12-02
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More