Экспериментальные возможности

Включение экспериментальных возможностей Nuxt для доступа к новому функционалу.

В Nuxt часть возможностей помечена как экспериментальные; их можно включить в конфигурации.

Описание этих возможностей задаётся в @nuxt/schema. Полный список и параметры — в API-документации и исходном коде.

Экспериментальные возможности могут быть изменены или удалены в будущих версиях.

alwaysRunFetchOnKeyChange

Запускать ли useFetch при изменении ключа, даже если задано immediate: false и запрос ещё не выполнялся. По умолчанию отключено.

appManifest

Использовать app manifest для учёта правил маршрутов на клиенте. По умолчанию включено.

asyncContext

Включить нативный async context для вложенных композаблов в Nuxt и Nitro — возможность вызывать композаблы внутри асинхронных и снизить ошибки «Nuxt instance is unavailable».

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    asyncContext: true,
  },
})
Подробнее в pull-request на GitHub.

asyncEntry

Включает генерацию асинхронной точки входа для Vue-бандла, что помогает при использовании module federation.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    asyncEntry: true,
  },
})

externalVue

Выносит vue, @vue/* и vue-router во внешние зависимости при сборке.

По умолчанию опция включена; при необходимости её можно отключить:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    externalVue: false,
  },
})
Эта возможность, скорее всего, будет удалена в ближайших версиях.

extractAsyncDataHandlers

Выносит функции-обработчики из вызовов useAsyncData и useLazyAsyncData в отдельные чанки для улучшения code splitting и кэширования.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    extractAsyncDataHandlers: true,
  },
})

Обработчики, заданные inline, превращаются в динамически подгружаемые чанки:

<!-- До -->
<script setup>
const { data } = await useAsyncData('user', async () => {
  return await $fetch('/api/user')
})
</script>
<!-- После преобразования -->
<script setup>
const { data } = await useAsyncData('user', () =>
  import('/generated-chunk.js').then(r => r.default()),
)
</script>

Так логика загрузки данных выносится в отдельные чанки, но при необходимости код по-прежнему подгружается.

Рекомендуется только для статической сборки с извлечением payload, когда данные не нужно подгружать заново в рантайме.

emitRouteChunkError

Вызывает хук app:chunkError при ошибке загрузки чанков vite/webpack. По умолчанию при переходе на новый маршрут при сбое загрузки чанка выполняется перезагрузка нового маршрута.

По умолчанию Nuxt перезагружает новый маршрут при сбое загрузки чанка при навигации (automatic).

Значение automatic-immediate заставляет Nuxt перезагружать текущий маршрут сразу при сбое загрузки чанка (не дожидаясь навигации). Это полезно для ошибок чанков, не связанных с навигацией, например когда не удаётся загрузить ленивый компонент. Минус — возможные лишние перезагрузки, если приложению не нужен чанк, из-за которого произошла ошибка.

Автоматическую обработку можно отключить, задав false, или обрабатывать ошибки чанков вручную, задав manual.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    emitRouteChunkError: 'automatic', // или 'automatic-immediate', 'manual' или false
  },
})

enforceModuleCompatibility

Нужно ли выбрасывать ошибку (и не загружать приложение), если модуль Nuxt несовместим.

По умолчанию отключено.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    enforceModuleCompatibility: true,
  },
})

restoreState

Позволяет восстанавливать состояние приложения Nuxt из sessionStorage при перезагрузке страницы после ошибки чанка или вызова reloadNuxtApp().

Чтобы избежать ошибок гидрации, состояние применяется только после монтирования Vue-приложения, из-за чего при первой загрузке возможна краткая «вспышка».

Включайте с осторожностью: возможны неожиданные эффекты. Рекомендуется задавать явные ключи в useState, так как автогенерируемые ключи могут не совпадать между сборками.
nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    restoreState: true,
  },
})

inlineRouteRules

Задаёт правила маршрутов на уровне страницы через defineRouteRules.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    inlineRouteRules: true,
  },
})

Правила создаются по path страницы.

Подробнее в утилите defineRouteRules.
Узнать больше Docs > 4 X > Guide > Concepts > Rendering#hybrid Rendering.

renderJsonPayloads

Включает рендер JSON payload с поддержкой восстановления сложных типов.

По умолчанию включено; при необходимости можно отключить:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    renderJsonPayloads: false,
  },
})

noVueServer

Отключает эндпоинт Vue server renderer в Nitro.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    noVueServer: true,
  },
})

parseErrorData

Нужно ли разбирать error.data при рендере страницы серверной ошибки.

По умолчанию включено; при необходимости можно отключить:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    parseErrorData: false,
  },
})

payloadExtraction

Управляет тем, как передаются данные payload для пререндеренных и кэшируемых (ISR/SWR) страниц.

  • 'client' — payload встраивается в HTML при первом серверном рендере и выносится в файлы _payload.json для клиентской навигации. Нет отдельного сетевого запроса при первой загрузке и сохраняется эффективная клиентская навигация.
  • true — payload выносится в отдельный _payload.json и для первого рендера, и для клиентской навигации.
  • false — извлечение payload отключено. Payload всегда в HTML, файлы _payload.json не создаются.

По умолчанию true, при compatibilityVersion: 5'client'.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    // Payload в HTML, в файлы — только для клиентской навигации
    payloadExtraction: 'client',
  },
})

Извлечение payload работает и для маршрутов с кэшированием ISR (Incremental Static Regeneration) или SWR (Stale-While-Revalidate). CDN могут кэшировать файлы payload вместе с HTML и ускорять клиентскую навигацию по кэшированным маршрутам.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    payloadExtraction: 'client',
  },
  routeRules: {
    // Для этих маршрутов будут создаваться файлы payload
    '/products/**': { isr: 3600 },
    '/blog/**': { swr: true },
  },
})

clientFallback

Включает экспериментальный компонент <NuxtClientFallback> для рендера контента на клиенте при ошибке SSR.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    clientFallback: true,
  },
})

crossOriginPrefetch

Включает cross-origin prefetch через Speculation Rules API.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    crossOriginPrefetch: true,
  },
})
Подробнее о Speculation Rules API.

viewTransition

Включает интеграцию View Transition API с клиентским роутером.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    viewTransition: true,
  },
})

Можно передать объект для настройки типов view transition — разных CSS-анимаций в зависимости от типа навигации:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    viewTransition: {
      enabled: true,
      types: ['slide'],
    },
  },
})
Прочитайте и отредактируйте живой пример в https://stackblitz.com/edit/nuxt-view-transitions?file=app.vue.
Подробнее о View Transition API.
Подробнее о View Transition API.

writeEarlyHints

Включает отправку early hints при использовании node-сервера.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    writeEarlyHints: true,
  },
})

componentIslands

Включает экспериментальную поддержку component islands с <NuxtIsland> и файлами .island.vue.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    componentIslands: true, // false или 'local+remote'
  },
})
Узнать больше Docs > 4 X > Directory Structure > App > Components#server Components.
Дорожная карта server components на GitHub.

localLayerAliases

Разрешать алиасы ~, ~~, @ и @@ внутри слоёв относительно исходной и корневой директорий слоя.

По умолчанию включено; при необходимости можно отключить:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    localLayerAliases: false,
  },
})

typedPages

Включает экспериментальный типизированный роутер на базе unplugin-vue-router.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    typedPages: true,
  },
})

По умолчанию даёт типизированное использование navigateTo, <NuxtLink>, router.push() и др.

Типизированные параметры в странице: const route = useRoute('route-name').

При использовании pnpm без shamefully-hoist=true добавьте unplugin-vue-router в publicHoistPattern в pnpm-workspace.yaml.
publicHoistPattern:
  - "unplugin-vue-router"

watcher

Задаёт альтернативный watcher для отслеживания файлов в Nuxt.

По умолчанию используется chokidar-granular, который игнорирует корневые каталоги (например node_modules и .git).

Значение parcel подключает @parcel/watcher и может улучшить производительность в больших проектах и на Windows.

Значение chokidar включает отслеживание всех файлов в исходной директории.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    watcher: 'chokidar-granular', // также возможны 'chokidar' или 'parcel'
  },
})

sharedPrerenderData

Nuxt автоматически делится данными payload между пререндеренными страницами. Это может заметно ускорить пререндер сайтов с useAsyncData или useFetch, когда одни и те же данные запрашиваются на разных страницах.

При необходимости функцию можно отключить.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    sharedPrerenderData: false,
  },
})

Важно: при включении опции ключ данных должен однозначно соответствовать этим данным. Например, при запросе данных страницы через useAsyncData задавайте ключ, однозначно идентифицирующий данные. (useFetch делает это автоматически.)

// Так делать небезопасно на динамической странице (напр. `[slug].vue`): slug влияет на данные,
// но Nuxt этого не видит, так как ключ от него не зависит.
const route = useRoute()
const { data } = await useAsyncData(async (_nuxtApp, { signal }) => {
  return await $fetch(`/api/my-page/${route.params.slug}`, { signal })
})
// Используйте ключ, однозначно идентифицирующий запрашиваемые данные.
const { data } = await useAsyncData(route.params.slug, async (_nuxtApp, { signal }) => {
  return await $fetch(`/api/my-page/${route.params.slug}`, { signal })
})

clientNodeCompat

При включении Nuxt полифиллит импорты Node.js в клиентской сборке с помощью unenv.

Чтобы глобалы вроде Buffer работали в браузере, их нужно подключать вручную.
import { Buffer } from 'node:buffer'

globalThis.Buffer ||= Buffer

scanPageMeta

Nuxt передаёт модулям на этапе сборки часть метаданных маршрута из definePageMeta (alias, name, path, redirect, props, middleware).

Работает только со статическими значениями или строками/массивами, не с переменными и условными присваиваниями. Подробнее: исходный issue.

По умолчанию метаданные страниц сканируются после регистрации всех маршрутов в pages:extend, затем вызывается хук pages:resolved.

При проблемах в проекте опцию можно отключить.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    scanPageMeta: false,
  },
})

cookieStore

Enables CookieStore support to listen for cookie updates (if supported by the browser) and refresh useCookie ref values.

This flag is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    cookieStore: false,
  },
})
Read more about the CookieStore.

buildCache

Caches Nuxt build artifacts based on a hash of the configuration and source files.

This only works for source files within srcDir and serverDir for the Vue/Nitro parts of your app.

This flag is disabled by default, but you can enable it:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    buildCache: true,
  },
})

When enabled, changes to the following files will trigger a full rebuild:

Directory structure
.nuxtrc
.npmrc
package.json
package-lock.json
yarn.lock
pnpm-lock.yaml
tsconfig.json
bun.lock
bun.lockb

In addition, any changes to files within srcDir will trigger a rebuild of the Vue client/server bundle. Nitro will always be rebuilt (though work is in progress to allow Nitro to announce its cacheable artifacts and their hashes).

A maximum of 10 cache tarballs are kept.

checkOutdatedBuildInterval

Set the time interval (in ms) to check for new builds. Disabled when experimental.appManifest is false.

Set to false to disable.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    checkOutdatedBuildInterval: 3600000, // 1 hour, or false to disable
  },
})

extraPageMetaExtractionKeys

The definePageMeta() macro is a useful way to collect build-time meta about pages. Nuxt itself provides a set list of supported keys which is used to power some of the internal features such as redirects, page aliases and custom paths.

This option allows passing additional keys to extract from the page metadata when using scanPageMeta.

<script lang="ts" setup>
definePageMeta({
  foo: 'bar',
})
</script>
export default defineNuxtConfig({
  experimental: {
    extraPageMetaExtractionKeys: ['foo'],
  },
  hooks: {
    'pages:resolved' (ctx) {
      // ✅ foo is available
    },
  },
})

This allows modules to access additional metadata from the page metadata in the build context. If you are using this within a module, it's recommended also to augment the NuxtPage types with your keys.

Wait for a single animation frame before navigation, which gives an opportunity for the browser to repaint, acknowledging user interaction.

It can reduce INP when navigating on prerendered routes.

This flag is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    navigationRepaint: false,
  },
})

normalizeComponentNames

Nuxt updates auto-generated Vue component names to match the full component name you would use to auto-import the component.

If you encounter issues, you can disable this feature.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    normalizeComponentNames: false,
  },
})

By default, if you haven't set it manually, Vue will assign a component name that matches the filename of the component.

Directory structure
├─ components/
├─── SomeFolder/
├───── MyComponent.vue

In this case, the component name would be MyComponent, as far as Vue is concerned. If you wanted to use <KeepAlive> with it, or identify it in the Vue DevTools, you would need to use this component.

But in order to auto-import it, you would need to use SomeFolderMyComponent.

By setting experimental.normalizeComponentNames, these two values match, and Vue will generate a component name that matches the Nuxt pattern for component naming.

normalizePageNames

Ensure that page component names match their route names. This sets the __name property on page components so that Vue's <KeepAlive> can correctly identify them by name.

By default, Vue assigns component names based on the filename. For example, pages/foo/index.vue and pages/bar/index.vue would both have the component name index. This makes name-based <KeepAlive> filtering unreliable because multiple pages share the same name.

With normalizePageNames enabled, page components are named after their route (e.g. foo and bar), so you can use <KeepAlive> with include/exclude without manually adding defineOptions({ name: '...' }) to each page.

This flag is enabled when future.compatibilityVersion is set to 5 or higher, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    normalizePageNames: false,
  },
})
app.vue
<template>
  <NuxtPage :keepalive="{ include: ['foo'] }" />
</template>

spaLoadingTemplateLocation

When rendering a client-only page (with ssr: false), we optionally render a loading screen (from ~/spa-loading-template.html).

It can be set to within, which will render it like this:

<div id="__nuxt">
  <!-- spa loading template -->
</div>

Alternatively, you can render the template alongside the Nuxt app root by setting it to body:

<div id="__nuxt"></div>
<!-- spa loading template -->

This avoids a white flash when hydrating a client-only page.

browserDevtoolsTiming

Enables performance markers for Nuxt hooks in browser devtools. This adds performance markers that you can track in the Performance tab of Chromium-based browsers, which is useful for debugging and optimizing performance.

This is enabled by default in development mode. If you need to disable this feature, it is possible to do so:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    browserDevtoolsTiming: false,
  },
})
See PR #29922 for implementation details.
Learn more about Chrome DevTools Performance API.

debugModuleMutation

Records mutations to nuxt.options in module context, helping to debug configuration changes made by modules during the Nuxt initialization phase.

This is enabled by default when debug mode is enabled. If you need to disable this feature, it is possible to do so:

To enable it explicitly:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    debugModuleMutation: true,
  },
})
See PR #30555 for implementation details.

lazyHydration

This enables hydration strategies for <Lazy> components, which improves performance by deferring hydration of components until they're needed.

Lazy hydration is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    lazyHydration: false,
  },
})
Read more about lazy hydration.

templateImportResolution

Disable resolving imports into Nuxt templates from the path of the module that added the template.

By default, Nuxt attempts to resolve imports in templates relative to the module that added them. Setting this to false disables this behavior, which may be useful if you're experiencing resolution conflicts in certain environments.

This flag is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    templateImportResolution: false,
  },
})
See PR #31175 for implementation details.

templateRouteInjection

By default the route object returned by the auto-imported useRoute() composable is kept in sync with the current page in view in <NuxtPage>. This is not true for vue-router's exported useRoute or for the default $route object available in your Vue templates.

By enabling this option a mixin will be injected to keep the $route template object in sync with Nuxt's managed useRoute().

This flag is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    templateRouteInjection: false,
  },
})

decorators

This option enables decorator syntax across your entire Nuxt/Nitro app.

When using the Vite builder (default), decorators are lowered via Babel using @babel/plugin-proposal-decorators. When using the webpack or rspack builders, decorators are lowered via esbuild.

For a long time, TypeScript has had support for decorators via compilerOptions.experimentalDecorators. This implementation predated the TC39 standardization process. Now, decorators are a Stage 3 Proposal, and supported without special configuration in TS 5.0+ (see https://github.com/microsoft/TypeScript/pull/52582 and https://devblogs.microsoft.com/typescript/announcing-typescript-5-0-beta/#decorators).

Enabling experimental.decorators enables support for the TC39 proposal, NOT for TypeScript's previous compilerOptions.experimentalDecorators implementation.

Note that there may be changes before this finally lands in the JS standard.

Usage

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    decorators: true,
  },
})

When using the Vite builder or the Nitro server build, you will need to install additional Babel packages as dev dependencies:

npm install -D @babel/plugin-proposal-decorators @babel/plugin-syntax-jsx
Nuxt will prompt you to install these automatically if they are not already present.
app/app.vue
function something (_method: () => unknown) {
  return () => 'decorated'
}

class SomeClass {
  @something
  public someMethod () {
    return 'initial'
  }
}

const value = new SomeClass().someMethod()
// this will return 'decorated'

defaults

This allows specifying the default options for core Nuxt components and composables.

These options will likely be moved elsewhere in the future, such as into app.config or into the app/ directory.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    defaults: {
      nuxtLink: {
        componentName: 'NuxtLink',
        prefetch: true,
        prefetchOn: {
          visibility: true,
        },
      },
      useAsyncData: {
        deep: true,
      },
      useState: {
        resetOnClear: true,
      },
    },
  },
})

The useState.resetOnClear option controls whether clearNuxtState resets state to its initial value (provided by the init function of useState) instead of setting it to undefined. This defaults to true with compatibilityVersion: 5.

purgeCachedData

Whether to clean up Nuxt static and asyncData caches on route navigation.

Nuxt will automatically purge cached data from useAsyncData and nuxtApp.static.data. This helps prevent memory leaks and ensures fresh data is loaded when needed, but it is possible to disable it.

This flag is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    purgeCachedData: false,
  },
})
See PR #31379 for implementation details.

granularCachedData

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 you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    granularCachedData: false,
  },
})
See PR #31373 for implementation details.

headNext

Use head optimisations:

  • Add the capo.js head plugin in order to render tags in of the head in a more performant way.
  • Uses the hash hydration plugin to reduce initial hydration

This flag is enabled by default, but you can disable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    headNext: false,
  },
})

pendingWhenIdle

For useAsyncData and useFetch, whether pending should be true when data has not yet started to be fetched.

This flag is disabled by default, but you can enable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    pendingWhenIdle: true,
  },
})

entryImportMap

By default, Nuxt improves chunk stability by using an import map to resolve the entry chunk of the bundle.

This injects an import map at the top of your <head> tag:

<script type="importmap">{"imports":{"#entry":"/_nuxt/DC5HVSK5.js"}}</script>

Within the script chunks emitted by Vite, imports will be from #entry. This means that changes to the entry will not invalidate chunks which are otherwise unchanged.

Nuxt smartly disables this feature if you have configured vite.build.target to include a browser that doesn't support import maps, or if you have configured vite.build.rolldownOptions.output.entryFileNames to a value that does not include [hash].

If you need to disable this feature you can do so:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    entryImportMap: false,
  },
  // or, better, simply tell vite your desired target
  // which nuxt will respect
  vite: {
    build: {
      target: 'safari13',
    },
  },
})

typescriptPlugin

Enable 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, but you can enable this feature:

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    typescriptPlugin: true,
  },
})
To use this feature, you need to:
  • Have typescript installed as a dependency
  • Configure VS Code to use your workspace TypeScript version (see VS Code documentation)
Learn more about @dxup/nuxt.