Install Unhead on TypeScript Projects

Get started with Unhead by installing the dependency to your project.

Introduction

Unhead is built for JavaScript applications that need to manage the head of their document in both server and client-rendered environments.

This guide is for installing Unhead with just TypeScript and no framework. Using a JavaScript framework? Select your framework below or continue with the TypeScript setup below.

Demos

1. Install Dependency

Install unhead dependency to your project. The next tag is for v2 of Unhead.

bash
pnpm add unhead@next

2. Setup Client-Side Rendering

To begin with, we'll import the function to initialize Unhead in our client app from unhead/client.

In Vite this entry file is typically named entry-client.ts. If you're not server-side rendering, you can add this to your main app entry instead.

entry-client.ts
import { createHead } from 'unhead/client'
import { setupCounter } from './counter'
import './style.css'
import './typescript.svg'

window.__UNHEAD__ = createHead()

setupCounter(document.querySelector('#counter') as HTMLButtonElement)

In the above example we are attaching the head instance to the global window object. While hacky, this is useful for when you need to access the head instance in other parts of your app.

Follow the Wrapping Composables guide for the recommended way to handle context.

3. Setup Server-Side Rendering (optional)

Serving your app as an SPA? You can skip this step.

Somewhere in your server entry, create a server head instance.

main.ts
import { createHead } from 'unhead/server'
import typescriptLogo from './typescript.svg'

export function render(_url: string) {
  const head = createHead()
  const html = `<!-- your html -->`
  return { html, head }
}

Within your server.js file or wherever you're handling the template logic, you need to transform the template data for the head tags using transformHtmlTemplate().

server.ts
import { transformHtmlTemplate } from 'unhead/server'
// ...

// Serve HTML
app.use('*all', async (req, res) => {
  try {
    // ...

    const rendered = await render(url)
    const html = await transformHtmlTemplate(
      rendered.head,
      template.replace(`<!--app-html-->`, rendered.html ?? '')
    )

    res.status(200).set({ 'Content-Type': 'text/html' }).send(html)
  }
  catch (e) {
    // ...
  }
})
// ..

4. Your First Tags

Done! Your app should now be rendering head tags on the server and client.

To improve your apps stability, Unhead will now insert important default tags for you.

  • <meta charset="utf-8">
  • <meta name="viewport" content="width=device-width, initial-scale=1">
  • <html lang="en">

You may need to change these for your app requirements, for example you may want to change the default language. Adding tags in your server entry means you won't add any weight to your client bundle.

main.ts
import { createHead } from 'unhead/server'
import typescriptLogo from './typescript.svg'

export function render(_url: string) {
  const head = createHead({
    // change default initial lang
    init: [
      {
        title: 'Default title',
        titleTemplate: '%s | My Site',
        htmlAttrs: { lang: 'fr' }
      },
    ]
  })
  const html = `<!-- your html -->`
  return { html, head }
}

Here is an example of how you can use useHead in your app for a counter:

counter.ts
import { useHead } from 'unhead'

export function setupCounter(element: HTMLButtonElement) {
  let counter = 0
  const setCounter = (count: number) => {
    counter = count
    element.innerHTML = `count is ${counter}`
    useHead(window.__UNHEAD__, {
      title: () => counter ? `count is ${counter}` : null,
    })
  }
  element.addEventListener('click', () => setCounter(counter + 1))
  setCounter(0)
}

Next Steps

Your app is now setup for head management, congrats! 🎉

Try next:

  1. Learn more about app context in the Wrapping Composables guide
  2. Consider using the Vite plugin
Did this page help you?