Composables

useServerHead

Learn how to use server only tags.

The useServerHead offers the same API as useHead but only works on the server.

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

useServerHeadSafe

The useServerHead function only applies minimal sanitisation on input to improve the developer experience.

If you're working with unknown or third party input, you should use useServerHeadSafe instead.

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

Why Server Tags

Server tags can be useful for improving the performance of your app, as there will be fewer tags to hydrate. An example would be avoiding hydration tags which only robots need from the initial page load.

It can also be useful for rendering tags which wouldn't be possible to render client side, such as link tags that use dynamic imports import('~/assets/my-file.png?url).

Tree Shaking

You can tree shake the useServerHead composable in most cases as robots will only need the initial SSR response.

For Nuxt, this is taken care of for you. For other implementations, you will need to use the Unhead Plugin.

Caveats

Server rendered tags do not have lifecycle events. If you use server rendered tags on a specific page they won't be removed when you leave the page .

The exception being, if a duplicate tag is registered, they will be replaced.

Let's look at an example, an about page.

// pages/about
useServerHead({
  meta: [
    {
      name: 'description',
      content: 'About page description',
    },
  ],
})

When server-side rendered we'll get the expected tags, however when the client hydrates the code won't be ran.

This means if we move from the /about page to a /contact page, the tags will still be there.

For meta tags this isn't an issue, but for other tags it can be.

In these instances you should either avoid using server tags, implement them only in root files or implement them with the key property so they can be replaced elsewhere.

Examples

// pages/about
useServerHead({
  script: [
    {
      src: await import('~/assets/js/about.js?url'),
      key: 'page-script'
    }
  ]
})
// pages/contact
useHead({
  script: [
    {
      // This will remove the script from the about page
      key: 'page-script'
    }
  ]
})