TypeScript
Hooks

init Hook

The init hook is called when a new Unhead instance is created and initialized. This hook provides a great opportunity to set up any global configurations or initial state needed for your head management.

Hook Signature

export interface Hook {
  init: (ctx: Unhead<any>) => HookResult
}

Parameters

NameTypeDescription
ctxUnhead<any>The Unhead instance that has been initialized

Returns

HookResult which is either void or Promise<void>

Usage Example

import { createHead } from 'unhead'

const head = createHead({
  hooks: {
    init: (head) => {
      // Log when head instance is initialized
      console.log('Unhead instance has been initialized!')

      // Set up any initial configuration
      head.push({
        title: 'Default Page Title',
        meta: [
          { name: 'description', content: 'Default page description' }
        ]
      })
    }
  }
})

Use Cases

Setting Default Head Configuration

Use the init hook to set default head configuration values that should be applied across your entire application:

import { defineHeadPlugin } from 'unhead'

export const defaultMetaPlugin = defineHeadPlugin({
  hooks: {
    init: (head) => {
      head.push({
        meta: [
          { charset: 'utf-8' },
          { name: 'viewport', content: 'width=device-width, initial-scale=1' },
          { name: 'format-detection', content: 'telephone=no' }
        ]
      })
    }
  }
})

Initializing Third-party Services

The init hook is also useful for initializing third-party services that need to be configured when your application starts:

import { defineHeadPlugin } from 'unhead'

export const analyticsInitPlugin = defineHeadPlugin({
  hooks: {
    init: (head) => {
      // Configure analytics service
      if (!head.ssr) {
        window.dataLayer = window.dataLayer || []
        window.gtag = function (args) {
          window.dataLayer.push(...args)
        }
        gtag('js', new Date())
        gtag('config', 'G-XXXXXXXXXX')
      }
    }
  }
})
Did this page help you?