new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Nuxt · Guide · all subjects

general-reference

388 notes in this subject, read out of this brain and free to use. This is page 4 of 7.

Custom runtime hook definition example

Custom hooks are defined by augmenting module interfaces. Example: declare module '#app' { interface RuntimeNuxtHooks { 'your-nuxt-runtime-hook': () => HookResult } interface NuxtHooks { 'your-nuxt-hook': () => HookResult } } declare module 'nitro/types' { interface NitroRuntimeHooks { 'your-nitro-hook': () => void } }

useNuxtApp composable

Within composables, plugins and components, you can access the nuxtApp instance using the useNuxtApp() composable. If you want to check whether the context is present without throwing an exception, use tryUseNuxtApp() instead.

NuxtApp runtime context access

In Nuxt, you can access runtime app context within composables, components, and plugins. The Nuxt context is only accessible in plugins, Nuxt hooks, Nuxt middleware (if wrapped in defineNuxtRouteMiddleware), and setup functions in pages and components.

Composable outside context error handling

If a composable is called without access to the Nuxt context, you may get an error stating that 'A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function.' You can resolve this by using nuxtApp.runWithContext() to explicitly call functions within the context.

Accessing nuxtApp in composables example

Example of accessing nuxtApp in a composable: ```ts export function useMyComposable () { const nuxtApp = useNuxtApp() // access runtime nuxt app instance } ```

Git repository layer sources

You can extend from git repositories using these formats: github:username/repoName, github:username/repoName/base, github:username/repoName#dev, github:username/repoName#v1.0.0, gitlab:username/repoName, bitbucket:username/repoName.

Authentication for private remote layers

To extend a private remote source, add the environment variable GIGET_AUTH=<token> to provide a token.

Self-hosted git instance URLs for layers

To extend from a self-hosted GitHub or GitLab instance, supply its URL with the GIGET_GITHUB_URL=<url> or GIGET_GITLAB_URL=<url> environment variable, or configure it directly with the auth option in nuxt.config.

Remote layer dependencies limitation

When extending a remote source as a layer, you cannot access its dependencies outside of Nuxt. For example, if the remote layer depends on an eslint plugin, this will not be usable in your eslint config because dependencies are located in node_modules/.c12/layer_name/node_modules/ which is not accessible to your package manager.

Installing dependencies for git remote layers

When using git remote sources, if a layer has npm dependencies and you wish to install them, specify install: true in your layer options: extends: [['github:username/repoName', { install: true }]].

Publishing Nuxt layer as npm package

To publish a Nuxt layer as an npm package, ensure package.json has correct properties: name, version, type (set to module), main (set to ./nuxt.config.ts), dependencies (explicitly add all imported dependencies), and devDependencies (include nuxt and testing dependencies).

Extending from npm package layers

To extend from an npm package layer, the module must be published to npm and installed as a devDependency in the user's project. Then use the module name in extends: extends: ['@scope/moduleName'] or extends: ['moduleName'].

Nuxt layers implementation libraries

Configuration loading and extends support for Nuxt layers is handled by unjs/c12, merged using unjs/defu, and remote git sources are supported using unjs/giget.

Layer starter template initialization

To initialize a layer, use: npm create nuxt -- --template layer nuxt-layer. This creates a basic structure based on the nuxt/starter/layer template that you can build upon.

Relative paths resolution in layer nuxt.config

When using relative paths in a layer's nuxt.config file (except for nested extends), they are resolved relative to the user's project instead of the layer. As a workaround, use full resolved paths by importing fileURLToPath and using dirname and join from node:path.

Global alias resolution in layer components and composables

When importing using global aliases (such as ~/ and @/) in layer components and composables, these aliases are resolved relative to the user's project paths, not the layer. As a workaround, use relative paths or named layer aliases.

Named layer aliases for auto-scanned layers

Auto-scanned layers from ~/layers directory automatically create aliases. For example, ~/layers/test layer is accessible via #layers/test. To create named aliases for other layers, specify a name in the layer configuration using $meta.name in nuxt.config.

Nuxt layers definition and purpose

Nuxt layers are a powerful feature that allows you to share and reuse partial Nuxt applications within a monorepo, or from a git repository or npm package. The layers structure is almost identical to a standard Nuxt application, making them easy to author and maintain.

Layer priority order from highest to lowest

The priority order for layers is: 1) Your project files (always highest priority), 2) Auto-scanned layers from ~/layers directory (sorted alphabetically, Z has higher priority than A), 3) Layers in extends config (first entry has higher priority than second).

When to use extends vs ~/layers directory

