Nuxt docs, chapter by chapter

API — composables

Every composable in the Nuxt API reference with its purpose, signature shape, side and version — from useAsyncData and useFetch to createUseFetch, useAnnouncer, useLayout, useRuntimeHook, onPrehydrate, useHydration, usePreviewMode and the request/response helpers.

Thirty-odd composables, each with a one-line job. Knowing the whole list is what lets you answer "how would you read a request header during SSR" or "how do you announce a toast to screen readers" without pausing.

Know — data

  • useAsyncData(key, handler, options) / useFetch(url, options) / useLazyAsyncData / useLazyFetch (the lazy: true shorthands): SSR-aware data fetching into the payload. Returns data, status, pending, error, refresh/execute, clear. Both useFetch and useLazyFetch are reserved names transformed by the compiler.
  • createUseAsyncData(options) / createUseFetch(options): compiler macros that build a pre-configured composable; must be an exported declaration in composables/; a plain object gives defaults callers can override, a function of the caller's options gives override mode.
  • useNuxtData(key): read the current cached value for a key (placeholder data, optimistic updates).
  • useHydration(key, get, set): advanced; store data on the server (get) and restore it on the client (set) through the payload; for plugins and modules.
  • usePreviewMode(options): enabled and state; enabled by default when ?preview=true is in the URL; customise with shouldEnable, getState, onEnable, onDisable.

Know — state, config, context

  • useState(key?, init): SSR-friendly shared state; serialised to JSON, so only plain data (combine with shallowRef when deep reactivity is unnecessary); reserved name.
  • useAppConfig(): reactive app.config. useRuntimeConfig(event?): runtime config, with event inside Nitro handlers.
  • useNuxtApp() (throws outside the context) and tryUseNuxtApp(): the runtime context with provide, hook, callHook, payload, isHydrating, ssrContext, runWithContext, vueApp.
  • useCookie(name, options): SSR-friendly cookie ref, JSON-serialised; options include maxAge/expires, path, domain, sameSite, secure, httpOnly, encode/decode, default, watch (true | false | 'shallow'), readonly, refresh; only in the Nuxt context.
  • useLayout(): read-only computed of the layout resolved for the current route (string, or false), including layouts set through route rules.
  • useRoute() and useRouter(): the Vue Router objects ($route/$router in templates).

Know — request and response (server side)

  • useRequestEvent(): the incoming request event (undefined in the browser); its shape follows the server builder, with web-standard req: Request on the way.
  • useRequestHeaders(names?) and useRequestHeader(name): incoming headers (undefined in the browser); the classic use is forwarding cookie to API calls.
  • useRequestURL(): a URL of the incoming request; under cached hybrid routes, set cache.varies for headers the URL depends on.
  • useRequestFetch(): a $fetch that forwards the incoming request's headers to internal API calls during SSR.
  • useResponseHeader(name) (3.14+): a ref that sets a response header, usable in pages and middleware.

Know — head and SEO

  • useHead(input), useHeadSafe(input) (whitelisted attributes only), useSeoMeta(input) (flat, typed meta), and the deprecated useServerSeoMeta (use if (import.meta.server) useSeoMeta(...)).

Know — errors, loading, accessibility, hooks

  • useError(): the current global NuxtError ref (status, statusText, message, data, cause, fatal).
  • useLoadingIndicator({ duration, throttle, estimatedProgress }): isLoading, error, progress plus start({ force }), set(n), finish({ force, error }), clear; hooks into page:loading:start/end.
  • useRouteAnnouncer({ politeness }) (3.12+): message, politeness, set, polite, assertive; follows the page title. useAnnouncer() (4.4.2+): the same API for in-page announcements, paired with <NuxtAnnouncer>.
  • useRuntimeHook(name, fn) (3.14+): register an app hook that is removed when the component scope is disposed.
  • onPrehydrate(callback, key?): run a callback in the browser before hydration (no imports, serialised to a string); advanced, used by colour-mode-style modules to avoid flashes.

How it works

app/pages/dashboard.vue
<script setup lang="ts">
// Request-side helpers during SSR
const ua = useRequestHeader('user-agent')
const url = useRequestURL()
useResponseHeader('X-Robots-Tag').value = 'noindex'

// Layout resolved for this route, including route-rule layouts
const layout = useLayout()

// Optimistic placeholder from a previous page's cache
const { data: cachedPosts } = useNuxtData<Post[]>('posts')
const { data: posts } = await useFetch<Post[]>('/api/posts', { key: 'posts', default: () => cachedPosts.value ?? [] })

// Component-scoped runtime hook
useRuntimeHook('page:finish', () => console.debug('navigated'))

// Announce async results to screen readers
const { polite, assertive } = useAnnouncer()
async function save() {
  try {
    await $fetch('/api/settings', { method: 'POST' })
    polite('Settings saved')
  }
  catch {
    assertive('Saving failed')
  }
}

// Set data on the server, restore it on the client, without useState (advanced)
useHydration('dashboard:rendered-at', () => Date.now(), (v) => console.debug('server rendered at', v))
</script>
app/composables/useAPI.ts
// Compiler macro: must be an exported declaration in composables/
export const useAPI = createUseFetch({ baseURL: '/api', lazy: true })
Gotcha· Reserved composable names

useState, useFetch, useLazyFetch, useAsyncData and useLazyAsyncData are transformed by the compiler (keys are injected). Defining your own function with one of those names breaks in confusing ways; wrap them under a different name, or use the createUse* macros.

Verify before the interview:

The full useCookie option list (watch, readonly, refresh, default) and the useRequestEvent type notes, which are changing with the server-builder work.

docs ↗

Exercise

Exercise
  • Use useRequestHeader('accept-language') to pick a default locale on the server and confirm the value is undefined after a client-side navigation.
  • Set a header with useResponseHeader in a global middleware and check it with curl -I on two different pages.
  • Build a createUseFetch-based useAPI, then a second one in override mode that forces server: false, and compare the behaviour in the Network panel.

Be able to say

Be able to say· Which Nuxt composables only make sense on the server, and what do they return in the browser?

"useRequestEvent, useRequestHeaders, useRequestHeader, useRequestURL, useRequestFetch and useResponseHeader read or write the incoming request and outgoing response, so they carry data during server rendering and return undefined, an empty object, or a no-op on the client after hydration; useRequestURL is the exception because it can reconstruct the URL from window.location. The pattern is to read them in setup or middleware on the server, put what you need into useState or a cookie, and never assume they have values during client-side navigation."

Your notes

Open in Notes

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