composables

useHead

How to use the useHead composable.

The useHead composable is the primary way to manage the head of the document at runtime.

Example

Add a page title and a meta description.

useHead({
  title: 'My Page',
  meta: [
    {
      name: 'description',
      content: 'My page description',
    },
  ],
})

XSS safety

The useHead function only applies minimal sanitization on input to improve the developer experience.

Be careful, do not use this function with any unknown / third party input, that isn't sanitised. It is not possible to guarantee that the output is safe when dealing with unknown input.

If you need XSS safety, sanitise your input or look at using the useSeoMeta or useHeadSafe composables instead.

Schema

interface Head<E extends MergeHead = SchemaAugmentations> {
  title?: string | Promise<string>
  titleTemplate?: string | null | ((title?: string) => string | null)
  templateParams?: { separator?: string } & Record<string, string | Record<string, string>>
  base?: Base<E['base']>
  link?: Link<E['link']>[]
  meta?: Meta<E['meta']>[]
  style?: (Style<E['style']> | string)[]
  script?: (Script<E['script']> | string)[]
  noscript?: (Noscript<E['noscript']> | string)[]
  htmlAttrs?: HtmlAttributes<E['htmlAttrs']>
  bodyAttrs?: BodyAttributes<E['bodyAttrs']>
}

Entry API

The useHead composable returns an API to manage the lifecycle of the head entry. Using this you can either patch or dispose of the entry.

const myPageHead = useHead({
  title: 'My Page',
  meta: [
    {
      name: 'description',
      content: 'My page description',
    },
  ],
})
// removes it
myPageHead.dispose()

How it works

For the base Unhead implementation, it uses the getActiveHead to access the Unhead instance, allowing you to use this function without referencing your head explicitly.

HeadEntryOptions

The second argument to useHead is the HeadEntryOptions.

export interface HeadEntryOptions {
  mode?: RuntimeMode
}

This lets you specify which mode the head should be applied in.

By default, entries are rendered in both server and client. If you'd like to only use a specific mode you can set the mode option to either server or client.

If you intend to server render tags you should instead opt for the useServerHead composable.