useHeadSafe()

How to use the useHeadSafe composable.

The useHeadSafe composable is a wrapper around the useHead composable that restricts the input to only allow safe values.

Logic

There is a whitelist of allowed tags and attributes. If you try to use a tag or attribute that isn't on the whitelist, it will be ignored.

The whitelist is restrictive, as there are many vectors for XSS attacks. If you need to use a tag or attribute that isn't on the whitelist, you can use the useHead composable instead, just make sure you sanitise the input.

The whitelist is as follows:

const WhitelistAttributes = {
  htmlAttrs: ['class', 'style', 'lang', 'dir'] satisfies (keyof HtmlAttributes)[],
  bodyAttrs: ['class', 'style'] satisfies (keyof BodyAttributes)[],
  meta: ['name', 'property', 'charset', 'content', 'media'] satisfies (keyof Meta)[],
  noscript: ['textContent'] satisfies (Partial<keyof Noscript> | 'textContent')[],
  style: ['media', 'textContent', 'nonce', 'title', 'blocking'] satisfies (Partial<keyof Style> | 'textContent')[],
  script: ['type', 'textContent', 'nonce', 'blocking'] satisfies (Partial<keyof Script> | 'textContent')[],
  link: ['color', 'crossorigin', 'fetchpriority', 'href', 'hreflang', 'imagesrcset', 'imagesizes', 'integrity', 'media', 'referrerpolicy', 'rel', 'sizes', 'type'] satisfies (keyof Link)[],
} as const
  • Scripts of any sort are not allowed, except for JSON. <script type="application/json">, use textContent: myObject.
  • http-equiv is not allowed on meta.
  • data-* attributes are allowed.
  • Link tags will strip invalid href's (data:, javascript:) and do not support rels: ['stylesheet', 'canonical', 'modulepreload', 'prerender', 'preload', 'prefetch'].

Example

Using head data from an untrusted data source.

const thirdPartyMeta = loadMeta()

useHeadSafe(thirdPartyMeta)

Styles

While styles are permitted it's important to note that clickjacking is still possible. You should ensure that your styles are safe to use.

Did this page help you?