Skip to content

useHtmlSanitizer ​

Sanitizes HTML with DOMPurify, allowing only the markup WeTipTap produces. WeHtml uses it to render stored rich text safely.

Usage ​

ts
const { sanitize } = useHtmlSanitizer()

sanitize('<p onclick="alert(1)">Hi <strong>there</strong></p><script>alert(2)</script>')
// '<p>Hi <strong>there</strong></p>'

// per-call additions, on top of `we.html`
sanitize(html, { addTags: ['img'], addAttributes: ['src'] })

Type Signature ​

ts
function useHtmlSanitizer(): {
  sanitize: (html?: string | null, options?: WeHtmlOptions) => string
}

interface WeHtmlOptions {
  addTags?: string[]
  addAttributes?: string[]
  forbidTags?: string[]
  forbidAttributes?: string[]
}

Allowed markup ​

Allowed by default
Tagsp, br, strong, b, em, i, u, s, code, pre, blockquote, h1–h6, ul, ol, li, hr, a
Attributeshref, target, rel, start, type

Everything else is removed: images, style, class, SVG, iframes, event handlers. DOMPurify also drops unsafe URLs such as javascript: links.

Options ​

sanitize(html, options) merges options with the module's we.html config (arrays are concatenated) and passes them to DOMPurify:

OptionDOMPurifyDescription
addTagsADD_TAGSExtra tags to allow
addAttributesADD_ATTRExtra attributes to allow
forbidTagsFORBID_TAGSTags to remove even if allowed
forbidAttributesFORBID_ATTRAttributes to remove even if allowed

Project-wide customizations go in nuxt.config:

ts
export default defineNuxtConfig({
  we: {
    html: {
      addTags: ['img'],
      addAttributes: ['src', 'alt'],
      forbidTags: [],
      forbidAttributes: [],
    },
  },
})

The options only add to or subtract from the default list: there is no way to replace it.

Server-side rendering ​

DOMPurify needs a DOM. Where none is available (e.g. during SSR) sanitize returns '' instead of unsanitized HTML. WeHtml handles this by rendering after hydration; when calling sanitize yourself, do it on the client.

Source Code ​