Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Nuxt 3.x reference covering SSR, file-based routing, auto-imports, server routes, and Nitro deployment.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/advanced-hooks.md
1---2name: lifecycle-hooks3description: Nuxt and Nitro hooks for extending build-time and runtime behavior4---56# Lifecycle Hooks78Nuxt provides hooks to tap into the build process, application lifecycle, and server runtime.910## Build-time Hooks (Nuxt)1112Used in `nuxt.config.ts` or modules:1314### In nuxt.config.ts1516```ts17// nuxt.config.ts18export default defineNuxtConfig({19hooks: {20'build:before': () => {21console.log('Build starting...')22},23'pages:extend': (pages) => {24// Add custom pages25pages.push({26name: 'custom',27path: '/custom',28file: '~/pages/custom.vue',29})30},31'components:dirs': (dirs) => {32// Add component directories33dirs.push({ path: '~/extra-components' })34},35},36})37```3839### In Modules4041```ts42// modules/my-module.ts43export default defineNuxtModule({44setup(options, nuxt) {45nuxt.hook('ready', async (nuxt) => {46console.log('Nuxt is ready')47})4849nuxt.hook('close', async (nuxt) => {50console.log('Nuxt is closing')51})5253nuxt.hook('modules:done', () => {54console.log('All modules loaded')55})56},57})58```5960### Common Build Hooks6162| Hook | When |63|------|------|64| `ready` | Nuxt initialization complete |65| `close` | Nuxt is closing |66| `modules:done` | All modules installed |67| `build:before` | Before build starts |68| `build:done` | Build complete |69| `pages:extend` | Pages routes resolved |70| `components:dirs` | Component dirs being resolved |71| `imports:extend` | Auto-imports being resolved |72| `nitro:config` | Before Nitro config finalized |73| `vite:extend` | Vite context created |74| `vite:extendConfig` | Before Vite config finalized |7576## App Hooks (Runtime)7778Used in plugins and composables:7980### In Plugins8182```ts83// plugins/lifecycle.ts84export default defineNuxtPlugin((nuxtApp) => {85nuxtApp.hook('app:created', (vueApp) => {86console.log('Vue app created')87})8889nuxtApp.hook('app:mounted', (vueApp) => {90console.log('App mounted')91})9293nuxtApp.hook('page:start', () => {94console.log('Page navigation starting')95})9697nuxtApp.hook('page:finish', () => {98console.log('Page navigation finished')99})100101nuxtApp.hook('page:loading:start', () => {102console.log('Page loading started')103})104105nuxtApp.hook('page:loading:end', () => {106console.log('Page loading ended')107})108})109```110111### Common App Hooks112113| Hook | When |114|------|------|115| `app:created` | Vue app created |116| `app:mounted` | Vue app mounted (client only) |117| `app:error` | Fatal error occurred |118| `page:start` | Page navigation starting |119| `page:finish` | Page navigation finished |120| `page:loading:start` | Loading indicator should show |121| `page:loading:end` | Loading indicator should hide |122| `link:prefetch` | Link is being prefetched |123124### Using Runtime Hooks125126```ts127// composables/usePageTracking.ts128export function usePageTracking() {129const nuxtApp = useNuxtApp()130131nuxtApp.hook('page:finish', () => {132trackPageView(useRoute().path)133})134}135```136137## Server Hooks (Nitro)138139Used in server plugins:140141```ts142// server/plugins/hooks.ts143export default defineNitroPlugin((nitroApp) => {144// Modify HTML before sending145nitroApp.hooks.hook('render:html', (html, { event }) => {146html.head.push('<meta name="custom" content="value">')147html.bodyAppend.push('<script>console.log("injected")</script>')148})149150// Modify response151nitroApp.hooks.hook('render:response', (response, { event }) => {152console.log('Sending response:', response.statusCode)153})154155// Before request156nitroApp.hooks.hook('request', (event) => {157console.log('Request:', event.path)158})159160// After response161nitroApp.hooks.hook('afterResponse', (event) => {162console.log('Response sent')163})164})165```166167### Common Nitro Hooks168169| Hook | When |170|------|------|171| `request` | Request received |172| `beforeResponse` | Before sending response |173| `afterResponse` | After response sent |174| `render:html` | Before HTML is sent |175| `render:response` | Before response is finalized |176| `error` | Error occurred |177178## Custom Hooks179180### Define Custom Hook Types181182```ts183// types/hooks.d.ts184import type { HookResult } from '@nuxt/schema'185186declare module '#app' {187interface RuntimeNuxtHooks {188'my-app:event': (data: MyEventData) => HookResult189}190}191192declare module '@nuxt/schema' {193interface NuxtHooks {194'my-module:init': () => HookResult195}196}197198declare module 'nitropack/types' {199interface NitroRuntimeHooks {200'my-server:event': (data: any) => void201}202}203```204205### Call Custom Hooks206207```ts208// In a plugin209export default defineNuxtPlugin((nuxtApp) => {210// Call custom hook211nuxtApp.callHook('my-app:event', { type: 'custom' })212})213214// In a module215export default defineNuxtModule({216setup(options, nuxt) {217nuxt.callHook('my-module:init')218},219})220```221222## useRuntimeHook223224Call hooks at runtime from components:225226```vue227<script setup lang="ts">228// Register a callback for a runtime hook229useRuntimeHook('app:error', (error) => {230console.error('App error:', error)231})232</script>233```234235## Hook Examples236237### Page View Tracking238239```ts240// plugins/analytics.client.ts241export default defineNuxtPlugin((nuxtApp) => {242nuxtApp.hook('page:finish', () => {243const route = useRoute()244analytics.track('pageview', {245path: route.path,246title: document.title,247})248})249})250```251252### Performance Monitoring253254```ts255// plugins/performance.client.ts256export default defineNuxtPlugin((nuxtApp) => {257let navigationStart: number258259nuxtApp.hook('page:start', () => {260navigationStart = performance.now()261})262263nuxtApp.hook('page:finish', () => {264const duration = performance.now() - navigationStart265console.log(`Navigation took ${duration}ms`)266})267})268```269270### Inject HTML271272```ts273// server/plugins/inject.ts274export default defineNitroPlugin((nitroApp) => {275nitroApp.hooks.hook('render:html', (html) => {276html.head.push(`277<script>278window.APP_CONFIG = ${JSON.stringify(config)}279</script>280`)281})282})283```284285<!--286Source references:287- https://nuxt.com/docs/guide/going-further/hooks288- https://nuxt.com/docs/api/advanced/hooks289-->290