composables
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',
},
],
})
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',
},
],
})
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)
.
To get avoid bundling useServerHead
to the client, you can install the Unhead Vite Plugin.
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.
// pages/about
useServerHead({
scripts: [
{
src: await import('~/assets/js/about.js?url'),
key: 'page-script'
}
]
})
// pages/contact
useHead({
scripts: [
{
// This will remove the script from the about page
key: 'page-script'
}
]
})