Use extends for external dependencies (npm packages, remote repositories) or layers outside your project directory. Use ~/layers directory for local layers that are part of your project.

Controlling auto-scanned layer order with prefixes

To control the order of auto-scanned layers in ~/layers, prefix them with numbers: ~/layers/1.z-layer, ~/layers/2.a-layer. This way 2.a-layer will have higher priority than 1.z-layer.

ssrStreaming experimental feature

The `ssrStreaming` experimental feature enables SSR streaming to dramatically improve Time to First Byte (TTFB). When enabled, the server sends the HTML shell (including `<head>`, styles, preload hints, and entry scripts) immediately, then streams the rendered body content progressively using Vue's `renderToWebStream`. Streaming is automatically disabled for bot and crawler user agents (such as Googlebot, Bingbot, etc.) to ensure search engines receive fully-rendered HTML for SEO safety. The bot detection regex can be customized using the `botRegex` property. Streaming can also be controlled per-route using `routeRules` by setting `streaming: false` for specific routes. It can be enabled by setting `experimental.ssrStreaming: true` in the config.

ssrStreaming production FOUC for nested async components

With ssrStreaming experimental feature in production, the renderer inlines route CSS in a chunk sent straight after the shell. It can only inline styles for components whose modules are already registered at that point: the page, the layout, and any async component placed directly inside a `<Suspense>` boundary (Vue instantiates those eagerly when render begins). An async component rendered inside another async component is instantiated only once its parent resolves, after the first chunk has streamed. Its SFC `<style>` misses the post-shell styles chunk and is emitted in the closing HTML instead, behind the component's DOM, causing a FOUC. Avoid by: putting styles that gate initial paint in a global CSS file (`css: ['~/assets/main.css']`); styling with utility classes (Tailwind, UnoCSS) - utility CSS lives in the entry stylesheet; keeping paint-critical `<style>` components directly under a `<Suspense>` boundary rather than nested; or opting routes out of streaming with `routeRules: { '/path': { streaming: false } }`. Non-paint-critical scoped styles on nested async components are fine.

ssrStreaming development FOUC for SFC styles

In development with ssrStreaming experimental feature, Vue Serve File Components (SFC) `<style>` blocks are served as JavaScript modules that inject styles client-side after the module evaluates, with no corresponding `<link>` in the shell. With streaming, the browser starts painting the streamed DOM before those style-injection modules run, causing SFC-defined styles to flash unstyled briefly (FOUC - Flash of Unstyled Content). Workaround: put paint-critical styles in a global CSS file registered via `css: ['~/assets/main.css']`. Global CSS files are emitted as `<link rel="stylesheet">` in the shell `<head>` and apply before body content streams. SFC `<style>` blocks remain fine for component-scoped styling that doesn't gate the initial paint. Production builds extract all styles to real CSS files (or inline via `features.inlineStyles`), so this only affects `nuxt dev`. Validate streaming visuals against `nuxt build && nuxt preview`.

ssrStreaming CSP nonce support

With ssrStreaming experimental feature, the renderer automatically handles Content Security Policy (CSP) nonce. The streaming renderer emits several inline scripts and styles (bootstrap queue, IIFE, suspense head pushes, island-teleport relocation, and route `<style>` blocks) that bypass unhead. If a `nonce` is present on rendered head scripts, the renderer reuses it on all of them automatically, so a strict `script-src`/`style-src 'nonce-…'` policy does not block streaming. A module only needs to put the nonce on the head scripts; the `render:html:chunk` hook remains available for stamping scripts that components render into the body.

ssrStreaming module hooks

With ssrStreaming experimental feature, modules participate in the streaming response via: `render:route` hook (fires once per request before rendering begins for every render, allows reading `ctx.canStream` and setting `ctx.prefersStream = false` to force buffered rendering); `render:html` hook (fires once before the shell flushes with `streaming: true` on second argument, mutations to `htmlAttrs`, `head`, `bodyAttrs`, and `bodyPrepend` reach the wire, mutations to `body`/`bodyAppend` are dropped with a dev-mode warning); `render:html:chunk` hook (fires for each chunk before enqueueing, allows mutating `ctx.chunk: Uint8Array` to transform bytes); and `render:html:close` hook (fires after body stream completes before closing tags, allows mutating `ctx.bodyAppend: string[]` to inject final markup).

ssrStreaming response status and headers timing

