TypeScript
You're viewing Unhead v3 beta documentation.
Get Started

Install Unhead on TypeScript Projects

Introduction

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

Quick Start: Install unhead, create head with createHead(), and use useHead() directly. For SSR, use separate client/server instances with renderSSRHead().

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

How do I install Unhead?

Install unhead dependency to your project.

bash
pnpm add unhead@beta

How do I 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.

How do I setup server-side rendering?

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) {
    // ...
  }
})
// ..

How do I add my first head 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)
}

What should I do next?

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?