Nuxt docs, chapter by chapter

API — utils

Every utility in the Nuxt API reference — the define* macros, navigation helpers, error helpers, data and state cache helpers, preload and prefetch helpers, lifecycle utilities and the server-side response helpers.

The utils are the verbs of a Nuxt app: define, navigate, error, refresh, preload. Most have one or two options that matter and one rule about where they may be called.

Know — define* helpers and macros

  • definePageMeta(meta): compiler macro for pages; PageMeta fields: validate, redirect, name, path, props, alias, groups, pageTransition, layoutTransition, viewTransition, key, keepalive, layout (string, false, ref, or { name, props }), middleware, scrollToTop, plus custom keys typed through PageMeta augmentation.
  • defineNuxtRouteMiddleware((to, from) => …): typed middleware; return nothing, navigateTo(...), or abortNavigation(...).
  • defineNuxtPlugin(fn | object): object form with name, enforce ('pre' | 'default' | 'post'), dependsOn, order, parallel, setup, hooks, env.islands.
  • defineNuxtComponent(options): Options API components with asyncData() and head() support; <script setup> is the recommended path.
  • defineRouteRules(rules): page-level route rules (experimental inlineRouteRules); translated to routeRules keyed by the page path; dynamic segments become wildcards.
  • defineLazyHydrationComponent(strategy, loader): a lazy component with a strategy ('visible' | 'idle' | 'interaction' | 'mediaQuery' | 'if' | 'time' | 'never') configured through the matching hydrate-on-* prop.

Know — navigation

  • navigateTo(to, options): works in the Nuxt context on both sides; options replace, redirectCode (server status, default 302), external (required for off-site URLs; also open: { target } for new windows). Always return or await it; not usable in Nitro routes (use sendRedirect). With experimental.navigateToEarlyReturn it short-circuits the rest of setup Nuxt 5 .
  • abortNavigation(err?): only inside route middleware; stops the navigation and optionally throws an error or a string.
  • addRouteMiddleware(name | fn, fn?, { global }): register middleware at runtime (plugins), named or anonymous, optionally global.
  • onBeforeRouteLeave, onBeforeRouteUpdate: Vue Router in-component guards, re-exported.
  • setPageLayout(name): change the layout at runtime (in middleware or setup, before the layout renders).

Know — errors

  • createError(err): string or { status, statusText, message, data, cause, fatal } (older statusCode/statusMessage still accepted, deprecated); on the server throwing it renders the error page, on the client it is non-fatal unless fatal: true; in API routes it sets the response status and prefers a short statusText.
  • showError(err): force the full-page error (calls app:error); clearError({ redirect }): leave it.

Know — data and state cache

  • refreshNuxtData(keys?): re-run all or specific useAsyncData/useFetch instances (also inside KeepAlive-deactivated components); returns a promise.
  • clearNuxtData(keys?): drop cached data, error and pending promises (keys, array, or predicate). clearNuxtState(keys?, { reset }): delete useState entries; reset: true (4.4) restores the init value instead.
  • refreshCookie(name) (3.10): resync a useCookie ref after the browser cookie changed (automatic with the cookieStore experimental flag, enabled by default since 3.12 where supported).
  • updateAppConfig(partial): deep-assign into app.config at runtime.

Know — lifecycle and performance

  • callOnce(key?, fn, { mode }) (3.9): run once during SSR or CSR, never both; mode: 'navigation' (3.15) re-runs on each client-side navigation.
  • onNuxtReady(fn): run after hydration when the browser is idle (client only).
  • prefetchComponents / preloadComponents (global components only; prefetch currently behaves like preload), preloadRouteComponents(path) (what NuxtLink does automatically), all no-ops on the server.
  • prerenderRoutes(paths): hint Nitro to prerender extra routes (including API routes) during prerendering; no effect otherwise; set responseType when fetching prerendered API routes.
  • reloadNuxtApp({ path, ttl, force, persistState }): hard reload, optionally persisting useState (experimental.restoreState restores it).

Know — server-side response and fetching

  • setResponseStatus(event, code, text?): set the SSR response status from a page or middleware (event from useRequestEvent()); no effect in the browser.
  • $fetch: ofetch, global; in-process calls to internal routes on the server; interceptors; $fetch.create() for instances; $fetch.raw() for the full response.

How it works

app/pages/admin/[section].vue
<script setup lang="ts">
definePageMeta({
  middleware: [
    (to) => {
      if (!['users', 'billing'].includes(String(to.params.section))) return abortNavigation(createError({ status: 404, statusText: 'Unknown section' }))
    },
    'auth',
  ],
  layout: { name: 'admin', props: { dense: true } },
  scrollToTop: true,
})

defineRouteRules({ ssr: false }) // experimental.inlineRouteRules: turns this page into an SPA route

const LazyChart = defineLazyHydrationComponent('visible', () => import('~/components/admin/Chart.vue'))

await callOnce('admin:bootstrap', async () => {
  useState('admin:flags').value = await $fetch('/api/admin/flags')
})

onNuxtReady(() => preloadRouteComponents('/admin/billing'))

async function saveAndLeave() {
  await $fetch('/api/admin/settings', { method: 'POST' })
  await refreshNuxtData('admin:settings')
  return navigateTo('/admin/users', { replace: true })
}

onBeforeRouteLeave(() => { /* confirm unsaved changes */ })
</script>

<template>
  <LazyChart :hydrate-on-visible="{ rootMargin: '200px' }" />
</template>
app/middleware/status.global.ts
export default defineNuxtRouteMiddleware((to) => {
  const event = useRequestEvent()
  if (event && to.path === '/gone') setResponseStatus(event, 410, 'Gone')
})
Gotcha· navigateTo inside a Nitro route

navigateTo needs the Nuxt app context, which server routes do not have. In server/ use sendRedirect(event, '/target', 302); the docs make this distinction explicitly.

Verify before the interview:

The current PageMeta field list (notably groups, props, viewTransition and the object form of layout) and the defineLazyHydrationComponent strategy names.

docs ↗

Exercise

Exercise
  • Use navigateTo with redirectCode: 301 in middleware and check the status with curl -I; then try navigateTo in a server route and read the error.
  • Use clearNuxtState('counter', { reset: true }) versus without reset, and log the value after each.
  • Enable experimental.inlineRouteRules, add defineRouteRules({ prerender: true }) to a page, build, and find the generated HTML in .output/public.

Be able to say

Be able to say· Which Nuxt utilities are compiler macros, and why does that matter?

"definePageMeta, defineRouteRules, defineLazyHydrationComponent, createUseFetch and createUseAsyncData are compiler macros, and useState, useFetch, useAsyncData and their lazy variants are transformed by the compiler as well. It matters because they are processed at build time: definePageMeta cannot reference component variables, defineRouteRules only works for paths that translate to a route pattern, the createUse* factories must be exported declarations in composables/, and you must not define your own functions with the reserved names. The rest of the utils are ordinary functions that need the Nuxt context but run at runtime."

Your notes

Open in Notes

Nothing yet. Notes filed here show up on this page and the section overview.