With ssrStreaming experimental feature, the HTTP response status and headers must be set before the shell is flushed, as streaming commits them with the first byte. Any mutations after that point cannot reach the client. Mutations from Nuxt and Nitro plugins (which run before rendering begins) reach the client, but `setResponseStatus()`, `useResponseHeader()`, `useCookie()` writes and h3 `setHeader()`/`appendResponseHeader()` calls made during component rendering are dropped. To keep a response mutation, move it into a plugin or opt the route out of streaming using `routeRules: { '/path': { streaming: false } }` or the `render:route` hook with `ctx.prefersStream = false`. In development, dropped mutations are logged as warnings.

prefetchPreloadTags experimental feature

The `prefetchPreloadTags` experimental feature forwards `<link rel="preload">` hints from prefetched `<NuxtLink>` destination routes that have payload extraction enabled (the default for prerendered and cached routes) into the current document. The forwarded links are downgraded from `rel="preload"` to `rel="prefetch"` so they don't compete with the current page's critical resources. Only user-defined head tags are forwarded; build-time JS/CSS chunk preloads are handled separately. This flag is off by default because, combined with `prefetchOn: 'visibility'` (the `<NuxtLink>` default), it could trigger a lot of cross-route prefetches at once. It can be enabled by setting `experimental.prefetchPreloadTags: true` in the config.

granularCachedData experimental feature

The `granularCachedData` experimental feature controls whether to call and use the result from `getCachedData` when refreshing data for `useAsyncData` and `useFetch`, whether by `watch`, `refreshNuxtData()`, or a manual `refresh()` call. This flag is enabled by default but can be disabled by setting `experimental.granularCachedData: false` in the config.

stripNeverHydratedData experimental feature

The `stripNeverHydratedData` experimental feature applies `serialize: false` by default to `useAsyncData` and `useFetch` calls made within components lazily hydrated with `hydrate-never`, keeping their data out of the `__NUXT_DATA__` payload. Since these components never hydrate on the client, their data is not needed for hydration. It can be enabled by setting `experimental.stripNeverHydratedData: true` in the config. An explicit `serialize` option always takes precedence. If the same key is shared with components that do hydrate, the `serialize` option should be consistent across calls, and Nuxt warns about mismatches in development.

headNext experimental feature

The `headNext` experimental feature uses head optimizations: it adds the capo.js head plugin to render tags in the head in a more performant way and uses the hash hydration plugin to reduce initial hydration. This flag is enabled by default but can be disabled by setting `experimental.headNext: false` in the config.

pendingWhenIdle experimental feature

The `pendingWhenIdle` experimental feature controls the `pending` ref returned by `useAsyncData` and `useFetch`. When `pendingWhenIdle` is `false` (the default), `pending` is `true` while a request is in flight and matches `status === 'pending'`, and stays `false` when `status` is `idle`. Setting `pendingWhenIdle: true` makes `pending` also `true` when `status` is `idle` and no cached data is available. Use `status` when the loading UI needs to distinguish `idle` from an in-flight request. It can be enabled by setting `experimental.pendingWhenIdle: true` in the config.

entryImportMap experimental feature

The `entryImportMap` experimental feature improves chunk stability by using an import map to resolve the entry chunk of the bundle. By default, this injects an import map at the top of the `<head>` tag, which allows imports within script chunks to reference the entry using `#entry`. Changes to the entry will not invalidate chunks that are otherwise unchanged. Nuxt intelligently disables this feature if `vite.build.target` includes a browser that doesn't support import maps or if `vite.build.rolldownOptions.output.entryFileNames` is configured to a value that does not include `[hash]`. It can be disabled by setting `experimental.entryImportMap: false` in the config.

typescriptPlugin experimental feature

The `typescriptPlugin` experimental feature enables enhanced TypeScript developer experience with the `@dxup/nuxt` module. This experimental plugin provides improved TypeScript integration and development tooling for better DX when working with TypeScript in Nuxt applications. This flag is disabled by default and can be enabled by setting `experimental.typescriptPlugin: true` in the config. To use this feature, `typescript` must be installed as a dependency and VS Code must be configured to use the workspace TypeScript version.

ssrStreaming automatic fallback to non-streamed rendering

When using ssrStreaming experimental feature, automatic fallback to non-streamed (buffered) rendering occurs for requests matching: `routeRules` setting `noScripts`, `cache`, `isr`, `swr`, `redirect`, or `streaming: false`; `ssr: false` routes; bot/crawler user agents; prerendered routes from `nuxt generate`; server-side `navigateTo()` redirects from plugins, middleware, or page setup; and fatal errors thrown during initial render before the shell flushes. This is because streaming commits the response status and headers once the shell is flushed, making it incompatible with features that need to mutate the response after render.

Experimental features configuration location

Nuxt experimental features are defined in the configuration file using the `experimental` object within `defineNuxtConfig()`. The schema for these features is defined in `@nuxt/schema` package, and the source code can be found in the `packages/schema/src/config/experimental.ts` file in the Nuxt repository.

alwaysRunFetchOnKeyChange experimental feature

The `alwaysRunFetchOnKeyChange` experimental feature controls whether `useFetch` runs when the key changes, even if it is set to `immediate: false` and has not been triggered yet. When `immediate: true` or after the request has been triggered, `useFetch` and `useAsyncData` will always run when the key changes. This flag is disabled by default and can be enabled by setting `experimental.alwaysRunFetchOnKeyChange: true` in the config.

appManifest experimental feature

The `appManifest` experimental feature uses app manifests to respect route rules on the client-side. This flag is enabled by default but can be disabled by setting `experimental.appManifest: false` in the config.

asyncContext experimental feature

The `asyncContext` experimental feature enables native async context to be accessible for nested composables in Nuxt and in Nitro. This allows composables to be used inside async composables and reduces the chance of getting the 'Nuxt instance is unavailable' error. It can be enabled by setting `experimental.asyncContext: true` in the config.

asyncEntry experimental feature

The `asyncEntry` experimental feature enables generation of an async entry point for the Vue bundle, which aids module federation support. It can be enabled by setting `experimental.asyncEntry: true` in the config.

extractAsyncDataHandlers experimental feature

The `extractAsyncDataHandlers` experimental feature extracts handler functions from `useAsyncData` and `useLazyAsyncData` calls into separate chunks for improved code splitting and caching efficiency. This feature transforms inline handler functions into dynamically imported chunks, enabling data fetching logic to be split out while still allowing the code to be loaded if required. This feature is only recommended for static builds with payload extraction, and where data does not need to be re-fetched at runtime. It can be enabled by setting `experimental.extractAsyncDataHandlers: true` in the config.

emitRouteChunkError experimental feature modes

The `emitRouteChunkError` experimental feature controls chunk error handling. It can be set to: `'automatic'` (default) - performs reload of the new route on navigation when a chunk fails to load; `'automatic-immediate'` - performs reload of the current route right when a chunk fails to load, useful for lazy components; `'manual'` - emits `app:chunkError` hook to handle chunk errors manually; or `false` - disables automatic handling.

enforceModuleCompatibility experimental feature

The `enforceModuleCompatibility` experimental feature determines whether Nuxt should throw an error and fail to load if a Nuxt module is incompatible. This feature is disabled by default and can be enabled by setting `experimental.enforceModuleCompatibility: true` in the config.

restoreState experimental feature

The `restoreState` experimental feature allows Nuxt app state to be restored from `sessionStorage` when reloading the page after a chunk error or manual `reloadNuxtApp()` call. To avoid hydration errors, it is applied only after the Vue app has been mounted, which may cause a flicker on initial load. This feature should be enabled carefully as it can cause unexpected behavior. It is recommended to provide explicit keys to `useState` as auto-generated keys may not match across builds. It can be enabled by setting `experimental.restoreState: true` in the config.

inlineRouteRules experimental feature

The `inlineRouteRules` experimental feature allows defining route rules at the page level using the `defineRouteRules` utility. Matching route rules are created based on the page's `path`. It can be enabled by setting `experimental.inlineRouteRules: true` in the config.

noVueServer experimental feature

The `noVueServer` experimental feature disables the Vue server renderer endpoint within Nitro. It can be enabled by setting `experimental.noVueServer: true` in the config.

parseErrorData experimental feature (deprecated)

The `parseErrorData` experimental feature is deprecated and will be removed. With `compatibilityVersion: 5`, it is forced on and setting it is ignored. Previously, it controlled whether `error.data` would be parsed when rendering a server error page. Errors are now JSON-encoded as a whole, so `error.data` arrives with its original shape and is never stringified.

payloadExtraction experimental feature modes

The `payloadExtraction` experimental feature controls how payload data is delivered for prerendered and cached (ISR/SWR) pages. It can be set to: `'client'` - payload is inlined in HTML for initial server render and extracted to `_payload.json` files for client-side navigation; `true` (default) - payload is extracted to a separate `_payload.json` file for both initial server render and client-side navigation; or `false` - payload extraction is disabled, payload is always inlined in HTML and no `_payload.json` files are generated. When `compatibilityVersion: 5` is set, the default becomes `'client'`. It is forced to `false` when `ssr: false` is set.

clientNodePlaceholder experimental feature

The `clientNodePlaceholder` experimental feature uses comment nodes (`<!--placeholder-->`) instead of `<div>` elements as placeholders for client-only components during server-side rendering. This fixes a Vue hydration issue where scoped styles may not be applied when the placeholder `<div>` and the actual component root share the same tag name. However, enabling this means attributes (`class`, `style`, etc.) passed to `.client.vue` components will not appear in the SSR HTML. If styled placeholders are needed to prevent layout shift, use `<ClientOnly>` with a `#fallback` slot instead. This flag is enabled when `future.compatibilityVersion` is set to 5 or higher, but can be enabled explicitly by setting `experimental.clientNodePlaceholder: true`.

clientFallback experimental feature

The `clientFallback` experimental feature enables the experimental `<NuxtClientFallback>` component for rendering content on the client if there's an error in SSR. It can be enabled by setting `experimental.clientFallback: true` in the config.

crossOriginPrefetch experimental feature

The `crossOriginPrefetch` experimental feature enables cross-origin prefetch using the Speculation Rules API. It can be enabled by setting `experimental.crossOriginPrefetch: true` in the config.

viewTransition experimental feature

The `viewTransition` experimental feature enables View Transition API integration with the client-side router. It can be enabled by setting `experimental.viewTransition: true` in the config. It can also be configured with an object to enable view transition types, which allow different CSS animations based on the type of navigation, using the `types` property (e.g., `types: ['slide']`).

writeEarlyHints experimental feature

The `writeEarlyHints` experimental feature enables writing of early hints when using node server. It can be enabled by setting `experimental.writeEarlyHints: true` in the config.

componentIslands experimental feature

The `componentIslands` experimental feature enables experimental component islands support with `<NuxtIsland>` and `.island.vue` files. It can be set to `true`, `false`, or `'local+remote'`. It can be enabled by setting `experimental.componentIslands: true` in the config. Related documentation mentions skipping `nuxt-client` on non-SFC components such as `<NuxtLink>` and selective hydration with `nuxt-client`.

localLayerAliases experimental feature

The `localLayerAliases` experimental feature resolves `~`, `~~`, `@` and `@@` aliases located within layers with respect to their layer source and root directories. This flag is enabled by default but can be disabled by setting `experimental.localLayerAliases: false` in the config.

typedPages experimental feature

The `typedPages` experimental feature enables the new experimental typed router. It can be enabled by setting `experimental.typedPages: true` in the config. Out of the box, this enables typed usage of `navigateTo`, `<NuxtLink>`, `router.push()`, and more. It also allows getting typed params within a page by using `const route = useRoute('route-name')`.

watcher experimental feature options

The `watcher` experimental feature sets an alternative watcher that will be used as the watching service for Nuxt. Options include: `'chokidar-granular'` (default) - ignores top-level directories like `node_modules` and `.git`; `'parcel'` - uses `@parcel/watcher`, may improve performance in large projects or on Windows; `'chokidar'` - watches all files in source directory; `'builder'` - reuses the active builder's own file watcher (e.g., Vite's `server.watcher`), reducing the number of file watchers in dev mode and becomes the default when `future.compatibilityVersion` is `5`. If the builder doesn't implement its own watcher (webpack and rspack), Nuxt logs a warning and falls back to default selection.

sharedPrerenderData experimental feature

The `sharedPrerenderData` experimental feature enables Nuxt to automatically share payload data between pages that are prerendered, resulting in significant performance improvement when prerendering sites using `useAsyncData` or `useFetch` that fetch the same data in different pages. This feature is enabled by default and can be disabled by setting `experimental.sharedPrerenderData: false` in the config. When enabling this feature, ensure that any unique key of the data is always resolvable to the same data - for dynamic pages, provide a key that uniquely identifies the data fetched.

clientNodeCompat experimental feature

The `clientNodeCompat` experimental feature enables Nuxt to automatically polyfill Node.js imports in the client build using `unenv`. To make globals like `Buffer` work in the browser, they need to be manually injected, for example: `globalThis.Buffer ||= Buffer`.

scanPageMeta experimental feature

The `scanPageMeta` experimental feature enables Nuxt to expose some route metadata defined in `definePageMeta` at build-time to modules. This works with `alias`, `name`, `path`, `redirect`, `props`, and `middleware` when they are static or strings/arrays rather than variables or conditional assignments. By default, page metadata is only scanned after all routes have been registered in the `pages:extend` hook, then another hook `pages:resolved` is called. This feature is enabled by default and can be disabled by setting `experimental.scanPageMeta: false` in the config.

Give your agent this brain