# Introduction Nuxt is a free and [open-source framework](https://github.com/nuxt/nuxt){rel=""nofollow""} with an intuitive and extendable way to create type-safe, performant and production-grade full-stack web applications and websites with [Vue.js](https://vuejs.org){rel=""nofollow""}. We made everything so you can start writing `.vue` files from the beginning while enjoying hot module replacement in development and a performant application in production with server-side rendering by default. Nuxt has no vendor lock-in, allowing you to deploy your application [**everywhere, even on the edge**](https://nuxt.com/blog/nuxt-on-the-edge). ::tip If you want to play around with Nuxt in your browser, you can [try it out in one of our online sandboxes](https://nuxt.com/docs/4.x/getting-started/installation#play-online). :: ## Automation and Conventions Nuxt uses conventions and an opinionated directory structure to automate repetitive tasks and allow developers to focus on pushing features. The configuration file can still customize and override its default behaviors. - **File-based routing:** define routes based on the structure of your [`app/pages/` directory](https://nuxt.com/docs/4.x/directory-structure/app/pages). This can make it easier to organize your application and avoid the need for manual route configuration. - **Code splitting:** Nuxt automatically splits your code into smaller chunks, which can help reduce the initial load time of your application. - **Server-side rendering out of the box:** Nuxt comes with built-in SSR capabilities, so you don't have to set up a separate server yourself. - **Auto-imports:** write Vue composables and components in their respective directories and use them without having to import them with the benefits of tree-shaking and optimized JS bundles. - **Data-fetching utilities:** Nuxt provides composables to handle SSR-compatible data fetching as well as different strategies. - **Zero-config TypeScript support:** write type-safe code without having to learn TypeScript with our auto-generated types and `tsconfig.json`. - **Configured build tools:** we use [Vite](https://vite.dev){rel=""nofollow""} by default to support hot module replacement (HMR) in development and bundling your code for production with best-practices baked-in. Nuxt takes care of these and provides both frontend and backend functionality so you can focus on what matters: **creating your web application**. ## Server-Side Rendering Nuxt comes with built-in server-side rendering (SSR) capabilities by default, without having to configure a server yourself, which has many benefits for web applications: - **Faster initial page load time:** Nuxt sends a fully rendered HTML page to the browser, which can be displayed immediately. This can provide a faster perceived page load time and a better user experience (UX), especially on slower networks or devices. - **Improved SEO:** search engines can better index SSR pages because the HTML content is available immediately, rather than requiring JavaScript to render the content on the client-side. - **Better performance on low-powered devices:** it reduces the amount of JavaScript that needs to be downloaded and executed on the client-side, which can be beneficial for low-powered devices that may struggle with processing heavy JavaScript applications. - **Better accessibility:** the content is immediately available on the initial page load, improving accessibility for users who rely on screen readers or other assistive technologies. - **Easier caching:** pages can be cached on the server-side, which can further improve performance by reducing the amount of time it takes to generate and send the content to the client. Overall, server-side rendering can provide a faster and more efficient user experience, as well as improve search engine optimization and accessibility. As Nuxt is a versatile framework, it gives you the possibility to statically render your whole application to a static hosting with `nuxt generate`, disable SSR globally with the `ssr: false` option or leverage hybrid rendering by setting up the `routeRules` option. :read-more{title="Nuxt rendering modes" to="https://nuxt.com/docs/4.x/guide/concepts/rendering"} ### Server engine The Nuxt server engine [Nitro](https://nitro.build/){rel=""nofollow""} unlocks new full-stack capabilities. In development, it uses Rollup and Node.js workers for your server code and context isolation. It also generates your server API by reading files in `server/api/` and server middleware from `server/middleware/`. In production, Nitro builds your app and server into one universal `.output` directory. This output is light: minified and removed from any Node.js modules (except polyfills). You can deploy this output on any system supporting JavaScript, from Node.js, Serverless, Workers, Edge-side rendering or purely static. :read-more{title="Nuxt server engine" to="https://nuxt.com/docs/4.x/guide/concepts/server-engine"} ### Production-ready A Nuxt application can be deployed on a Node or Deno server, pre-rendered to be hosted in static environments, or deployed to serverless and edge providers. :read-more{title="Deployment section" to="https://nuxt.com/docs/4.x/getting-started/deployment"} ### Modular A module system allows you to extend Nuxt with custom features and integrations with third-party services. :read-more{title="Nuxt Modules Concept" to="https://nuxt.com/docs/4.x/guide/concepts/modules"} ### Architecture Nuxt is composed of different [core packages](https://github.com/nuxt/nuxt/tree/main/packages){rel=""nofollow""}: - Core engine: [nuxt](https://github.com/nuxt/nuxt/tree/main/packages/nuxt){rel=""nofollow""} - Bundlers: [@nuxt/vite-builder](https://github.com/nuxt/nuxt/tree/main/packages/vite){rel=""nofollow""}, [@nuxt/rspack-builder](https://github.com/nuxt/nuxt/tree/main/packages/rspack){rel=""nofollow""} and [@nuxt/webpack-builder](https://github.com/nuxt/nuxt/tree/main/packages/webpack){rel=""nofollow""} - Command line interface: [@nuxt/cli](https://github.com/nuxt/cli){rel=""nofollow""} - Server engine: [nitro](https://github.com/nitrojs/nitro){rel=""nofollow""} - Development kit: [@nuxt/kit](https://github.com/nuxt/nuxt/tree/main/packages/kit){rel=""nofollow""} We recommend reading each concept to have a full vision of Nuxt capabilities and the scope of each package. # Installation ## Play Online If you just want to play around with Nuxt in your browser without setting up a project, you can use one of our online sandboxes: ::card-group :::card --- icon: i-simple-icons-stackblitz target: _blank title: Open on StackBlitz to: https://nuxt.new/s/v4 --- ::: :::card --- icon: i-simple-icons-codesandbox target: _blank title: Open on CodeSandbox to: https://nuxt.new/c/v4 --- ::: :: Or follow the steps below to set up a new Nuxt project on your computer. ## New Project ### Prerequisites - **Node.js** - [`20.x`](https://nodejs.org/en){rel=""nofollow""} or newer (but we recommend the [active LTS release](https://github.com/nodejs/release#release-schedule){rel=""nofollow""}) - **Text editor** - There is no IDE requirement, but we recommend [Visual Studio Code](https://code.visualstudio.com/){rel=""nofollow""} with the [official Vue extension](https://marketplace.visualstudio.com/items?itemName=Vue.volar){rel=""nofollow""} (previously known as Volar) or [WebStorm](https://www.jetbrains.com/webstorm/){rel=""nofollow""}, which, along with [other JetBrains IDEs](https://www.jetbrains.com/ides/){rel=""nofollow""}, offers great Nuxt support right out-of-the-box. - **Terminal** - In order to run Nuxt commands ::note Additional notes for an optimal setup: - **Node.js**: Make sure to use an even numbered version (20, 22, etc.) - **WSL**: If you are using Windows and experience slow HMR, you may want to try using [WSL (Windows Subsystem for Linux)](https://learn.microsoft.com/en-us/windows/wsl/install){rel=""nofollow""} which may solve some performance issues. - **Windows slow DNS resolution**: Instead of using `localhost:3000` for local dev server on Windows, use `127.0.0.1` for much faster loading experience on browsers. :: Open a terminal (if you're using [Visual Studio Code](https://code.visualstudio.com){rel=""nofollow""}, you can open an [integrated terminal](https://code.visualstudio.com/docs/terminal/basics){rel=""nofollow""}) and use the following command to create a new starter project: ::code-group{sync="pm"} ```bash [npm] npm create nuxt@latest ``` ```bash [yarn] yarn create nuxt ``` ```bash [pnpm] pnpm create nuxt@latest ``` ```bash [bun] bun create nuxt@latest ``` ```bash [deno] deno -A npm:create-nuxt@latest ``` :: ::tip Alternatively, you can find other starters or themes by opening [nuxt.new](https://nuxt.new){rel=""nofollow""} and following the instructions there. :: Open your project folder in Visual Studio Code: ```bash [Terminal] code ``` Or change directory into your new project from your terminal: ```bash cd ``` ## Development Server Now you'll be able to start your Nuxt app in development mode: ::code-group{sync="pm"} ```bash [npm] npm run dev -- -o ``` ```bash [yarn] yarn dev --open ``` ```bash [pnpm] pnpm dev -o ``` ```bash [bun] bun run dev -o # To use the Bun runtime during development # bun --bun run dev -o ``` ```bash [deno] deno run dev -o ``` :: ::tip{icon="i-lucide-circle-check"} Well done! A browser window should automatically open for {rel=""nofollow""}. :: ## Next Steps Now that you've created your Nuxt project, you are ready to start building your application. :read-more{title="Nuxt Concepts" to="https://nuxt.com/docs/4.x/guide/concepts"} # Configuration By default, Nuxt is configured to cover most use cases. The [`nuxt.config.ts`](https://nuxt.com/docs/4.x/directory-structure/nuxt-config) file can override or extend this default configuration. ## Nuxt Configuration The [`nuxt.config.ts`](https://nuxt.com/docs/4.x/directory-structure/nuxt-config) file is located at the root of a Nuxt project and can override or extend the application's behavior. A minimal configuration file exports the `defineNuxtConfig` function containing an object with your configuration. The `defineNuxtConfig` helper is globally available without import. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ // My Nuxt config }) ``` This file will often be mentioned in the documentation, for example to add custom scripts, register modules or change rendering modes. ::read-more{to="https://nuxt.com/docs/4.x/api/configuration/nuxt-config"} Every option is described in the **Configuration Reference**. :: ::note You don't have to use TypeScript to build an application with Nuxt. However, it is strongly recommended to use the `.ts` extension for the `nuxt.config` file. This way you can benefit from hints in your IDE to avoid typos and mistakes while editing your configuration. :: ### Environment Overrides You can configure fully typed, per-environment overrides in your nuxt.config ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ $production: { routeRules: { '/**': { isr: true }, }, }, $development: { // }, $env: { staging: { // }, }, }) ``` To select an environment when running a Nuxt CLI command, simply pass the name to the `--envName` flag, like so: `nuxt build --envName staging`. To learn more about the mechanism behind these overrides, please refer to the `c12` documentation on [environment-specific configuration](https://github.com/unjs/c12?tab=readme-ov-file#environment-specific-configuration){rel=""nofollow""}. :video-accordion{title="Watch a video from Alexander Lichter about the env-aware nuxt.config.ts" video-id="DFZI2iVCrNc"} ::note If you're authoring layers, you can also use the `$meta` key to provide metadata that you or the consumers of your layer might use. :: ### Environment Variables and Private Tokens The `runtimeConfig` API exposes values like environment variables to the rest of your application. By default, these keys are only available server-side. The keys within `runtimeConfig.public` and `runtimeConfig.app` (which is used by Nuxt internally) are also available client-side. Those values should be defined in `nuxt.config` and can be overridden using environment variables. ::code-group ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ runtimeConfig: { // The private keys which are only available server-side apiSecret: '123', // Keys within public are also exposed client-side public: { apiBase: '/api', }, }, }) ``` ```ini [.env] # This will override the value of apiSecret NUXT_API_SECRET=api_secret_token ``` :: These variables are exposed to the rest of your application using the [`useRuntimeConfig()`](https://nuxt.com/docs/4.x/api/composables/use-runtime-config) composable. ```vue [app/pages/index.vue] ``` :read-more{to="https://nuxt.com/docs/4.x/guide/going-further/runtime-config"} ## App Configuration The `app.config.ts` file, located in the source directory (by default `app/`), is used to expose public variables that can be determined at build time. Contrary to the `runtimeConfig` option, these cannot be overridden using environment variables. A minimal configuration file exports the `defineAppConfig` function containing an object with your configuration. The `defineAppConfig` helper is globally available without import. ```ts [app/app.config.ts] export default defineAppConfig({ title: 'Hello Nuxt', theme: { dark: true, colors: { primary: '#ff0000', }, }, }) ``` These variables are exposed to the rest of your application using the [`useAppConfig`](https://nuxt.com/docs/4.x/api/composables/use-app-config) composable. ```vue [app/pages/index.vue] ``` :read-more{to="https://nuxt.com/docs/4.x/directory-structure/app/app-config"} ## `runtimeConfig` vs. `app.config` As stated above, `runtimeConfig` and `app.config` are both used to expose variables to the rest of your application. To determine whether you should use one or the other, here are some guidelines: - `runtimeConfig`: Private or public tokens that need to be specified after build using environment variables. - `app.config`: Public tokens that are determined at build time, website configuration such as theme variant, title and any project config that are not sensitive. | Feature | `runtimeConfig` | `app.config` | | ------------------------- | --------------- | ------------ | | Client Side | Hydrated | Bundled | | Environment Variables | ✅ Yes | ❌ No | | Reactive | ✅ Yes | ✅ Yes | | Types support | ✅ Partial | ✅ Yes | | Client-side | Hydrated | Bundled | | Environment variables | ✅ Yes | ❌ No | | Reactive | ✅ Yes | ✅ Yes | | Types support | ✅ Partial | ✅ Yes | | Configuration per request | ❌ No | ✅ Yes | | Hot module replacement | ❌ No | ✅ Yes | | Non-primitive JS types | ❌ No | ✅ Yes | ## External Configuration Files Nuxt uses [`nuxt.config.ts`](https://nuxt.com/docs/4.x/directory-structure/nuxt-config) file as the single source of truth for configurations and skips reading external configuration files. During the course of building your project, you may have a need to configure those. The following table highlights common configurations and, where applicable, how they can be configured with Nuxt. | Name | Config File | How To Configure | | ------------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------- | | [Nitro](https://nitro.build){rel=""nofollow""} | ~~`nitro.config.ts`~~ | Use [`nitro`](https://nuxt.com/docs/4.x/api/nuxt-config#nitro) key in `nuxt.config` | | [PostCSS](https://postcss.org){rel=""nofollow""} | ~~`postcss.config.js`~~ | Use [`postcss`](https://nuxt.com/docs/4.x/api/nuxt-config#postcss) key in `nuxt.config` | | [Vite](https://vite.dev){rel=""nofollow""} | ~~`vite.config.ts`~~ | Use [`vite`](https://nuxt.com/docs/4.x/api/nuxt-config#vite) key in `nuxt.config` | | [webpack](https://webpack.js.org){rel=""nofollow""} | ~~`webpack.config.ts`~~ | Use [`webpack`](https://nuxt.com/docs/4.x/api/nuxt-config#webpack-1) key in `nuxt.config` | Here is a list of other common config files: | Name | Config File | How To Configure | | ------------------------------------------------------------------------ | --------------------- | --------------------------------------------------------------------------------------------------------- | | [TypeScript](https://www.typescriptlang.org){rel=""nofollow""} | `tsconfig.json` | [More Info](https://nuxt.com/docs/4.x/directory-structure/tsconfig) | | [ESLint](https://eslint.org){rel=""nofollow""} | `eslint.config.js` | [More Info](https://eslint.org/docs/latest/use/configure/configuration-files){rel=""nofollow""} | | [Prettier](https://prettier.io){rel=""nofollow""} | `prettier.config.js` | [More Info](https://prettier.io/docs/configuration.html){rel=""nofollow""} | | [Stylelint](https://stylelint.io){rel=""nofollow""} | `stylelint.config.js` | [More Info](https://stylelint.io/user-guide/configure/){rel=""nofollow""} | | [TailwindCSS](https://tailwindcss.com){rel=""nofollow""} | `tailwind.config.js` | [More Info](https://tailwindcss.nuxtjs.org/tailwindcss/configuration/){rel=""nofollow""} | | [Vitest](https://vitest.dev){rel=""nofollow""} | `vitest.config.ts` | [More Info](https://vitest.dev/config/){rel=""nofollow""} | ## Vue Configuration ### With Vite If you need to pass options to `@vitejs/plugin-vue` or `@vitejs/plugin-vue-jsx`, you can do this in your `nuxt.config` file. - `vite.vue` for `@vitejs/plugin-vue`. Check [available options](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue){rel=""nofollow""}. - `vite.vueJsx` for `@vitejs/plugin-vue-jsx`. Check [available options](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue-jsx){rel=""nofollow""}. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ vite: { vue: { customElement: true, }, vueJsx: { mergeProps: true, }, }, }) ``` :read-more{to="https://nuxt.com/docs/4.x/api/configuration/nuxt-config#vue"} ### With webpack If you use webpack and need to configure `vue-loader`, you can do this using `webpack.loaders.vue` key inside your `nuxt.config` file. The available options are [defined here](https://github.com/vuejs/vue-loader/blob/main/src/index.ts#L32-L62){rel=""nofollow""}. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ webpack: { loaders: { vue: { hotReload: true, }, }, }, }) ``` :read-more{to="https://nuxt.com/docs/4.x/api/configuration/nuxt-config#loaders"} ### Enabling Experimental Vue Features You may need to enable experimental features in Vue, such as `propsDestructure`. Nuxt provides an easy way to do that in `nuxt.config.ts`, no matter which builder you are using: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ vue: { propsDestructure: true, }, }) ``` #### experimental `reactivityTransform` migration from Vue 3.4 and Nuxt 3.9 Since Nuxt 3.9 and Vue 3.4, `reactivityTransform` has been moved from Vue to Vue Macros which has a [Nuxt integration](https://vue-macros.dev/guide/nuxt-integration.html){rel=""nofollow""}. :read-more{to="https://nuxt.com/docs/4.x/api/configuration/nuxt-config#vue-1"} # Views ## `app.vue` ![The app.vue file is the entry point of your application](https://nuxt.com/assets/docs/getting-started/views/app.svg) By default, Nuxt will treat this file as the **entrypoint** and render its content for every route of the application. ```vue [app/app.vue] ``` ::tip If you are familiar with Vue, you might wonder where `main.js` is (the file that normally creates a Vue app). Nuxt does this behind the scene. :: ## Components ![Components are reusable pieces of UI](https://nuxt.com/assets/docs/getting-started/views/components.svg) Most components are reusable pieces of the user interface, like buttons and menus. In Nuxt, you can create these components in the [`app/components/`](https://nuxt.com/docs/4.x/directory-structure/app/components) directory, and they will be automatically available across your application without having to explicitly import them. ::code-group ```vue [app/app.vue] ``` ```vue [app/components/AppAlert.vue] ``` :: ## Pages ![Pages are views tied to a specific route](https://nuxt.com/assets/docs/getting-started/views/pages.svg) Pages represent views for each specific route pattern. Every file in the [`app/pages/`](https://nuxt.com/docs/4.x/directory-structure/app/pages) directory represents a different route displaying its content. To use pages, create an `app/pages/index.vue` file and add `` component to the [`app/app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app) (or remove `app/app.vue` for default entry). You can now create more pages and their corresponding routes by adding new files in the [`app/pages/`](https://nuxt.com/docs/4.x/directory-structure/app/pages) directory. ::code-group ```vue [app/pages/index.vue] ``` ```vue [app/pages/about.vue] ``` :: :read-more{title="Routing Section" to="https://nuxt.com/docs/4.x/getting-started/routing"} ## Layouts ![Layouts are wrapper around pages](https://nuxt.com/assets/docs/getting-started/views/layouts.svg) Layouts are wrappers around pages that contain a common User Interface for several pages, such as header and footer displays. Layouts are Vue files using `` components to display the **page** content. The `app/layouts/default.vue` file will be used by default. Custom layouts can be set as part of your page metadata. ::note If you only have a single layout in your application, we recommend using [`app/app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app) with [``](https://nuxt.com/docs/4.x/api/components/nuxt-page) instead. :: ::code-group ```vue [app/app.vue] ``` ```vue [app/layouts/default.vue] ``` ```vue [app/pages/index.vue] ``` ```vue [app/pages/about.vue] ``` :: If you want to create more layouts and learn how to use them in your pages, find more information in the [Layouts section](https://nuxt.com/docs/4.x/directory-structure/app/layouts). ## Advanced: Extending the HTML Template ::note If you only need to modify the ``, you can refer to the [SEO and meta section](https://nuxt.com/docs/4.x/getting-started/seo-meta). :: You can have full control over the HTML template by adding a Nitro plugin that registers a hook. The callback function of the `render:html` hook allows you to mutate the HTML before it is sent to the client. ```ts [server/plugins/extend-html.ts] export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('render:html', (html, { event }) => { // This will be an object representation of the html template. console.log(html) html.head.push(``) }) // You can also intercept the response here. nitroApp.hooks.hook('render:response', (response, { event }) => { console.log(response) }) }) ``` :read-more{to="https://nuxt.com/docs/4.x/guide/going-further/hooks"} # Assets Nuxt uses two directories to handle assets like stylesheets, fonts or images. - The [`public/`](https://nuxt.com/docs/4.x/directory-structure/public) directory content is served at the server root as-is. - The [`app/assets/`](https://nuxt.com/docs/4.x/directory-structure/app/assets) directory contains by convention every asset that you want the build tool (Vite or webpack) to process. ## Public Directory The [`public/`](https://nuxt.com/docs/4.x/directory-structure/public) directory is used as a public server for static assets publicly available at a defined URL of your application. You can get a file in the [`public/`](https://nuxt.com/docs/4.x/directory-structure/public) directory from your application's code or from a browser by the root URL `/`. ### Example For example, referencing an image file in the `public/img/` directory, available at the static URL `/img/nuxt.png`: ```vue [app/app.vue] ``` ## Assets Directory Nuxt uses [Vite](https://vite.dev/guide/assets){rel=""nofollow""} (default) or [webpack](https://webpack.js.org/guides/asset-management/){rel=""nofollow""} to build and bundle your application. The main function of these build tools is to process JavaScript files, but they can be extended through [plugins](https://vite.dev/plugins/){rel=""nofollow""} (for Vite) or [loaders](https://webpack.js.org/loaders/){rel=""nofollow""} (for webpack) to process other kinds of assets, like stylesheets, fonts or SVGs. This step transforms the original file, mainly for performance or caching purposes (such as stylesheet minification or browser cache invalidation). By convention, Nuxt uses the [`app/assets/`](https://nuxt.com/docs/4.x/directory-structure/app/assets) directory to store these files but there is no auto-scan functionality for this directory, and you can use any other name for it. In your application's code, you can reference a file located in the [`app/assets/`](https://nuxt.com/docs/4.x/directory-structure/app/assets) directory by using the `~/assets/` path. ### Example For example, referencing an image file that will be processed if a build tool is configured to handle this file extension: ```vue [app/app.vue] ``` ::note Nuxt won't serve files in the [`app/assets/`](https://nuxt.com/docs/4.x/directory-structure/app/assets) directory at a static URL like `/assets/my-file.png`. If you need a static URL, use the [`public/`](https://nuxt.com/docs/4.x/getting-started/assets#public-directory) directory. :: # Styling Nuxt is highly flexible when it comes to styling. Write your own styles, or reference local and external stylesheets. You can use CSS preprocessors, CSS frameworks, UI libraries and Nuxt modules to style your application. ## Local Stylesheets If you're writing local stylesheets, the natural place to put them is the [`app/assets/` directory](https://nuxt.com/docs/4.x/directory-structure/app/assets). ### Importing Within Components You can import stylesheets in your pages, layouts and components directly. You can use a JavaScript import, or a CSS [`@import` statement](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@import){rel=""nofollow""}. ```vue [app/pages/index.vue] ``` ::tip The stylesheets will be inlined in the HTML rendered by Nuxt. :: ### The CSS Property You can also use the `css` property in the Nuxt configuration. The natural place for your stylesheets is the [`app/assets/` directory](https://nuxt.com/docs/4.x/directory-structure/app/assets). You can then reference its path and Nuxt will include it to all the pages of your application. ```ts [nuxt.config.ts] export default defineNuxtConfig({ css: ['~/assets/css/main.css'], }) ``` ::tip The stylesheets will be inlined in the HTML rendered by Nuxt, injected globally and present in all pages. :: ### Working With Fonts Place your local fonts files in your `public/` directory, for example in `public/fonts`. You can then reference them in your stylesheets using `url()`. ```css [assets/css/main.css] @font-face { font-family: 'FarAwayGalaxy'; src: url('/fonts/FarAwayGalaxy.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; } ``` Then reference your fonts by name in your stylesheets, pages or components: ```vue ``` ### Stylesheets Distributed Through NPM You can also reference stylesheets that are distributed through npm. Let's use the popular `animate.css` library as an example. ::code-group{sync="pm"} ```bash [npm] npm install animate.css ``` ```bash [yarn] yarn add animate.css ``` ```bash [pnpm] pnpm install animate.css ``` ```bash [bun] bun install animate.css ``` ```bash [deno] deno install npm:animate.css ``` :: Then you can reference it directly in your pages, layouts and components: ```vue [app/app.vue] ``` The package can also be referenced as a string in the css property of your Nuxt configuration. ```ts [nuxt.config.ts] export default defineNuxtConfig({ css: ['animate.css'], }) ``` ## External Stylesheets You can include external stylesheets in your application by adding a link element in the head section of your nuxt.config file. You can achieve this result using different methods. Note that local stylesheets can also be included this way. You can manipulate the head with the [`app.head`](https://nuxt.com/docs/4.x/api/nuxt-config#head) property of your Nuxt configuration: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { head: { link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }], }, }, }) ``` ### Dynamically Adding Stylesheets You can use the useHead composable to dynamically set a value in your head in your code. :read-more{to="https://nuxt.com/docs/4.x/api/composables/use-head"} ```ts twoslash useHead({ link: [{ rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css' }], }) ``` Nuxt uses `unhead` under the hood, and you can refer to [its full documentation](https://unhead.unjs.io){rel=""nofollow""}. ### Modifying The Rendered Head With A Nitro Plugin If you need more advanced control, you can intercept the rendered html with a hook and modify the head programmatically. Create a plugin in `~/server/plugins/my-plugin.ts` like this: ```ts [server/plugins/my-plugin.ts] export default defineNitroPlugin((nitro) => { nitro.hooks.hook('render:html', (html) => { html.head.push('') }) }) ``` External stylesheets are render-blocking resources: they must be loaded and processed before the browser renders the page. Web pages that contain unnecessarily large styles take longer to render. You can read more about it on [web.dev](https://web.dev/articles/defer-non-critical-css){rel=""nofollow""}. ## Using Preprocessors To use a preprocessor like SCSS, Sass, Less or Stylus, install it first. ::code-group ```bash [Sass & SCSS] npm install -D sass ``` ```bash [Less] npm install -D less ``` ```bash [Stylus] npm install -D stylus ``` :: The natural place to write your stylesheets is the `app/assets` directory. You can then import your source files in your `app.vue` (or layouts files) using your preprocessor's syntax. ```vue [app/pages/app.vue] ``` Alternatively, you can use the `css` property of your Nuxt configuration. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ css: ['~/assets/scss/main.scss'], }) ``` ::tip In both cases, the compiled stylesheets will be inlined in the HTML rendered by Nuxt. :: If you need to inject code in pre-processed files, like a [Sass partial](https://sass-lang.com/documentation/at-rules/use/#partials){rel=""nofollow""} with color variables, you can do so with the Vite [preprocessors options](https://vite.dev/config/shared-options#css-preprocessoroptions){rel=""nofollow""}. Create some partials in your `app/assets` directory: ::code-group{sync="preprocessor"} ```scss [assets/_colors.scss] $primary: #49240F; $secondary: #E4A79D; ``` ```sass [assets/_colors.sass] $primary: #49240F $secondary: #E4A79D ``` :: Then in your `nuxt.config` : ::code-group ```ts [SCSS] twoslash export default defineNuxtConfig({ vite: { css: { preprocessorOptions: { scss: { additionalData: '@use "~/assets/_colors.scss" as *;', }, }, }, }, }) ``` ```ts [SASS] twoslash export default defineNuxtConfig({ vite: { css: { preprocessorOptions: { sass: { additionalData: '@use "~/assets/_colors.sass" as *\n', }, }, }, }, }) ``` :: Nuxt uses Vite by default. If you wish to use webpack instead, refer to each preprocessor loader [documentation](https://webpack.js.org/loaders/sass-loader/){rel=""nofollow""}. ### Preprocessor Workers (Experimental) Vite has made available an [experimental option](https://vite.dev/config/shared-options#css-preprocessormaxworkers){rel=""nofollow""} which can speed up using preprocessors. You can enable this in your `nuxt.config`: ```ts export default defineNuxtConfig({ vite: { css: { preprocessorMaxWorkers: true, // number of CPUs minus 1 }, }, }) ``` ::note This is an experimental option and you should refer to the Vite documentation and [provide feedback](https://github.com/vitejs/vite/discussions/15835){rel=""nofollow""}. :: ## Single File Components (SFC) Styling One of the best things about Vue and SFC is how great it is at naturally dealing with styling. You can directly write CSS or preprocessor code in the style block of your components file, therefore you will have fantastic developer experience without having to use something like CSS-in-JS. However if you wish to use CSS-in-JS, you can find 3rd party libraries and modules that support it, such as [pinceau](https://github.com/Tahul/pinceau){rel=""nofollow""}. You can refer to the [Vue docs](https://vuejs.org/api/sfc-css-features){rel=""nofollow""} for a comprehensive reference about styling components in SFC. ### Class And Style Bindings You can leverage Vue SFC features to style your components with class and style attributes. ::code-group ```vue [Ref and Reactive] ``` ```vue [Computed] ``` ```vue [Array] ``` ```vue [Style] ``` :: Refer to the [Vue docs](https://vuejs.org/guide/essentials/class-and-style){rel=""nofollow""} for more information. ### Dynamic Styles With `v-bind` You can reference JavaScript variable and expression within your style blocks with the v-bind function. The binding will be dynamic, meaning that if the variable value changes, the style will be updated. ```vue ``` ### Scoped Styles The scoped attribute allows you to style components in isolation. The styles declared with this attribute will only apply to this component. ```vue ``` ### CSS Modules You can use [CSS Modules](https://github.com/css-modules/css-modules){rel=""nofollow""} with the module attribute. Access it with the injected `$style` variable. ```vue ``` ### Preprocessors Support SFC style blocks support preprocessor syntax. Vite comes with built-in support for .scss, .sass, .less, .styl and .stylus files without configuration. You just need to install them first, and they will be available directly in SFC with the lang attribute. ::code-group ```vue [SCSS] ``` ```vue [Sass] ``` ```vue [LESS] ``` ```vue [Stylus] ``` :: You can refer to the [Vite CSS docs](https://vite.dev/guide/features#css){rel=""nofollow""} and the [@vitejs/plugin-vue docs](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue){rel=""nofollow""}. For webpack users, refer to the [vue loader docs](https://vue-loader.vuejs.org){rel=""nofollow""}. ## Using PostCSS Nuxt comes with postcss built-in. You can configure it in your `nuxt.config` file. ```ts [nuxt.config.ts] export default defineNuxtConfig({ postcss: { plugins: { 'postcss-nested': {}, 'postcss-custom-media': {}, }, }, }) ``` For proper syntax highlighting in SFC, you can use the postcss lang attribute. ```vue ``` By default, Nuxt comes with the following plugins already pre-configured: - [postcss-import](https://github.com/postcss/postcss-import){rel=""nofollow""}: Improves the `@import` rule - [postcss-url](https://github.com/postcss/postcss-url){rel=""nofollow""}: Transforms `url()` statements - [autoprefixer](https://github.com/postcss/autoprefixer){rel=""nofollow""}: Automatically adds vendor prefixes - [cssnano](https://cssnano.github.io/cssnano/){rel=""nofollow""}: Minification and purge ## Leveraging Layouts For Multiple Styles If you need to style different parts of your application completely differently, you can use layouts. Use different styles for different layouts. ```vue ``` :read-more{to="https://nuxt.com/docs/4.x/directory-structure/app/layouts"} ## Third Party Libraries And Modules Nuxt isn't opinionated when it comes to styling and provides you with a wide variety of options. You can use any styling tool that you want, such as popular libraries like [UnoCSS](https://unocss.dev){rel=""nofollow""} or [Tailwind CSS](https://tailwindcss.com){rel=""nofollow""}. The community and the Nuxt team have developed plenty of Nuxt modules to make the integration easier. You can discover them on the [modules section](https://nuxt.com/modules) of the website. Here are a few modules to help you get started: - [UnoCSS](https://nuxt.com/modules/unocss): Instant on-demand atomic CSS engine - [Tailwind CSS](https://nuxt.com/modules/tailwindcss): Utility-first CSS framework - [Fontaine](https://github.com/nuxt-modules/fontaine){rel=""nofollow""}: Font metric fallback - [Pinceau](https://github.com/Tahul/pinceau){rel=""nofollow""}: Adaptable styling framework - [Nuxt UI](https://ui.nuxt.com){rel=""nofollow""}: A UI Library for Modern Web Apps - [Panda CSS](https://panda-css.com/docs/installation/nuxt){rel=""nofollow""}: CSS-in-JS engine that generates atomic CSS at build time Nuxt modules provide you with a good developer experience out of the box, but remember that if your favorite tool doesn't have a module, it doesn't mean that you can't use it with Nuxt! You can configure it yourself for your own project. Depending on the tool, you might need to use a [Nuxt plugin](https://nuxt.com/docs/4.x/directory-structure/app/plugins) and/or [make your own module](https://nuxt.com/docs/4.x/guide/modules). Share them with the [community](https://nuxt.com/modules) if you do! ### Easily Load Webfonts You can use [the Nuxt Google Fonts module](https://github.com/nuxt-modules/google-fonts){rel=""nofollow""} to load Google Fonts. If you are using [UnoCSS](https://unocss.dev/integrations/nuxt){rel=""nofollow""}, note that it comes with a [web fonts presets](https://unocss.dev/presets/web-fonts){rel=""nofollow""} to conveniently load fonts from common providers, including Google Fonts and more. ## Advanced ### Transitions Nuxt comes with the same `` element that Vue has, and also has support for the experimental [View Transitions API](https://nuxt.com/docs/4.x/getting-started/transitions#view-transitions-api-experimental). :read-more{to="https://nuxt.com/docs/4.x/getting-started/transitions"} ### Font Advanced Optimization We would recommend using [Fontaine](https://github.com/nuxt-modules/fontaine){rel=""nofollow""} to reduce your [CLS](https://web.dev/articles/cls){rel=""nofollow""}. If you need something more advanced, consider creating a Nuxt module to extend the build process or the Nuxt runtime. ::tip Always remember to take advantage of the various tools and techniques available in the Web ecosystem at large to make styling your application easier and more efficient. Whether you're using native CSS, a preprocessor, postcss, a UI library or a module, Nuxt has got you covered. Happy styling! :: ### LCP Advanced Optimizations You can do the following to speed-up the download of your global CSS files: - Use a CDN so the files are physically closer to your users - Compress your assets, ideally using Brotli - Use HTTP2/HTTP3 for delivery - Host your assets on the same domain (do not use a different subdomain) Most of these things should be done for you automatically if you're using modern platforms like Cloudflare, Netlify or Vercel. You can find an LCP optimization guide on [web.dev](https://web.dev/articles/optimize-lcp){rel=""nofollow""}. If all of your CSS is inlined by Nuxt, you can (experimentally) completely stop external CSS files from being referenced in your rendered HTML. You can achieve that with a hook, that you can place in a module, or in your Nuxt configuration file. ```ts [nuxt.config.ts] export default defineNuxtConfig({ hooks: { 'build:manifest': (manifest) => { // find the app entry, css list const css = Object.values(manifest).find(options => options.isEntry)?.css if (css) { // start from the end of the array and go to the beginning for (let i = css.length - 1; i >= 0; i--) { // if it starts with 'entry', remove it from the list if (css[i].startsWith('entry')) { css.splice(i, 1) } } } }, }, }) ``` # Routing One core feature of Nuxt is the file system router. Every Vue file inside the [`app/pages/`](https://nuxt.com/docs/4.x/directory-structure/app/pages) directory creates a corresponding URL (or route) that displays the contents of the file. By using dynamic imports for each page, Nuxt leverages code-splitting to ship the minimum amount of JavaScript for the requested route. ## Pages Nuxt routing is based on [vue-router](https://router.vuejs.org){rel=""nofollow""} and generates the routes from every component created in the [`app/pages/` directory](https://nuxt.com/docs/4.x/directory-structure/app/pages), based on their filename. This file system routing uses naming conventions to create dynamic and nested routes: ::code-group ```bash [Directory Structure] -| pages/ ---| about.vue ---| index.vue ---| posts/ -----| [id].vue ``` ```json [Generated Router File] { "routes": [ { "path": "/about", "component": "pages/about.vue" }, { "path": "/", "component": "pages/index.vue" }, { "path": "/posts/:id", "component": "pages/posts/[id].vue" } ] } ``` :: :read-more{to="https://nuxt.com/docs/4.x/directory-structure/app/pages"} ## Navigation The [``](https://nuxt.com/docs/4.x/api/components/nuxt-link) component links pages between them. It renders an `` tag with the `href` attribute set to the route of the page. Once the application is hydrated, page transitions are performed in JavaScript by updating the browser URL. This prevents full-page refreshes and allows for animated transitions. When a [``](https://nuxt.com/docs/4.x/api/components/nuxt-link) enters the viewport on the client side, Nuxt will automatically prefetch components and payload (generated pages) of the linked pages ahead of time, resulting in faster navigation. ```vue [app/pages/index.vue] ``` :read-more{to="https://nuxt.com/docs/4.x/api/components/nuxt-link"} ## Route Parameters The [`useRoute()`](https://nuxt.com/docs/4.x/api/composables/use-route) composable can be used in a ` ``` :read-more{to="https://nuxt.com/docs/4.x/api/composables/use-route"} ## Route Middleware Nuxt provides a customizable route middleware framework you can use throughout your application, ideal for extracting code that you want to run before navigating to a particular route. ::note Route middleware runs within the Vue part of your Nuxt app. Despite the similar name, they are completely different from server middleware, which are run in the Nitro server part of your app. :: ::important Route middleware does **not** run for server routes (e.g. `/api/*`) or other server requests. To apply middleware to these requests, use [server middleware](https://nuxt.com/docs/4.x/directory-structure/server#server-middleware) instead. :: There are three kinds of route middleware: 1. Anonymous (or inline) route middleware, which are defined directly in the pages where they are used. 2. Named route middleware, which are placed in the [`app/middleware/`](https://nuxt.com/docs/4.x/directory-structure/app/middleware) directory and will be automatically loaded via asynchronous import when used on a page. (**Note**: The route middleware name is normalized to kebab-case, so `someMiddleware` becomes `some-middleware`.) 3. Global route middleware, which are placed in the [`app/middleware/`](https://nuxt.com/docs/4.x/directory-structure/app/middleware) directory (with a `.global` suffix) and will be automatically run on every route change. Example of an `auth` middleware protecting the `/dashboard` page: ::code-group ```ts [middleware/auth.ts] twoslash function isAuthenticated (): boolean { return false } // ---cut--- export default defineNuxtRouteMiddleware((to, from) => { // isAuthenticated() is an example method verifying if a user is authenticated if (isAuthenticated() === false) { return navigateTo('/login') } }) ``` ```vue [pages/dashboard.vue] twoslash ``` :: :read-more{to="https://nuxt.com/docs/4.x/directory-structure/app/middleware"} ## Route Validation Nuxt offers route validation via the `validate` property in [`definePageMeta()`](https://nuxt.com/docs/4.x/api/utils/define-page-meta) in each page you wish to validate. The `validate` property accepts the `route` as an argument. You can return a boolean value to determine whether or not this is a valid route to be rendered with this page. If you return `false`, this will cause a 404 error. You can also directly return an object with `status`/`statusText` to customize the error returned. If you have a more complex use case, then you can use anonymous route middleware instead. ```vue [pages/posts/[id\\].vue] twoslash ``` :read-more{to="https://nuxt.com/docs/4.x/api/utils/define-page-meta"} # SEO and Meta Nuxt head tag management is powered by [Unhead](https://unhead.unjs.io){rel=""nofollow""}. It provides sensible defaults, several powerful composables and numerous configuration options to manage your app's head and SEO meta tags. ## Nuxt Config Providing an [`app.head`](https://nuxt.com/docs/4.x/api/nuxt-config#head) property in your [`nuxt.config.ts`](https://nuxt.com/docs/4.x/directory-structure/nuxt-config) allows you to statically customize the head for your entire app. ::important This method does not allow you to provide reactive data. We recommend using `useHead()` in `app.vue`. :: It's good practice to set tags here that won't change such as your site title default, language and favicon. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { head: { title: 'Nuxt', // default fallback title htmlAttrs: { lang: 'en', }, link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }, ], }, }, }) ``` You can also provide any of the keys listed below in [Types](https://nuxt.com/docs/4.x/getting-started/seo-meta#types). ### Defaults Tags Some tags are provided by Nuxt by default to ensure your website works well out of the box. - `viewport`: `width=device-width, initial-scale=1` - `charset`: `utf-8` While most sites won't need to override these defaults, you can update them using the keyed shortcuts. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { head: { // update Nuxt defaults charset: 'utf-16', viewport: 'width=device-width, initial-scale=1, maximum-scale=1', }, }, }) ``` ## `useHead` The [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head) composable function supports reactive input, allowing you to manage your head tags programmatically. ```vue [app/app.vue] twoslash ``` We recommend taking a look at the [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head) and [`useHeadSafe`](https://nuxt.com/docs/4.x/api/composables/use-head-safe) composables. ## `useSeoMeta` The [`useSeoMeta`](https://nuxt.com/docs/4.x/api/composables/use-seo-meta) composable lets you define your site's SEO meta tags as an object with full type safety. This helps you avoid typos and common mistakes, such as using `name` instead of `property`. ```vue [app/app.vue] twoslash ``` :read-more{to="https://nuxt.com/docs/4.x/api/composables/use-seo-meta"} ## Components While using [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head) is recommended in all cases, you may have a personal preference for defining your head tags in your template using components. Nuxt provides the following components for this purpose: ``, `<Base>`, `<NoScript>`, `<Style>`, `<Meta>`, `<Link>`, `<Body>`, `<Html>` and `<Head>`. Note the capitalization of these components ensuring we don't use invalid native HTML tags. `<Head>` and `<Body>` can accept nested meta tags (for aesthetic reasons) but this does not affect *where* the nested meta tags are rendered in the final HTML. ```vue [app/app.vue] <script setup lang="ts"> const title = ref('Hello World') </script> <template> <div> <Head> <Title>{{ title }}

{{ title }}

``` It's suggested to wrap your components in either a `` or `` components as tags will be deduped more intuitively. ::warning If you need to duplicate tags across client-server boundaries, apply a `key` attribute on the `` component. :: ## Types Below are the non-reactive types used for [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head), [`app.head`](https://nuxt.com/docs/4.x/api/nuxt-config#head) and components. ```ts interface MetaObject { title?: string titleTemplate?: string | ((title?: string) => string) templateParams?: Record> base?: Base link?: Link[] meta?: Meta[] style?: Style[] script?: Script[] noscript?: Noscript[] htmlAttrs?: HtmlAttributes bodyAttrs?: BodyAttributes } ``` See [@unhead/vue](https://github.com/unjs/unhead/blob/main/packages/vue/src/types/schema.ts){rel=""nofollow""} for more detailed types. ## Features ### Reactivity Reactivity is supported on all properties, by providing a computed value, a getter, or a reactive object. ::code-group ```vue [useHead] twoslash ``` ```vue [useSeoMeta] twoslash ``` ```vue [app/Components] ``` :: ### Title Template You can use the `titleTemplate` option to provide a dynamic template for customizing the title of your site. For example, you could add the name of your site to the title of every page. The `titleTemplate` can either be a string, where `%s` is replaced with the title, or a function. If you want to use a function (for full control), then this cannot be set in your `nuxt.config`. It is recommended instead to set it within your `app.vue` file where it will apply to all pages on your site: ::code-group ```vue [useHead] twoslash ``` :: Now, if you set the title to `My Page` with [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head) on another page of your site, the title would appear as 'My Page - Site Title' in the browser tab. You could also pass `null` to default to 'Site Title'. ### Template Params You can use `templateParams` to provide additional placeholders in your `titleTemplate` besides the default `%s`. This allows for more dynamic title generation. ::code-group ```vue [useHead] twoslash ``` :: ### Body Tags You can use the `tagPosition: 'bodyClose'` option on applicable tags to append them to the end of the `` tag. For example: ```vue twoslash ``` ## Examples ### With `definePageMeta` Within your [`app/pages/` directory](https://nuxt.com/docs/4.x/directory-structure/app/pages), you can use `definePageMeta` along with [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head) to set metadata based on the current route. For example, you can first set the current page title (this is extracted at build time via a macro, so it can't be set dynamically): ```vue [pages/some-page.vue] twoslash ``` And then in your layout file, you might use the route's metadata you have previously set: ```vue [layouts/default.vue] twoslash ``` :link-example{to="https://nuxt.com/docs/4.x/examples/features/meta-tags"} :read-more{to="https://nuxt.com/docs/4.x/directory-structure/app/pages/#page-metadata"} ### Dynamic Title In the example below, `titleTemplate` is set either as a string with the `%s` placeholder or as a `function`, which allows greater flexibility in setting the page title dynamically for each route of your Nuxt app: ```vue [app/app.vue] twoslash ``` ```vue [app/app.vue] twoslash ``` `nuxt.config` is also used as an alternative way of setting the page title. However, `nuxt.config` does not allow the page title to be dynamic. Therefore, it is recommended to use `titleTemplate` in the `app.vue` file to add a dynamic title, which is then applied to all routes of your Nuxt app. ### External CSS The example below shows how you might enable Google Fonts using either the `link` property of the [`useHead`](https://nuxt.com/docs/4.x/api/composables/use-head) composable or using the `` component: ::code-group ```vue [useHead] twoslash ``` ```vue [app/Components] ``` :: # Transitions ::note Nuxt leverages Vue's [``](https://vuejs.org/guide/built-ins/transition#the-transition-component){rel=""nofollow""} component to apply transitions between pages and layouts. :: ## Page Transitions You can enable page transitions to apply an automatic transition for all your [pages](https://nuxt.com/docs/4.x/directory-structure/app/pages). ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { pageTransition: { name: 'page', mode: 'out-in' }, }, }) ``` ::note If you are changing layouts as well as page, the page transition you set here will not run. Instead, you should set a [layout transition](https://nuxt.com/docs/4.x/getting-started/transitions#layout-transitions). :: To start adding transition between your pages, add the following CSS to your [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app): ::code-group ```vue [app/app.vue] ``` ```vue [app/pages/index.vue] ``` ```vue [app/pages/about.vue] ``` :: This produces the following result when navigating between pages: :video{.rounded controls="true" poster="https://res.cloudinary.com/nuxt/video/upload/v1665061349/nuxt3/nuxt3-page-transitions_umwvmh.jpg"} To set a different transition for a page, set the `pageTransition` key in [`definePageMeta`](https://nuxt.com/docs/4.x/api/utils/define-page-meta) of the page: ::code-group ```vue [pages/about.vue] twoslash ``` ```vue [app/app.vue] ``` :: Moving to the about page will add the 3d rotation effect: :video{.rounded controls="true" poster="https://res.cloudinary.com/nuxt/video/upload/v1665063233/nuxt3/nuxt3-page-transitions-cutom.jpg"} ## Layout Transitions You can enable layout transitions to apply an automatic transition for all your [layouts](https://nuxt.com/docs/4.x/directory-structure/app/layouts). ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { layoutTransition: { name: 'layout', mode: 'out-in' }, }, }) ``` To start adding transition between your pages and layouts, add the following CSS to your [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app): ::code-group ```vue [app/app.vue] ``` ```vue [app/layouts/default.vue] ``` ```vue [app/layouts/orange.vue] ``` ```vue [app/pages/index.vue] ``` ```vue [app/pages/about.vue] ``` :: This produces the following result when navigating between pages: :video{.rounded controls="true" poster="https://res.cloudinary.com/nuxt/video/upload/v1665065289/nuxt3/nuxt3-layouts-transitions_c9hwlx.jpg"} Similar to `pageTransition`, you can apply a custom `layoutTransition` to the page component using `definePageMeta`: ```vue [pages/about.vue] twoslash ``` ## Global Settings You can customize these default transition names globally using `nuxt.config`. Both `pageTransition` and `layoutTransition` keys accept [`TransitionProps`](https://vuejs.org/api/built-in-components#transition){rel=""nofollow""} as JSON serializable values where you can pass the `name`, `mode` and other valid transition-props of the custom CSS transition. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { pageTransition: { name: 'fade', mode: 'out-in', // default }, layoutTransition: { name: 'slide', mode: 'out-in', // default }, }, }) ``` ::warning If you change the `name` property, you also have to rename the CSS classes accordingly. :: To override the global transition property, use the `definePageMeta` to define page or layout transitions for a single Nuxt page and override any page or layout transitions that are defined globally in `nuxt.config` file. ```vue [pages/some-page.vue] twoslash ``` ## Disable Transitions `pageTransition` and `layoutTransition` can be disabled for a specific route: ```vue [pages/some-page.vue] twoslash ``` Or globally in the `nuxt.config`: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { pageTransition: false, layoutTransition: false, }, }) ``` ## JavaScript Hooks For advanced use-cases, you can use JavaScript hooks to create highly dynamic and custom transitions for your Nuxt pages. This way presents perfect use-cases for JavaScript animation libraries such as [GSAP](https://gsap.com){rel=""nofollow""}. ```vue [pages/some-page.vue] twoslash ``` ::tip Learn more about additional [JavaScript hooks](https://vuejs.org/guide/built-ins/transition#javascript-hooks){rel=""nofollow""} available in the `Transition` component. :: ## Dynamic Transitions To apply dynamic transitions using conditional logic, you can leverage inline [middleware](https://nuxt.com/docs/4.x/directory-structure/app/middleware) to assign a different transition name to `to.meta.pageTransition`. ::code-group ```vue [pages/[id\\].vue] twoslash ``` ```vue [app/layouts/default.vue] ``` :: The page now applies the `slide-left` transition when going to the next id and `slide-right` for the previous: :video{.rounded controls="true" poster="https://res.cloudinary.com/nuxt/video/upload/v1665069410/nuxt3/nuxt-dynamic-page-transitions.jpg"} ## Transition with NuxtPage When `` is used in `app.vue`, transitions can be configured with the `transition` prop to activate transitions globally. ```vue [app/app.vue] ``` ::note Remember, this page transition cannot be overridden with `definePageMeta` on individual pages. :: ## View Transitions API (experimental) Nuxt ships with an experimental implementation of the [**View Transitions API**](https://developer.chrome.com/docs/web-platform/view-transitions){rel=""nofollow""} (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/View_Transition_API){rel=""nofollow""}). This is an exciting new way to implement native browser transitions which (among other things) have the ability to transition between unrelated elements on different pages. You can check a demo [on StackBlitz](https://stackblitz.com/edit/nuxt-view-transitions){rel=""nofollow""}. The Nuxt integration can be enabled with the `experimental.viewTransition` option in your configuration file: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { viewTransition: true, }, }) ``` The possible values are: `false`, `true`, or `'always'`. If set to true, Nuxt will not apply transitions if the user's browser matches `prefers-reduced-motion: reduce` (recommended). If set to `always`, Nuxt will always apply the transition and it is up to you to respect the user's preference. By default, view transitions are enabled for all [pages](https://nuxt.com/docs/4.x/directory-structure/app/pages), but you can set a different global default. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ app: { // Disable view transitions globally, and opt-in on a per page basis viewTransition: false, }, }) ``` It is possible to override the default `viewTransition` value for a page by setting the `viewTransition` key in [`definePageMeta`](https://nuxt.com/docs/4.x/api/utils/define-page-meta) of the page: ```vue [pages/about.vue] twoslash ``` ::warning Overriding view transitions on a per-page basis will only have an effect if you have enabled the `experimental.viewTransition` option. :: If you are also using Vue transitions like `pageTransition` and `layoutTransition` (see above) to achieve the same result as the new View Transitions API, then you may wish to *disable* Vue transitions if the user's browser supports the newer, native web API. You can do this by creating `~/middleware/disable-vue-transitions.global.ts` with the following contents: ```ts export default defineNuxtRouteMiddleware((to) => { if (import.meta.server || !document.startViewTransition) { return } // Disable built-in Vue transitions to.meta.pageTransition = false to.meta.layoutTransition = false }) ``` ### Known Issues - If you perform data fetching within your page setup functions, you may wish to reconsider using this feature for the moment. (By design, View Transitions completely freeze DOM updates whilst they are taking place.) We're looking at restricting the View Transition to the final moments before `` resolves, but in the interim you may want to consider carefully whether to adopt this feature if this describes you. # Data Fetching Nuxt comes with two composables and a built-in library to perform data-fetching in browser or server environments: `useFetch`, [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) and `$fetch`. In a nutshell: - [`$fetch`](https://nuxt.com/docs/4.x/api/utils/dollarfetch) is the simplest way to make a network request. - [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) is a wrapper around `$fetch` that fetches data only once in [universal rendering](https://nuxt.com/docs/4.x/guide/concepts/rendering#universal-rendering). - [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) is similar to `useFetch` but offers more fine-grained control. Both `useFetch` and `useAsyncData` share a common set of options and patterns that we will detail in the last sections. ## The need for `useFetch` and `useAsyncData` Nuxt is a framework which can run isomorphic (or universal) code in both server and client environments. If the [`$fetch` function](https://nuxt.com/docs/4.x/api/utils/dollarfetch) is used to perform data fetching in the setup function of a Vue component, this may cause data to be fetched twice, once on the server (to render the HTML) and once again on the client (when the HTML is hydrated). This can cause hydration issues, increase the time to interactivity and cause unpredictable behavior. The [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) and [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) composables solve this problem by ensuring that if an API call is made on the server, the data is forwarded to the client in the payload. The payload is a JavaScript object accessible through [`useNuxtApp().payload`](https://nuxt.com/docs/4.x/api/composables/use-nuxt-app#payload). It is used on the client to avoid refetching the same data when the code is executed in the browser [during hydration](https://nuxt.com/docs/4.x/guide/concepts/rendering#universal-rendering). ::tip Use the [Nuxt DevTools](https://devtools.nuxt.com){rel=""nofollow""} to inspect this data in the **Payload tab**. :: ```vue [app/app.vue] ``` In the example above, `useFetch` would make sure that the request would occur in the server and is properly forwarded to the browser. `$fetch` has no such mechanism and is a better option to use when the request is solely made from the browser. ### Suspense Nuxt uses Vue's [``](https://vuejs.org/guide/built-ins/suspense){rel=""nofollow""} component under the hood to prevent navigation before every async data is available to the view. The data fetching composables can help you leverage this feature and use what suits best on a per-call basis. ::note You can add the [``](https://nuxt.com/docs/4.x/api/components/nuxt-loading-indicator) to add a progress bar between page navigations. :: ## `$fetch` Nuxt includes the [ofetch](https://github.com/unjs/ofetch){rel=""nofollow""} library, and is auto-imported as the `$fetch` alias globally across your application. ```vue [pages/todos.vue] twoslash ``` ::warning Beware that using only `$fetch` will not provide [network calls de-duplication and navigation prevention](https://nuxt.com/docs/4.x/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata). :br It is recommended to use `$fetch` for client-side interactions (event-based) or combined with [`useAsyncData`](https://nuxt.com/docs/4.x/getting-started/data-fetching#useasyncdata) when fetching the initial component data. :: ::read-more{to="https://nuxt.com/docs/4.x/api/utils/dollarfetch"} Read more about `$fetch`. :: ### Pass Client Headers to the API When calling `useFetch` on the server, Nuxt will use [`useRequestFetch`](https://nuxt.com/docs/4.x/api/composables/use-request-fetch) to proxy client headers and cookies (with the exception of headers not meant to be forwarded, like `host`). ```vue ``` ```ts // /api/echo.ts export default defineEventHandler(event => parseCookies(event)) ``` Alternatively, the example below shows how to use [`useRequestHeaders`](https://nuxt.com/docs/4.x/api/composables/use-request-headers) to access and send cookies to the API from a server-side request (originating on the client). Using an isomorphic `$fetch` call, we ensure that the API endpoint has access to the same `cookie` header originally sent by the user's browser. This is only necessary if you aren't using `useFetch`. ```vue ``` ::tip You can also use [`useRequestFetch`](https://nuxt.com/docs/4.x/api/composables/use-request-fetch) to proxy headers to the call automatically. :: ::caution Be very careful before proxying headers to an external API and just include headers that you need. Not all headers are safe to be bypassed and might introduce unwanted behavior. Here is a list of common headers that are NOT to be proxied: - `host`, `accept` - `content-length`, `content-md5`, `content-type` - `x-forwarded-host`, `x-forwarded-port`, `x-forwarded-proto` - `cf-connecting-ip`, `cf-ray` :: ## `useFetch` The [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) composable uses `$fetch` under-the-hood to make SSR-safe network calls in the setup function. ```vue [app/app.vue] twoslash ``` This composable is a wrapper around the [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) composable and `$fetch` utility. :video-accordion{title="Watch a video from Alexander Lichter to avoid using useFetch the wrong way" video-id="njsGVmcWviY"} :read-more{to="https://nuxt.com/docs/4.x/api/composables/use-fetch"} :link-example{to="https://nuxt.com/docs/4.x/examples/features/data-fetching"} ## `useAsyncData` The `useAsyncData` composable is responsible for wrapping async logic and returning the result once it is resolved. ::tip `useFetch(url)` is nearly equivalent to `useAsyncData(url, () => event.$fetch(url))`. :br It's developer experience sugar for the most common use case. (You can find out more about `event.fetch` at [`useRequestFetch`](https://nuxt.com/docs/4.x/api/composables/use-request-fetch).) :: :video-accordion{title="Watch a video from Alexander Lichter to dig deeper into the difference between useFetch and useAsyncData" video-id="0X-aOpSGabA"} There are some cases when using the [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) composable is not appropriate, for example when a CMS or a third-party provide their own query layer. In this case, you can use [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) to wrap your calls and still keep the benefits provided by the composable. ```vue [app/pages/users.vue] ``` ::note The first argument of [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) is a unique key used to cache the response of the second argument, the querying function. This key can be ignored by directly passing the querying function, the key will be auto-generated. :br :br Since the autogenerated key only takes into account the file and line where `useAsyncData` is invoked, it is recommended to always create your own key to avoid unwanted behavior, like when you are creating your own custom composable wrapping `useAsyncData`. :br :br Setting a key can be useful to share the same data between components using [`useNuxtData`](https://nuxt.com/docs/4.x/api/composables/use-nuxt-data) or to [refresh specific data](https://nuxt.com/docs/4.x/api/utils/refresh-nuxt-data#refresh-specific-data). :: ```vue [app/pages/users/[id\\].vue] ``` The `useAsyncData` composable is a great way to wrap and wait for multiple `$fetch` requests to be completed, and then process the results. ```vue ``` ::note `useAsyncData` is for fetching and caching data, not triggering side effects like calling Pinia actions, as this can cause unintended behavior such as repeated executions with nullish values. If you need to trigger side effects, use the [`callOnce`](https://nuxt.com/docs/4.x/api/utils/call-once) utility to do so. ```vue ``` :: ::read-more{to="https://nuxt.com/docs/4.x/api/composables/use-async-data"} Read more about `useAsyncData`. :: ## Return Values `useFetch` and `useAsyncData` have the same return values listed below. - `data`: the result of the asynchronous function that is passed in. - `refresh`/`execute`: a function that can be used to refresh the data returned by the `handler` function. - `clear`: a function that can be used to set `data` to `undefined` (or the value of `options.default()` if provided), set `error` to `undefined`, set `status` to `idle`, and mark any currently pending requests as cancelled. - `error`: an error object if the data fetching failed. - `status`: a string indicating the status of the data request (`"idle"`, `"pending"`, `"success"`, `"error"`). ::note `data`, `error` and `status` are Vue refs accessible with `.value` in ` ``` You can alternatively use [`useLazyFetch`](https://nuxt.com/docs/4.x/api/composables/use-lazy-fetch) and `useLazyAsyncData` as convenient methods to perform the same. ```vue twoslash ``` ::read-more{to="https://nuxt.com/docs/4.x/api/composables/use-lazy-fetch"} Read more about `useLazyFetch`. :: ::read-more{to="https://nuxt.com/docs/4.x/api/composables/use-lazy-async-data"} Read more about `useLazyAsyncData`. :: :video-accordion{platform="vimeo" title="Watch a video from Vue School on blocking vs. non-blocking (lazy) requests" video-id="1022000555"} ### Client-only fetching By default, data fetching composables will perform their asynchronous function on both client and server environments. Set the `server` option to `false` to only perform the call on the client-side. On initial load, the data will not be fetched before hydration is complete so you have to handle a pending state, though on subsequent client-side navigation the data will be awaited before loading the page. Combined with the `lazy` option, this can be useful for data that is not needed on the first render (for example, non-SEO sensitive data). ```ts twoslash /* This call is performed before hydration */ const articles = await useFetch('/api/article') /* This call will only be performed on the client */ const { status, data: comments } = useFetch('/api/comments', { lazy: true, server: false, }) ``` The `useFetch` composable is meant to be invoked in setup method or called directly at the top level of a function in lifecycle hooks, otherwise you should use [`$fetch` method](https://nuxt.com/docs/4.x/getting-started/data-fetching#fetch). ### Minimize payload size The `pick` option helps you to minimize the payload size stored in your HTML document by only selecting the fields that you want returned from the composables. ```vue ``` If you need more control or map over several objects, you can use the `transform` function to alter the result of the query. ```ts const { data: mountains } = await useFetch('/api/mountains', { transform: (mountains) => { return mountains.map(mountain => ({ title: mountain.title, description: mountain.description })) }, }) ``` ::note Both `pick` and `transform` don't prevent the unwanted data from being fetched initially. But they will prevent unwanted data from being added to the payload transferred from server to client. :: :video-accordion{platform="vimeo" title="Watch a video from Vue School on minimizing payload size" video-id="1026410430"} ### Caching and refetching #### Keys [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) and [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) use keys to prevent refetching the same data. - [`useFetch`](https://nuxt.com/docs/4.x/api/composables/use-fetch) uses the provided URL as a key. Alternatively, a `key` value can be provided in the `options` object passed as a last argument. - [`useAsyncData`](https://nuxt.com/docs/4.x/api/composables/use-async-data) uses its first argument as a key if it is a string. If the first argument is the handler function that performs the query, then a key that is unique to the file name and line number of the instance of `useAsyncData` will be generated for you. ::tip To get the cached data by key, you can use [`useNuxtData`](https://nuxt.com/docs/4.x/api/composables/use-nuxt-data) :: :video-accordion{platform="vimeo" title="Watch a video from Vue School on caching data with the key option" video-id="1026410044"} #### Shared State and Option Consistency When multiple components use the same key with `useAsyncData` or `useFetch`, they will share the same `data`, `error` and `status` refs. This ensures consistency across components but requires some options to be consistent. The following options **must be consistent** across all calls with the same key: - `handler` function - `deep` option - `transform` function - `pick` array - `getCachedData` function - `default` value ```ts // ❌ This will trigger a development warning const { data: users1 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { deep: false }) const { data: users2 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { deep: true }) ``` The following options **can safely differ** without triggering warnings: - `server` - `lazy` - `immediate` - `dedupe` - `watch` ```ts // ✅ This is allowed const { data: users1 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { immediate: true }) const { data: users2 } = useAsyncData('users', (_nuxtApp, { signal }) => $fetch('/api/users', { signal }), { immediate: false }) ``` If you need independent instances, use different keys: ```ts // These are completely independent instances const { data: users1 } = useAsyncData('users-1', (_nuxtApp, { signal }) => $fetch('/api/users', { signal })) const { data: users2 } = useAsyncData('users-2', (_nuxtApp, { signal }) => $fetch('/api/users', { signal })) ``` #### Reactive Keys You can use computed refs, plain refs or getter functions as keys, allowing for dynamic data fetching that automatically updates when dependencies change: ```ts // Using a computed property as a key const userId = ref('123') const { data: user } = useAsyncData( computed(() => `user-${userId.value}`), () => fetchUser(userId.value), ) // When userId changes, the data will be automatically refetched // and the old data will be cleaned up if no other components use it userId.value = '456' ``` #### Refresh and execute If you want to fetch or refresh data manually, use the `execute` or `refresh` function provided by the composables. ```vue twoslash ``` The `execute` function is an alias for `refresh` that works in exactly the same way but is more semantic for cases when the fetch is [not immediate](https://nuxt.com/docs/4.x/getting-started/data-fetching#not-immediate). ::tip To globally refetch or invalidate cached data, see [`clearNuxtData`](https://nuxt.com/docs/4.x/api/utils/clear-nuxt-data) and [`refreshNuxtData`](https://nuxt.com/docs/4.x/api/utils/refresh-nuxt-data). :: #### Clear If you want to clear the data provided, for whatever reason, without needing to know the specific key to pass to `clearNuxtData`, you can use the `clear` function provided by the composables. ```vue twoslash ``` #### Watch To re-run your fetching function each time other reactive values in your application change, use the `watch` option. You can use it for one or multiple *watchable* elements. ```vue twoslash ``` Note that **watching a reactive value won't change the URL fetched**. For example, this will keep fetching the same initial ID of the user because the URL is constructed at the moment the function is invoked. ```vue ``` If you need to change the URL based on a reactive value, you may want to use a [computed URL](https://nuxt.com/docs/4.x/getting-started/data-fetching#computed-url) instead. When reactive fetch options are provided, they'll be automatically watched and trigger refetches. In some cases, it can be useful to opt-out of this behavior by specifying `watch: false`. ```ts const id = ref(1) // Won't automatically refetch when id changes const { data, execute } = await useFetch('/api/users', { query: { id }, // id is watched by default watch: false, // disables automatic watching of id }) // doesn't trigger refetch id.value = 2 ``` #### Computed URL Sometimes you may need to compute a URL from reactive values, and refresh the data each time these change. Instead of juggling your way around, you can attach each param as a reactive value. Nuxt will automatically use the reactive value and re-fetch each time it changes. ```vue ``` In the case of more complex URL construction, you may use a callback as a [computed getter](https://vuejs.org/guide/essentials/computed){rel=""nofollow""} that returns the URL string. Every time a dependency changes, the data will be fetched using the newly constructed URL. Combine this with [not-immediate](https://nuxt.com/docs/4.x/getting-started/data-fetching#not-immediate), and you can wait until the reactive element changes before fetching. ```vue ``` If you need to force a refresh when other reactive values change, you can also [watch other values](https://nuxt.com/docs/4.x/getting-started/data-fetching#watch). ### Not immediate The `useFetch` composable will start fetching data the moment is invoked. You may prevent this by setting `immediate: false`, for example, to wait for user interaction. With that, you will need both the `status` to handle the fetch lifecycle, and `execute` to start the data fetch. ```vue ``` For finer control, the `status` variable can be: - `idle` when the fetch hasn't started - `pending` when a fetch has started but not yet completed - `error` when the fetch fails - `success` when the fetch is completed successfully ## Passing Headers and Cookies When we call `$fetch` in the browser, user headers like `cookie` will be directly sent to the API. Normally, during server-side-rendering, due to security considerations, the `$fetch` wouldn't include the user's browser cookies, nor pass on cookies from the fetch response. However, when calling `useFetch` with a relative URL on the server, Nuxt will use [`useRequestFetch`](https://nuxt.com/docs/4.x/api/composables/use-request-fetch) to proxy headers and cookies (with the exception of headers not meant to be forwarded, like `host`). ### Pass Cookies From Server-side API Calls on SSR Response If you want to pass on/proxy cookies in the other direction, from an internal request back to the client, you will need to handle this yourself. ```ts [app/composables/fetch.ts] import { appendResponseHeader } from 'h3' import type { H3Event } from 'h3' export const fetchWithCookie = async (event: H3Event, url: string) => { /* Get the response from the server endpoint */ const res = await $fetch.raw(url) /* Get the cookies from the response */ const cookies = res.headers.getSetCookie() /* Attach each cookie to our incoming Request */ for (const cookie of cookies) { appendResponseHeader(event, 'set-cookie', cookie) } /* Return the data of the response */ return res._data } ``` ```vue ``` ## Options API Support Nuxt provides a way to perform `asyncData` fetching within the Options API. You must wrap your component definition within `defineNuxtComponent` for this to work. ```vue ``` ::note Using ` ``` ### Custom serializer function To customize the serialization behavior, you can define a `toJSON` function on your returned object. If you define a `toJSON` method, Nuxt will respect the return type of the function and will not try to convert the types. ```ts [server/api/bar.ts] export default defineEventHandler(() => { const data = { createdAt: new Date(), toJSON () { return { createdAt: { year: this.createdAt.getFullYear(), month: this.createdAt.getMonth(), day: this.createdAt.getDate(), }, } }, } return data }) ``` ```vue [app/app.vue] ``` ### Using an alternative serializer Nuxt does not currently support an alternative serializer to `JSON.stringify`. However, you can return your payload as a normal string and utilize the `toJSON` method to maintain type safety. In the example below, we use [superjson](https://github.com/flightcontrolhq/superjson){rel=""nofollow""} as our serializer. ```ts [server/api/superjson.ts] import superjson from 'superjson' export default defineEventHandler(() => { const data = { createdAt: new Date(), // Workaround the type conversion toJSON () { return this }, } // Serialize the output to string, using superjson return superjson.stringify(data) as unknown as typeof data }) ``` ```vue [app/app.vue] ``` ## Recipes ### Consuming SSE (Server-Sent Events) via POST request ::tip If you're consuming SSE via GET request, you can use [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource){rel=""nofollow""} or VueUse composable [`useEventSource`](https://vueuse.org/core/useeventsource/){rel=""nofollow""}. :: When consuming SSE via POST request, you need to handle the connection manually. Here's how you can do it: ```ts // Make a POST request to the SSE endpoint const response = await $fetch('/chats/ask-ai', { method: 'POST', body: { query: 'Hello AI, how are you?', }, responseType: 'stream', }) // Create a new ReadableStream from the response with TextDecoderStream to get the data as text const reader = response.pipeThrough(new TextDecoderStream()).getReader() // Read the chunk of data as we get it while (true) { const { value, done } = await reader.read() if (done) { break } console.log('Received:', value) } ``` ### Making parallel requests When requests don't rely on each other, you can make them in parallel with `Promise.all()` to boost performance. ```ts const { data } = await useAsyncData((_nuxtApp, { signal }) => { return Promise.all([ $fetch('/api/comments/', { signal }), $fetch('/api/author/12', { signal }), ]) }) const comments = computed(() => data.value?.[0]) const author = computed(() => data.value?.[1]) ``` :video-accordion{platform="vimeo" title="Watch a video from Vue School on parallel data fetching" video-id="1024262536"} # State Management Nuxt provides the [`useState`](https://nuxt.com/docs/4.x/api/composables/use-state) composable to create a reactive and SSR-friendly shared state across components. [`useState`](https://nuxt.com/docs/4.x/api/composables/use-state) is an SSR-friendly [`ref`](https://vuejs.org/api/reactivity-core#ref){rel=""nofollow""} replacement. Its value will be preserved after server-side rendering (during client-side hydration) and shared across all components using a unique key. :video-accordion{title="Watch a video from Alexander Lichter about why and when to use useState" video-id="mv0WcBABcIk"} ::important Because the data inside [`useState`](https://nuxt.com/docs/4.x/api/composables/use-state) will be serialized to JSON, it is important that it does not contain anything that cannot be serialized, such as classes, functions or symbols. :: ::read-more{to="https://nuxt.com/docs/4.x/api/composables/use-state"} Read more about `useState` composable. :: ## Best Practices ::warning Never define `const state = ref()` outside of ` ``` :link-example{to="https://nuxt.com/docs/4.x/examples/features/state-management"} ::note To globally invalidate cached state, see [`clearNuxtState`](https://nuxt.com/docs/4.x/api/utils/clear-nuxt-state) util. :: ### Initializing State Most of the time, you will want to initialize your state with data that resolves asynchronously. You can use the [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app) component with the [`callOnce`](https://nuxt.com/docs/4.x/api/utils/call-once) util to do so. ```vue [app/app.vue] twoslash ``` ::tip This is similar to the [`nuxtServerInit` action](https://v2.nuxt.com/docs/directory-structure/store/#the-nuxtserverinit-action){rel=""nofollow""} in Nuxt 2, which allows filling the initial state of your store server-side before rendering the page. :: :read-more{to="https://nuxt.com/docs/4.x/api/utils/call-once"} ### Usage with Pinia In this example, we leverage the [Pinia module](https://nuxt.com/modules/pinia) to create a global store and use it across the app. ::important Make sure to install the Pinia module with `npx nuxt module add pinia` or follow the [module's installation steps](https://pinia.vuejs.org/ssr/nuxt.html#Installation){rel=""nofollow""}. :: ::code-group ```ts [app/stores/website.ts] export const useWebsiteStore = defineStore('websiteStore', { state: () => ({ name: '', description: '', }), actions: { async fetch () { const infos = await $fetch('https://api.nuxt.com/modules/pinia') this.name = infos.name this.description = infos.description }, }, }) ``` ```vue [app/app.vue] ``` :: ## Advanced Usage ::code-group ```ts [app/composables/locale.ts] import type { Ref } from 'vue' export const useLocale = () => { return useState('locale', () => useDefaultLocale().value) } export const useDefaultLocale = (fallback = 'en-US') => { const locale = ref(fallback) if (import.meta.server) { const reqLocale = useRequestHeaders()['accept-language']?.split(',')[0] if (reqLocale) { locale.value = reqLocale } } else if (import.meta.client) { const navLang = navigator.language if (navLang) { locale.value = navLang } } return locale } export const useLocales = () => { const locale = useLocale() const locales = ref([ 'en-US', 'en-GB', // ..., 'ja-JP-u-ca-japanese', ]) if (!locales.value.includes(locale.value)) { locales.value.unshift(locale.value) } return locales } export const useLocaleDate = (date: Ref | Date, locale = useLocale()) => { return computed(() => new Intl.DateTimeFormat(locale.value, { dateStyle: 'full' }).format(unref(date))) } ``` ```vue [app/app.vue] ``` :: :link-example{to="https://nuxt.com/docs/4.x/examples/advanced/locale"} ## Shared State By using [auto-imported composables](https://nuxt.com/docs/4.x/directory-structure/app/composables) we can define global type-safe states and import them across the app. ```ts [composables/states.ts] twoslash export const useColor = () => useState('color', () => 'pink') ``` ```vue [app/app.vue] ``` :video-accordion{title="Watch a video from Daniel Roe on how to deal with global state and SSR in Nuxt" video-id="dZSNW07sO-A"} ## Using third-party libraries Nuxt **used to rely** on the Vuex library to provide global state management. If you are migrating from Nuxt 2, please head to [the migration guide](https://nuxt.com/docs/4.x/migration/configuration#vuex). Nuxt is not opinionated about state management, so feel free to choose the right solution for your needs. There are multiple integrations with the most popular state management libraries, including: - [Pinia](https://nuxt.com/modules/pinia) - the official Vue recommendation - [Harlem](https://nuxt.com/modules/harlem) - immutable global state management - [XState](https://nuxt.com/modules/xstate) - state machine approach with tools for visualizing and testing your state logic # Error Handling Nuxt is a full-stack framework, which means there are several sources of unpreventable user runtime errors that can happen in different contexts: - Errors during the Vue rendering lifecycle (SSR & CSR) - Server and client startup errors (SSR + CSR) - Errors during Nitro server lifecycle ([`server/`](https://nuxt.com/docs/4.x/directory-structure/server) directory) - Errors downloading JS chunks ::tip **SSR** stands for **Server-Side Rendering** and **CSR** for **Client-Side Rendering**. :: ## Vue Errors You can hook into Vue errors using [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle#onerrorcaptured){rel=""nofollow""}. In addition, Nuxt provides a [`vue:error`](https://nuxt.com/docs/4.x/api/advanced/hooks#app-hooks-runtime) hook that will be called if any errors propagate up to the top level. If you are using an error reporting framework, you can provide a global handler through [`vueApp.config.errorHandler`](https://vuejs.org/api/application#app-config-errorhandler){rel=""nofollow""}. It will receive all Vue errors, even if they are handled. ```ts [plugins/error-handler.ts] twoslash export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.config.errorHandler = (error, instance, info) => { // handle error, e.g. report to a service } // Also possible nuxtApp.hook('vue:error', (error, instance, info) => { // handle error, e.g. report to a service }) }) ``` ::note Note that the `vue:error` hook is based on [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle#onerrorcaptured){rel=""nofollow""} lifecycle hook. :: ## Startup Errors Nuxt will call the `app:error` hook if there are any errors in starting your Nuxt application. This includes: - running [Nuxt plugins](https://nuxt.com/docs/4.x/directory-structure/app/plugins) - processing `app:created` and `app:beforeMount` hooks - rendering your Vue app to HTML (during SSR) - mounting the app (on client-side), though you should handle this case with `onErrorCaptured` or with `vue:error` - processing the `app:mounted` hook ## Nitro Server Errors You cannot currently define a server-side handler for these errors, but can render an error page, see the [Render an Error Page](https://nuxt.com/docs/4.x/getting-started/error-handling#error-page) section. ## Errors with JS Chunks You might encounter chunk loading errors due to a network connectivity failure or a new deployment (which invalidates your old, hashed JS chunk URLs). Nuxt provides built-in support for handling chunk loading errors by performing a hard reload when a chunk fails to load during route navigation. You can change this behavior by setting `experimental.emitRouteChunkError` to `false` (to disable hooking into these errors at all) or to `manual` if you want to handle them yourself. If you want to handle chunk loading errors manually, you can check out the [the automatic implementation](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/plugins/chunk-reload.client.ts){rel=""nofollow""} for ideas. ## Error Page ::note When Nuxt encounters a fatal error (any unhandled error on the server, or an error created with `fatal: true` on the client) it will either render a JSON response (if requested with `Accept: application/json` header) or trigger a full-screen error page. :: An error may occur during the server lifecycle when: - processing your Nuxt plugins - rendering your Vue app into HTML - a server API route throws an error It can also occur on the client side when: - processing your Nuxt plugins - before mounting the application (`app:beforeMount` hook) - mounting your app if the error was not handled with `onErrorCaptured` or `vue:error` hook - the Vue app is initialized and mounted in browser (`app:mounted`). ::read-more{to="https://nuxt.com/docs/4.x/api/advanced/hooks"} Discover all the Nuxt lifecycle hooks. :: Customize the default error page by adding `~/error.vue` in the source directory of your application, alongside `app.vue`. ```vue [error.vue] ``` ::read-more{to="https://nuxt.com/docs/4.x/directory-structure/app/error"} Read more about `error.vue` and its uses. :: For custom errors we highly recommend using `onErrorCaptured` composable that can be called in a page/component setup function or `vue:error` runtime nuxt hook that can be configured in a nuxt plugin. ```ts [plugins/error-handler.ts] twoslash export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('vue:error', (err) => { // }) }) ``` When you are ready to remove the error page, you can call the [`clearError`](https://nuxt.com/docs/4.x/api/utils/clear-error) helper function, which takes an optional path to redirect to (for example, if you want to navigate to a 'safe' page). ::important Make sure to check before using anything dependent on Nuxt plugins, such as `$route` or `useRouter`, as if a plugin threw an error, then it won't be re-run until you clear the error. :: ::note Rendering an error page is an entirely separate page load, meaning any registered middleware will run again. You can use [`useError`](https://nuxt.com/docs/4.x/getting-started/error-handling#useerror) in middleware to check if an error is being handled. :: ::note If you are running on Node 16 and you set any cookies when rendering your error page, they will [overwrite cookies previously set](https://github.com/nuxt/nuxt/pull/20585){rel=""nofollow""}. We recommend using a newer version of Node as Node 16 reached end-of-life in September 2023. :: ## Error Utils ### `useError` ```ts [TS Signature] function useError (): Ref ``` This function will return the global Nuxt error that is being handled. ::read-more{to="https://nuxt.com/docs/4.x/api/composables/use-error"} Read more about `useError` composable. :: ### `createError` ```ts [TS Signature] function createError (err: string | { cause, data, message, name, stack, status, statusText, fatal }): Error ``` Create an error object with additional metadata. You can pass a string to be set as the error `message` or an object containing error properties. It is usable in both the Vue and Server portions of your app, and is meant to be thrown. If you throw an error created with `createError`: - on server-side, it will trigger a full-screen error page which you can clear with [`clearError`](https://nuxt.com/docs/4.x/getting-started/error-handling#clearerror). - on client-side, it will throw a non-fatal error for you to handle. If you need to trigger a full-screen error page, then you can do this by setting `fatal: true`. ```vue [pages/movies/[slug\\].vue] twoslash ``` ::tip The `statusText` property is intended for short, HTTP-compliant status texts (e.g., "Not Found"). It should only contain horizontal tabs, spaces, and visible ASCII characters (`[\t\u0020-\u007E]`). For any detailed descriptions, multi-line messages, or content with non-ASCII characters, you should always use the `message` property instead. :: ::read-more{to="https://nuxt.com/docs/4.x/api/utils/create-error"} Read more about `createError` util. :: ### `showError` ```ts [TS Signature] function showError (err: string | Error | { status, statusText }): Error ``` You can call this function at any point on client-side, or (on server side) directly within middleware, plugins or `setup()` functions. It will trigger a full-screen error page which you can clear with [`clearError`](https://nuxt.com/docs/4.x/getting-started/error-handling#clearerror). It is recommended instead to use `throw createError()`. ::read-more{to="https://nuxt.com/docs/4.x/api/utils/show-error"} Read more about `showError` util. :: ### `clearError` ```ts [TS Signature] function clearError (options?: { redirect?: string }): Promise ``` This function will clear the currently handled Nuxt error. It also takes an optional path to redirect to (for example, if you want to navigate to a 'safe' page). ::read-more{to="https://nuxt.com/docs/4.x/api/utils/clear-error"} Read more about `clearError` util. :: ## Render Error in Component Nuxt also provides a [``](https://nuxt.com/docs/4.x/api/components/nuxt-error-boundary) component that allows you to handle client-side errors within your app, without replacing your entire site with an error page. This component is responsible for handling errors that occur within its default slot. On client-side, it will prevent the error from bubbling up to the top level, and will render the `#error` slot instead. The `#error` slot will receive `error` as a prop. (If you set `error = null` it will trigger re-rendering the default slot; you'll need to ensure that the error is fully resolved first or the error slot will just be rendered a second time.) ::tip If you navigate to another route, the error will be cleared automatically. :: ```vue [app/pages/index.vue] ``` :link-example{to="https://nuxt.com/docs/4.x/examples/advanced/error-handling"} # Server :read-more{to="https://nuxt.com/docs/4.x/directory-structure/server"} ## Powered by Nitro ![Server engine](https://nuxt.com/assets/docs/getting-started/server.svg) Nuxt's server is [Nitro](https://github.com/nitrojs/nitro){rel=""nofollow""}. It was originally created for Nuxt but is now part of [UnJS](https://unjs.io){rel=""nofollow""} and open for other frameworks - and can even be used on its own. Using Nitro gives Nuxt superpowers: - Full control of the server-side part of your app - Universal deployment on any provider (many zero-config) - Hybrid rendering Nitro is internally using [h3](https://github.com/h3js/h3){rel=""nofollow""}, a minimal H(TTP) framework built for high performance and portability. :video-accordion{title="Watch a video from Alexander Lichter to understand the responsibilities of Nuxt and Nitro in your application" video-id="DkvgJa-X31k"} ## Server Endpoints & Middleware You can easily manage the server-only part of your Nuxt app, from API endpoints to middleware. Both endpoints and middleware can be defined like this: ```ts [server/api/test.ts] twoslash export default defineEventHandler(async (event) => { // ... Do whatever you want here }) ``` And you can directly return `text`, `json`, `html` or even a `stream`. Out-of-the-box, it supports **hot module replacement** and **auto-import** like the other parts of your Nuxt application. :read-more{to="https://nuxt.com/docs/4.x/directory-structure/server"} ## Universal Deployment Nitro offers the ability to deploy your Nuxt app anywhere, from a bare metal server to the edge network, with a start time of just a few milliseconds. That's fast! :read-more{to="https://nuxt.com/blog/nuxt-on-the-edge"} There are more than 15 presets to build your Nuxt app for different cloud providers and servers, including: - [Cloudflare Workers](https://workers.cloudflare.com){rel=""nofollow""} - [Netlify Functions](https://www.netlify.com/platform/core/functions/){rel=""nofollow""} - [Vercel Cloud](https://vercel.com/home){rel=""nofollow""} Or for other runtimes: ::card-group :::card --- icon: i-logos-deno target: _blank title: Deno to: https://deno.com --- ::: :::card --- icon: i-logos-bun target: _blank title: Bun to: https://bun.com --- ::: :: :read-more{to="https://nuxt.com/docs/4.x/getting-started/deployment"} ## Hybrid Rendering Nitro has a powerful feature called `routeRules` which allows you to define a set of rules to customize how each route of your Nuxt app is rendered (and more). ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ routeRules: { // Generated at build time for SEO purpose '/': { prerender: true }, // Cached for 1 hour '/api/*': { cache: { maxAge: 60 * 60 } }, // Redirection to avoid 404 '/old-page': { redirect: { to: '/new-page', statusCode: 302 }, }, // ... }, }) ``` ::read-more --- to: https://nuxt.com/docs/4.x/guide/concepts/rendering#hybrid-rendering --- Learn about all available route rules are available to customize the rendering mode of your routes. :: In addition, there are some route rules (for example, `ssr`, `appMiddleware`, and `noScripts`) that are Nuxt specific to change the behavior when rendering your pages to HTML. Some route rules (`appMiddleware`, `redirect` and `prerender`) also affect client-side behavior. Nitro is used to build the app for server side rendering, as well as pre-rendering. :read-more{to="https://nuxt.com/docs/4.x/guide/concepts/rendering"} # Layers One of the core features of Nuxt is the layers and extending support. You can extend a default Nuxt application to reuse components, utils, and configuration. The layers structure is almost identical to a standard Nuxt application which makes them easy to author and maintain. ## Use Cases - Share reusable configuration presets across projects using `nuxt.config` and `app.config` - Create a component library using [`app/components/`](https://nuxt.com/docs/4.x/directory-structure/app/components) directory - Create utility and composable library using [`app/composables/`](https://nuxt.com/docs/4.x/directory-structure/app/composables) and [`app/utils/`](https://nuxt.com/docs/4.x/directory-structure/app/utils) directories - Create Nuxt module presets - Share standard setup across projects - Create Nuxt themes - Enhance code organization by implementing a modular architecture and support Domain-Driven Design (DDD) pattern in large scale projects. ## Usage By default, any layers within your project in the `~~/layers` directory will be automatically registered as layers in your project. ::note Layer auto-registration was introduced in Nuxt v3.12.0. :: In addition, named layer aliases to the `srcDir` of each of these layers will automatically be created. For example, you will be able to access the `~~/layers/test` layer via `#layers/test`. ::note Named layer aliases were introduced in Nuxt v3.16.0. :: In addition, you can extend from a layer by adding the [extends](https://nuxt.com/docs/4.x/api/nuxt-config#extends) property to your [`nuxt.config`](https://nuxt.com/docs/4.x/directory-structure/nuxt-config) file. ```ts [nuxt.config.ts] export default defineNuxtConfig({ extends: [ // Extend from a local layer '../base', // Extend from an installed npm package '@my-themes/awesome', // Extend from a git repository 'github:my-themes/awesome#v1', ], }) ``` You can also pass an authentication token if you are extending from a private GitHub repository: ```ts [nuxt.config.ts] export default defineNuxtConfig({ extends: [ // per layer configuration ['github:my-themes/private-awesome', { auth: process.env.GITHUB_TOKEN }], ], }) ``` ::note If a branch is not specified, this will clone `main`. :: ::tip You can override a layer's alias by specifying it in the options next to the layer source. ```ts [nuxt.config.ts] export default defineNuxtConfig({ extends: [ [ 'github:my-themes/awesome', { meta: { name: 'my-awesome-theme', }, }, ], ], }) ``` :: Nuxt uses [unjs/c12](https://github.com/unjs/c12){rel=""nofollow""} and [unjs/giget](https://github.com/unjs/giget){rel=""nofollow""} for extending remote layers. Check the documentation for more information and all available options. ## Layer Priority When using multiple layers, it's important to understand the override order. Layers with **higher priority** override layers with lower priority when they define the same files or components. The priority order from highest to lowest is: 1. **Your project files** - always have the 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 Each - **`extends`** - Use for external dependencies (npm packages, remote repositories) or layers outside your project directory - **`~~/layers` directory** - Use for local layers that are part of your project ::tip If you need to control the order of auto-scanned layers, you can 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`. :: ### Example ```ts [nuxt.config.ts] export default defineNuxtConfig({ extends: [ // Local layer outside the project '../base', // NPM package '@my-themes/awesome', // Remote repository 'github:my-themes/awesome#v1', ], }) ``` If you also have `~~/layers/custom`, the priority order is: - Your project files (highest) - `~~/layers/custom` - `../base` - `@my-themes/awesome` - `github:my-themes/awesome#v1` (lowest) This means your project files will override any layer, and `~~/layers/custom` will override anything in `extends`. ::read-more{to="https://nuxt.com/docs/4.x/guide/going-further/layers"} Read more about layers in the **Layer Author Guide**. :: :video-accordion{title="Watch a video from Learn Vue about Nuxt Layers" video-id="lnFCM7c9f7I"} :video-accordion{title="Watch a video from Alexander Lichter about Nuxt Layers" video-id="fr5yo3aVkfA"} ## Examples ::card-group :::card --- icon: i-simple-icons-github target: _blank title: Content Wind to: https://github.com/Atinux/content-wind --- A lightweight Nuxt theme to build a Markdown driven website. Powered by Nuxt Content, TailwindCSS and Iconify. ::: :: # Prerendering Nuxt allows for select pages from your application to be rendered at build time. Nuxt will serve the prebuilt pages when requested instead of generating them on the fly. :read-more{title="Nuxt rendering modes" to="https://nuxt.com/docs/4.x/guide/concepts/rendering"} ## Crawl-based Pre-rendering Use the [`nuxt generate` command](https://nuxt.com/docs/4.x/api/commands/generate) to build and pre-render your application using the [Nitro](https://nuxt.com/docs/4.x/guide/concepts/server-engine) crawler. This command is similar to `nuxt build` with the `nitro.static` option set to `true`, or running `nuxt build --prerender`. This will build your site, stand up a nuxt instance, and, by default, prerender the root page `/` along with any of your site's pages it links to, any of your site's pages they link to, and so on. ::code-group{sync="pm"} ```bash [npm] npx nuxt generate ``` ```bash [yarn] yarn nuxt generate ``` ```bash [pnpm] pnpm nuxt generate ``` ```bash [bun] bun x nuxt generate ``` ```bash [deno] deno x nuxt generate ``` :: You can now deploy the `.output/public` directory to any static hosting service or preview it locally with `npx serve .output/public`. Working of the Nitro crawler: 1. Load the HTML of your application's root route (`/`), any non-dynamic pages in your `~/pages` directory, and any other routes in the `nitro.prerender.routes` array. 2. Save the HTML and `payload.json` to the `~/.output/public/` directory to be served statically. 3. Find all anchor tags (`
`) in the HTML to navigate to other routes. 4. Repeat steps 1-3 for each anchor tag found until there are no more anchor tags to crawl. This is important to understand since pages that are not linked to a discoverable page can't be pre-rendered automatically. ::read-more{to="https://nuxt.com/docs/4.x/api/commands/generate#nuxt-generate"} Read more about the `nuxt generate` command. :: ### Selective Pre-rendering You can manually specify routes that [Nitro](https://nuxt.com/docs/4.x/guide/concepts/server-engine) will fetch and pre-render during the build or ignore routes that you don't want to pre-render like `/dynamic` in the `nuxt.config` file: ```ts [nuxt.config.ts] twoslash // @errors: 2353 export default defineNuxtConfig({ nitro: { prerender: { routes: ['/user/1', '/user/2'], ignore: ['/dynamic'], }, }, }) ``` You can combine this with the `crawlLinks` option to pre-render a set of routes that the crawler can't discover like your `/sitemap.xml` or `/robots.txt`: ```ts [nuxt.config.ts] twoslash // @errors: 2353 export default defineNuxtConfig({ nitro: { prerender: { crawlLinks: true, routes: ['/sitemap.xml', '/robots.txt'], }, }, }) ``` Setting `nitro.prerender` to `true` is similar to `nitro.prerender.crawlLinks` to `true`. ::read-more{to="https://nitro.build/config#prerender"} Read more about pre-rendering in the Nitro documentation. :: Lastly, you can manually configure this using routeRules. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ routeRules: { // Set prerender to true to configure it to be prerendered '/rss.xml': { prerender: true }, // Set it to false to configure it to be skipped for prerendering '/this-DOES-NOT-get-prerendered': { prerender: false }, // Everything under /blog gets prerendered as long as it // is linked to from another page '/blog/**': { prerender: true }, }, }) ``` ::read-more{to="https://nitro.build/config#routerules"} Read more about Nitro's `routeRules` configuration. :: As a shorthand, you can also configure this in a page file using [`defineRouteRules`](https://nuxt.com/docs/4.x/api/utils/define-route-rules). ::read-more --- icon: i-lucide-star to: https://nuxt.com/docs/4.x/guide/going-further/experimental-features#inlinerouterules --- This feature is experimental and in order to use it you must enable the `experimental.inlineRouteRules` option in your `nuxt.config`. :: ```vue [app/pages/index.vue] ``` This will be translated to: ```ts [nuxt.config.ts] export default defineNuxtConfig({ routeRules: { '/': { prerender: true }, }, }) ``` ## Runtime Prerender Configuration ### `prerenderRoutes` You can use this at runtime within a [Nuxt context](https://nuxt.com/docs/4.x/guide/going-further/nuxt-app#the-nuxt-context) to add more routes for Nitro to prerender. ```vue [app/pages/index.vue] ``` :read-more{title="prerenderRoutes" to="https://nuxt.com/docs/4.x/api/utils/prerender-routes"} ### `prerender:routes` Nuxt hook This is called before prerendering for additional routes to be registered. ```ts [nuxt.config.ts] export default defineNuxtConfig({ hooks: { async 'prerender:routes' (ctx) { const { pages } = await fetch('https://api.some-cms.com/pages').then( res => res.json(), ) for (const page of pages) { ctx.routes.add(`/${page.name}`) } }, }, }) ``` ### `prerender:generate` Nitro hook This is called for each route during prerendering. You can use this for fine-grained handling of each route that gets prerendered. ```ts [nuxt.config.ts] export default defineNuxtConfig({ nitro: { hooks: { 'prerender:generate' (route) { if (route.route?.includes('private')) { route.skip = true } }, }, }, }) ``` # Deployment A Nuxt application can be deployed on a Node.js server, pre-rendered for static hosting, or deployed to serverless or edge (CDN) environments. ::tip If you are looking for a list of cloud providers that support Nuxt, see the [Hosting providers](https://nuxt.com/deploy) section. :: ## Node.js Server Discover the Node.js server preset with Nitro to deploy on any Node hosting. - **Default output format** if none is specified or auto-detected :br - Loads only the required chunks to render the request for optimal cold start timing :br - Useful for deploying Nuxt apps to any Node.js hosting ### Entry Point When running `nuxt build` with the Node server preset, the result will be an entry point that launches a ready-to-run Node server. ```bash [Terminal] node .output/server/index.mjs ``` This will launch your production Nuxt server that listens on port 3000 by default. It respects the following runtime environment variables: - `NITRO_PORT` or `PORT` (defaults to `3000`) - `NITRO_HOST` or `HOST` (defaults to `'0.0.0.0'`) - `NITRO_SSL_CERT` and `NITRO_SSL_KEY` - if both are present, this will launch the server in HTTPS mode. In the vast majority of cases, this should not be used other than for testing, and the Nitro server should be run behind a reverse proxy like nginx or Cloudflare which terminates SSL. ### PM2 [PM2](https://pm2.keymetrics.io/){rel=""nofollow""} (Process Manager 2) is a fast and easy solution for hosting your Nuxt application on your server or VM. To use `pm2`, use an `ecosystem.config.cjs`: ```ts [ecosystem.config.cjs] module.exports = { apps: [ { name: 'NuxtAppName', port: '3000', exec_mode: 'cluster', instances: 'max', script: './.output/server/index.mjs', }, ], } ``` ### Cluster Mode You can use `NITRO_PRESET=node_cluster` in order to leverage multi-process performance using Node.js [cluster](https://nodejs.org/dist/latest/docs/api/cluster.html){rel=""nofollow""} module. By default, the workload gets distributed to the workers with the round robin strategy. ### Learn More :read-more{title="the Nitro documentation for node-server preset" to="https://nitro.build/deploy/runtimes/node"} :video-accordion{title="Watch Daniel Roe's short video on the topic" video-id="0x1H6K5yOfs"} ## Static Hosting There are two ways to deploy a Nuxt application to any static hosting services: - Static site generation (SSG) with `ssr: true` pre-renders routes of your application at build time. (This is the default behavior when running `nuxt generate`.) It will also generate `/200.html` and `/404.html` single-page app fallback pages, which can render dynamic routes or 404 errors on the client (though you may need to configure this on your static host). - Alternatively, you can prerender your site with `ssr: false` (static single-page app). This will produce HTML pages with an empty `
` where your Vue app would normally be rendered. You will lose many SEO benefits of prerendering your site, so it is suggested instead to use [``](https://nuxt.com/docs/4.x/api/components/client-only) to wrap the portions of your site that cannot be server rendered (if any). :read-more{title="Nuxt prerendering" to="https://nuxt.com/docs/4.x/getting-started/prerendering"} ### Client-side Only Rendering If you don't want to pre-render your routes, another way of using static hosting is to set the `ssr` property to `false` in the `nuxt.config` file. The `nuxt generate` command will then output an `.output/public/index.html` entrypoint and JavaScript bundles like a classic client-side Vue.js application. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ ssr: false, }) ``` ## Hosting Providers Nuxt can be deployed to several cloud providers with a minimal amount of configuration: :read-more{to="https://nuxt.com/deploy"} ## Presets In addition to Node.js servers and static hosting services, a Nuxt project can be deployed with several well-tested presets and minimal amount of configuration. You can explicitly set the desired preset in the [`nuxt.config.ts`](https://nuxt.com/docs/4.x/directory-structure/nuxt-config) file: ```ts [nuxt.config.ts] twoslash // @errors: 2353 export default defineNuxtConfig({ nitro: { preset: 'node-server', }, }) ``` ... or use the `NITRO_PRESET` environment variable when running `nuxt build`: ```bash [Terminal] NITRO_PRESET=node-server nuxt build ``` 🔎 Check [the Nitro deployment](https://nitro.build/deploy){rel=""nofollow""} for all possible deployment presets and providers. ## CDN Proxy In most cases, Nuxt can work with third-party content that is not generated or created by Nuxt itself. But sometimes such content can cause problems, especially Cloudflare's "Minification and Security Options". Accordingly, you should make sure that the following options are unchecked / disabled in Cloudflare. Otherwise, unnecessary re-rendering or hydration errors could impact your production application. 1. Speed > Optimization > Content Optimization > Disable "Rocket Loader™" 2. Speed > Optimization > Image Optimization > Disable "Mirage" 3. Scrape Shield > Disable "Email Address Obfuscation" With these settings, you can be sure that Cloudflare won't inject scripts into your Nuxt application that may cause unwanted side effects. ::tip Their location on the Cloudflare dashboard sometimes changes so don't hesitate to look around. :: # Testing ::tip If you are a module author, you can find more specific information in the [Module Author's guide](https://nuxt.com/docs/4.x/guide/modules/testing). :: Nuxt offers first-class support for end-to-end and unit testing of your Nuxt application via `@nuxt/test-utils`, a library of test utilities and configuration that currently powers the [tests we use on Nuxt itself](https://github.com/nuxt/nuxt/tree/main/test){rel=""nofollow""} and tests throughout the module ecosystem. :video-accordion{title="Watch a video from Alexander Lichter about getting started with @nuxt/test-utils" video-id="yGzwk9xi9gU"} ## Installation In order to allow you to manage your other testing dependencies, `@nuxt/test-utils` ships with various optional peer dependencies. For example: - you can choose between `happy-dom` and `jsdom` for a runtime Nuxt environment - you can choose between `vitest`, `cucumber`, `jest` and `playwright` for end-to-end test runners - `playwright-core` is only required if you wish to use the built-in browser testing utilities (and are not using `@playwright/test` as your test runner) ::code-group{sync="pm"} ```bash [npm] npm i --save-dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core ``` ```bash [yarn] yarn add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core ``` ```bash [pnpm] pnpm add -D @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core ``` ```bash [bun] bun add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core ``` :: ## Unit Testing We currently ship an environment for unit testing code that needs a [Nuxt](https://nuxt.com){rel=""nofollow""} runtime environment. It currently *only has support for `vitest`* (although contribution to add other runtimes would be welcome). ### Setup 1. Add `@nuxt/test-utils/module` to your `nuxt.config` file (optional). It adds a Vitest integration to your Nuxt DevTools which supports running your unit tests in development. ```ts twoslash export default defineNuxtConfig({ modules: [ '@nuxt/test-utils/module', ], }) ``` 2. Create a `vitest.config.ts` with the following content: ```ts twoslash import { defineConfig } from 'vitest/config' import { defineVitestProject } from '@nuxt/test-utils/config' export default defineConfig({ test: { projects: [ { test: { name: 'unit', include: ['test/unit/*.{test,spec}.ts'], environment: 'node', }, }, { test: { name: 'e2e', include: ['test/e2e/*.{test,spec}.ts'], environment: 'node', }, }, await defineVitestProject({ test: { name: 'nuxt', include: ['test/nuxt/*.{test,spec}.ts'], environment: 'nuxt', }, }), ], }, }) ``` ::tip When importing `@nuxt/test-utils` in your vitest config, It is necessary to have `"type": "module"` specified in your `package.json` or rename your vitest config file appropriately. > i.e., `vitest.config.m{ts,js}`. :: ::tip It is possible to set environment variables for testing by using the `.env.test` file. :: ### Using a Nuxt Runtime Environment Using [Vitest projects](https://vitest.dev/guide/projects.html#test-projects){rel=""nofollow""}, you have fine-grained control over which tests run in which environment: - **Unit tests**: Place regular unit tests in `test/unit/` - these run in a Node environment for speed - **Nuxt tests**: Place tests that rely on the Nuxt runtime environment in `test/nuxt/` - these will run within a Nuxt runtime environment #### Alternative: Simple Setup If you prefer a simpler setup and want all tests to run in the Nuxt environment, you can use the basic configuration: ```ts twoslash import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { environment: 'nuxt', // you can optionally set Nuxt-specific environment options // environmentOptions: { // nuxt: { // rootDir: fileURLToPath(new URL('./playground', import.meta.url)), // domEnvironment: 'happy-dom', // 'happy-dom' (default) or 'jsdom' // overrides: { // // other Nuxt config you want to pass // } // } // } }, }) ``` If you're using the simple setup with `environment: 'nuxt'` by default, you can opt *out* of the [Nuxt environment](https://vitest.dev/guide/environment.html#test-environment){rel=""nofollow""} per test file as needed. ```ts twoslash // @vitest-environment node import { test } from 'vitest' test('my test', () => { // ... test without Nuxt environment! }) ``` ::warning This approach is not recommended as it creates a hybrid environment where Nuxt Vite plugins run but the Nuxt entry and `nuxtApp` are not initialized. This can lead to hard-to-debug errors. :: ### Organizing Your Tests With the project-based setup, you might organize your tests as follows: ```bash [Directory structure] test/ ├── e2e/ │ └── ssr.test.ts ├── nuxt/ │ ├── components.test.ts │ └── composables.test.ts ├── unit/ │ └── utils.test.ts ``` You can of course opt for any test structure, but keeping the Nuxt runtime environment separated from Nuxt end-to-end tests is important for test stability. #### TypeScript Support in Tests By default, test files in `test/nuxt/` and `tests/nuxt/` directories are included in the [Nuxt app TypeScript context](https://nuxt.com/docs/4.x/guide/concepts/typescript#how-nuxt-uses-project-references). That means they will recognise Nuxt aliases (like `~/`, `@/`, `#imports`) and TypeScript will be aware of auto-imports that work in your Nuxt app. ::tip This matches the recommended structure where only tests that need the Nuxt runtime environment are placed in these directories. Unit tests in other directories like `test/unit/` can be added manually if needed. :: ##### Adding other test directories If you have tests in other directories that you will be running in the Nuxt Vitest environment, you can include them in the Nuxt app TypeScript context by adding them to your configuration: ```ts [nuxt.config.ts] export default defineNuxtConfig({ typescript: { tsConfig: { include: [ // this path is relative to the generated .nuxt/tsconfig.json '../test/other-nuxt-context/**/*', ], }, }, }) ``` ::important Unit tests should not depend on Nuxt runtime features like auto-imports or composables. Only add TypeScript path alias support if your tests import from your source files (e.g., `~/utils/helpers`), not for Nuxt-specific features. :: #### Running Tests With the project setup, you can run different test suites: ```bash # Run all tests npx vitest # Run only unit tests npx vitest --project unit # Run only Nuxt tests npx vitest --project nuxt # Run tests in watch mode npx vitest --watch ``` ::warning When you run your tests within the Nuxt environment, they will be running in a [`happy-dom`](https://github.com/capricorn86/happy-dom){rel=""nofollow""} or [`jsdom`](https://github.com/jsdom/jsdom){rel=""nofollow""} environment. Before your tests run, a global Nuxt app will be initialized (including, for example, running any plugins or code you've defined in your `app.vue`). This means you should take particular care not to mutate the global state in your tests (or, if you need to, to reset it afterwards). :: ### 🎭 Built-In Mocks `@nuxt/test-utils` provides some built-in mocks for the DOM environment. #### `intersectionObserver` Default `true`, creates a dummy class without any functionality for the IntersectionObserver API #### `indexedDB` Default `false`, uses [`fake-indexeddb`](https://github.com/dumbmatter/fakeIndexedDB){rel=""nofollow""} to create a functional mock of the IndexedDB API These can be configured in the `environmentOptions` section of your `vitest.config.ts` file: ```ts twoslash import { defineVitestConfig } from '@nuxt/test-utils/config' export default defineVitestConfig({ test: { environmentOptions: { nuxt: { mock: { intersectionObserver: true, indexedDb: true, }, }, }, }, }) ``` ### 🛠️ Helpers `@nuxt/test-utils` provides a number of helpers to make testing Nuxt apps easier. #### `mountSuspended` `mountSuspended` allows you to mount any Vue component within the Nuxt environment, allowing async setup and access to injections from your Nuxt plugins. ::note Under the hood, `mountSuspended` wraps `mount` from `@vue/test-utils`, so you can check out [the Vue Test Utils documentation](https://test-utils.vuejs.org/guide/){rel=""nofollow""} for more on the options you can pass, and how to use this utility. :: For example: ```ts twoslash // @noErrors import { expect, it } from 'vitest' import type { Component } from 'vue' declare module '#components' { export const SomeComponent: Component } // ---cut--- // tests/components/SomeComponents.nuxt.spec.ts import { mountSuspended } from '@nuxt/test-utils/runtime' import { SomeComponent } from '#components' it('can mount some component', async () => { const component = await mountSuspended(SomeComponent) expect(component.text()).toMatchInlineSnapshot( '"This is an auto-imported component"', ) }) ``` ```ts twoslash // @noErrors import { expect, it } from 'vitest' // ---cut--- // tests/components/SomeComponents.nuxt.spec.ts import { mountSuspended } from '@nuxt/test-utils/runtime' import App from '~/app.vue' // tests/App.nuxt.spec.ts it('can also mount an app', async () => { const component = await mountSuspended(App, { route: '/test' }) expect(component.html()).toMatchInlineSnapshot(` "
This is an auto-imported component
I am a global component
/
Test link " `) }) ``` #### `renderSuspended` `renderSuspended` allows you to render any Vue component within the Nuxt environment using `@testing-library/vue`, allowing async setup and access to injections from your Nuxt plugins. This should be used together with utilities from Testing Library, e.g. `screen` and `fireEvent`. Install [@testing-library/vue](https://testing-library.com/docs/vue-testing-library/intro/){rel=""nofollow""} in your project to use these. Additionally, Testing Library also relies on testing globals for cleanup. You should turn these on in your [Vitest config](https://vitest.dev/config/globals){rel=""nofollow""}. The passed in component will be rendered inside a `
`. Examples: ```ts twoslash // @noErrors import { expect, it } from 'vitest' import type { Component } from 'vue' declare module '#components' { export const SomeComponent: Component } // ---cut--- // tests/components/SomeComponents.nuxt.spec.ts import { renderSuspended } from '@nuxt/test-utils/runtime' import { SomeComponent } from '#components' import { screen } from '@testing-library/vue' it('can render some component', async () => { await renderSuspended(SomeComponent) expect(screen.getByText('This is an auto-imported component')).toBeDefined() }) ``` ```ts twoslash // @noErrors import { expect, it } from 'vitest' // ---cut--- // tests/App.nuxt.spec.ts import { renderSuspended } from '@nuxt/test-utils/runtime' import App from '~/app.vue' it('can also render an app', async () => { const html = await renderSuspended(App, { route: '/test' }) expect(html).toMatchInlineSnapshot(` "
This is an auto-imported component
I am a global component
Index page
Test link
" `) }) ``` #### `mockNuxtImport` `mockNuxtImport` allows you to mock Nuxt's auto import functionality. For example, to mock `useStorage`, you can do so like this: ```ts twoslash import { mockNuxtImport } from '@nuxt/test-utils/runtime' mockNuxtImport('useStorage', () => { return () => { return { value: 'mocked storage' } } }) // your tests here ``` ::note `mockNuxtImport` can only be used once per mocked import per test file. It is actually a macro that gets transformed to `vi.mock` and `vi.mock` is hoisted, as described [in the Vitest docs](https://vitest.dev/api/vi#vi-mock){rel=""nofollow""}. :: If you need to mock a Nuxt import and provide different implementations between tests, you can do it by creating and exposing your mocks using [`vi.hoisted`](https://vitest.dev/api/vi#vi-hoisted){rel=""nofollow""}, and then use those mocks in `mockNuxtImport`. You then have access to the mocked imports, and can change the implementation between tests. Be careful to [restore mocks](https://vitest.dev/api/mock#mockrestore){rel=""nofollow""} before or after each test to undo mock state changes between runs. ```ts twoslash import { vi } from 'vitest' import { mockNuxtImport } from '@nuxt/test-utils/runtime' const { useStorageMock } = vi.hoisted(() => { return { useStorageMock: vi.fn(() => { return { value: 'mocked storage' } }), } }) mockNuxtImport('useStorage', () => { return useStorageMock }) // Then, inside a test useStorageMock.mockImplementation(() => { return { value: 'something else' } }) ``` #### `mockComponent` `mockComponent` allows you to mock Nuxt's component. The first argument can be the component name in PascalCase, or the relative path of the component. The second argument is a factory function that returns the mocked component. For example, to mock `MyComponent`, you can: ```ts twoslash import { mockComponent } from '@nuxt/test-utils/runtime' mockComponent('MyComponent', { props: { value: String, }, setup (props) { // ... }, }) // relative path or alias also works mockComponent('~/components/my-component.vue', () => { // or a factory function return defineComponent({ setup (props) { // ... }, }) }) // or you can use SFC for redirecting to a mock component mockComponent('MyComponent', () => import('./MockComponent.vue')) // your tests here ``` > **Note**: You can't reference local variables in the factory function since they are hoisted. If you need to access Vue APIs or other variables, you need to import them in your factory function. ```ts twoslash import { mockComponent } from '@nuxt/test-utils/runtime' mockComponent('MyComponent', async () => { const { ref, h } = await import('vue') return defineComponent({ setup (props) { const counter = ref(0) return () => h('div', null, counter.value) }, }) }) ``` #### `registerEndpoint` `registerEndpoint` allows you create Nitro endpoint that returns mocked data. It can come in handy if you want to test a component that makes requests to API to display some data. The first argument is the endpoint name (e.g. `/test/`). The second argument is a factory function that returns the mocked data. For example, to mock `/test/` endpoint, you can do: ```ts twoslash import { registerEndpoint } from '@nuxt/test-utils/runtime' registerEndpoint('/test/', () => ({ test: 'test-field', })) ``` By default, your request will be made using the `GET` method. You may use another method by setting an object as the second argument instead of a function. ```ts twoslash import { registerEndpoint } from '@nuxt/test-utils/runtime' registerEndpoint('/test/', { method: 'POST', handler: () => ({ test: 'test-field' }), }) ``` > **Note**: If your requests in a component go to an external API, you can use `baseURL` and then make it empty using [Nuxt Environment Override Config](https://nuxt.com/docs/4.x/getting-started/configuration#environment-overrides) (`$test`) so all your requests will go to Nitro server. #### Conflict with End-To-End Testing `@nuxt/test-utils/runtime` and `@nuxt/test-utils/e2e` need to run in different testing environments and so can't be used in the same file. If you would like to use both the end-to-end and unit testing functionality of `@nuxt/test-utils`, you can split your tests into separate files. You then either specify a test environment per-file with the special `// @vitest-environment nuxt` comment, or name your runtime unit test files with the `.nuxt.spec.ts` extension. `app.nuxt.spec.ts` ```ts twoslash import { mockNuxtImport } from '@nuxt/test-utils/runtime' mockNuxtImport('useStorage', () => { return () => { return { value: 'mocked storage' } } }) ``` `app.e2e.spec.ts` ```ts twoslash import { $fetch, setup } from '@nuxt/test-utils/e2e' await setup({ setupTimeout: 10000, }) // ... ``` ### Using `@vue/test-utils` If you prefer to use `@vue/test-utils` on its own for unit testing in Nuxt, and you are only testing components which do not rely on Nuxt composables, auto-imports or context, you can follow these steps to set it up. 1. Install the needed dependencies ::code-group{sync="pm"} ```bash [npm] npm i --save-dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue ``` ```bash [yarn] yarn add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue ``` ```bash [pnpm] pnpm add -D vitest @vue/test-utils happy-dom @vitejs/plugin-vue ``` ```bash [bun] bun add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue ``` :: 2. Create a `vitest.config.ts` with the following content: ```ts import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { environment: 'happy-dom', }, }) ``` 3. Add a new command for test in your `package.json` ```json "scripts": { "build": "nuxt build", "dev": "nuxt dev", ... "test": "vitest" }, ``` 4. Create a simple `` component `app/components/HelloWorld.vue` with the following content: ```vue ``` 5. Create a simple unit test for this newly created component `~/components/HelloWorld.spec.ts` ```ts twoslash import { describe, expect, it } from 'vitest' import { mount } from '@vue/test-utils' import HelloWorld from './HelloWorld.vue' describe('HelloWorld', () => { it('component renders Hello world properly', () => { const wrapper = mount(HelloWorld) expect(wrapper.text()).toContain('Hello world') }) }) ``` 6. Run vitest command ::code-group{sync="pm"} ```bash [npm] npm run test ``` ```bash [yarn] yarn test ``` ```bash [pnpm] pnpm run test ``` ```bash [bun] bun run test ``` :: Congratulations, you're all set to start unit testing with `@vue/test-utils` in Nuxt! Happy testing! ## End-To-End Testing For end-to-end testing, we support [Vitest](https://github.com/vitest-dev/vitest){rel=""nofollow""}, [Jest](https://jestjs.io){rel=""nofollow""}, [Cucumber](https://cucumber.io/){rel=""nofollow""} and [Playwright](https://playwright.dev/){rel=""nofollow""} as test runners. ### Setup In each `describe` block where you are taking advantage of the `@nuxt/test-utils/e2e` helper methods, you will need to set up the test context before beginning. ```ts [test/my-test.spec.ts] twoslash import { describe, test } from 'vitest' import { $fetch, setup } from '@nuxt/test-utils/e2e' describe('My test', async () => { await setup({ // test context options }) test('my test', () => { // ... }) }) ``` Behind the scenes, `setup` performs a number of tasks in `beforeAll`, `beforeEach`, `afterEach` and `afterAll` to set up the Nuxt test environment correctly. Please use the options below for the `setup` method. #### Nuxt Config - `rootDir`: Path to a directory with a Nuxt app to be put under test. - Type: `string` - Default: `'.'` - `configFile`: Name of the configuration file. - Type: `string` - Default: `'nuxt.config'` #### Timings - `setupTimeout`: The amount of time (in milliseconds) to allow for `setupTest` to complete its work (which could include building or generating files for a Nuxt application, depending on the options that are passed). - Type: `number` - Default: `120000` or `240000` on windows - `teardownTimeout`: The amount of time (in milliseconds) to allow tearing down the test environment, such as closing the browser. - Type: `number` - Default: `30000` #### Features - `build`: Whether to run a separate build step. - Type: `boolean` - Default: `true` (`false` if `browser` or `server` is disabled, or if a `host` is provided) - `server`: Whether to launch a server to respond to requests in the test suite. - Type: `boolean` - Default: `true` (`false` if a `host` is provided) - `port`: If provided, set the launched test server port to the value. - Type: `number | undefined` - Default: `undefined` - `host`: If provided, a URL to use as the test target instead of building and running a new server. Useful for running "real" end-to-end tests against a deployed version of your application, or against an already running local server (which may provide a significant reduction in test execution timings). See the [target host end-to-end example below](https://nuxt.com/docs/4.x/getting-started/testing#target-host-end-to-end-example). - Type: `string` - Default: `undefined` - `browser`: Under the hood, Nuxt test utils uses [`playwright`](https://playwright.dev){rel=""nofollow""} to carry out browser testing. If this option is set, a browser will be launched and can be controlled in the subsequent test suite. - Type: `boolean` - Default: `false` - `browserOptions` - Type: `object`with the following properties - `type`: The type of browser to launch - either `chromium`, `firefox` or `webkit` - `launch`: `object` of options that will be passed to playwright when launching the browser. See [full API reference](https://playwright.dev/docs/api/class-browsertype#browser-type-launch){rel=""nofollow""}. - `runner`: Specify the runner for the test suite. Currently, [Vitest](https://vitest.dev){rel=""nofollow""} is recommended. - Type: `'vitest' | 'jest' | 'cucumber'` - Default: `'vitest'` ##### Target `host` end-to-end example A common use-case for end-to-end testing is running the tests against a deployed application running in the same environment typically used for Production. For local development or automated deploy pipelines, testing against a separate local server can be more efficient and is typically faster than allowing the test framework to rebuild between tests. To utilize a separate target host for end-to-end tests, simply provide the `host` property of the `setup` function with the desired URL. ```ts import { createPage, setup } from '@nuxt/test-utils/e2e' import { describe, expect, it } from 'vitest' describe('login page', async () => { await setup({ host: 'http://localhost:8787', }) it('displays the email and password fields', async () => { const page = await createPage('/login') expect(await page.getByTestId('email').isVisible()).toBe(true) expect(await page.getByTestId('password').isVisible()).toBe(true) }) }) ``` ### APIs #### `$fetch(url)` Get the HTML of a server-rendered page. ```ts twoslash import { $fetch } from '@nuxt/test-utils/e2e' const html = await $fetch('/') ``` #### `fetch(url)` Get the response of a server-rendered page. ```ts twoslash import { fetch } from '@nuxt/test-utils/e2e' const res = await fetch('/') const { body, headers } = res ``` #### `url(path)` Get the full URL for a given page (including the port the test server is running on.) ```ts twoslash import { url } from '@nuxt/test-utils/e2e' const pageUrl = url('/page') // 'http://localhost:6840/page' ``` ### Testing in a Browser We provide built-in support using Playwright within `@nuxt/test-utils`, either programmatically or via the Playwright test runner. #### `createPage(url)` Within `vitest`, `jest` or `cucumber`, you can create a configured Playwright browser instance with `createPage`, and (optionally) point it at a path from the running server. You can find out more about the API methods available from [in the Playwright documentation](https://playwright.dev/docs/api/class-page){rel=""nofollow""}. ```ts twoslash import { createPage } from '@nuxt/test-utils/e2e' const page = await createPage('/page') // you can access all the Playwright APIs from the `page` variable ``` #### Testing with Playwright Test Runner We also provide first-class support for testing Nuxt within [the Playwright test runner](https://playwright.dev/docs/intro){rel=""nofollow""}. ::code-group{sync="pm"} ```bash [npm] npm i --save-dev @playwright/test @nuxt/test-utils ``` ```bash [yarn] yarn add --dev @playwright/test @nuxt/test-utils ``` ```bash [pnpm] pnpm add -D @playwright/test @nuxt/test-utils ``` ```bash [bun] bun add --dev @playwright/test @nuxt/test-utils ``` ```bash [deno] deno add --dev npm:@playwright/test npm:@nuxt/test-utils ``` :: You can provide global Nuxt configuration, with the same configuration details as the `setup()` function mentioned earlier in this section. ```ts [playwright.config.ts] import { fileURLToPath } from 'node:url' import { defineConfig, devices } from '@playwright/test' import type { ConfigOptions } from '@nuxt/test-utils/playwright' export default defineConfig({ use: { nuxt: { rootDir: fileURLToPath(new URL('.', import.meta.url)), }, }, // ... }) ``` :read-more{target="_blank" title="See full example config" to="https://github.com/nuxt/test-utils/blob/main/examples/app-playwright/playwright.config.ts"} Your test file should then use `expect` and `test` directly from `@nuxt/test-utils/playwright`: ```ts [tests/example.test.ts] import { expect, test } from '@nuxt/test-utils/playwright' test('test', async ({ page, goto }) => { await goto('/', { waitUntil: 'hydration' }) await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!') }) ``` You can alternatively configure your Nuxt server directly within your test file: ```ts [tests/example.test.ts] import { expect, test } from '@nuxt/test-utils/playwright' test.use({ nuxt: { rootDir: fileURLToPath(new URL('..', import.meta.url)), }, }) test('test', async ({ page, goto }) => { await goto('/', { waitUntil: 'hydration' }) await expect(page.getByRole('heading')).toHaveText('Welcome to Playwright!') }) ``` # Upgrade Guide ## Upgrading Nuxt ### Latest release To upgrade Nuxt to the [latest release](https://github.com/nuxt/nuxt/releases){rel=""nofollow""}, use the `nuxt upgrade` command. ::code-group{sync="pm"} ```bash [npm] npx nuxt upgrade ``` ```bash [yarn] yarn nuxt upgrade ``` ```bash [pnpm] pnpm nuxt upgrade ``` ```bash [bun] bun x nuxt upgrade ``` ```bash [deno] deno x nuxt upgrade ``` :: ### Nightly Release Channel To use the latest Nuxt build and test features before their release, read about the [nightly release channel](https://nuxt.com/docs/4.x/guide/going-further/nightly-release-channel) guide. ## Testing Nuxt 5 Nuxt 5 is **currently in development**. Until the release, it is possible to test many of Nuxt 5's breaking changes from Nuxt version 4.2+. ### Opting in to Nuxt 5 First, upgrade Nuxt to the [latest release](https://github.com/nuxt/nuxt/releases){rel=""nofollow""}. Then you can set your `future.compatibilityVersion` to match Nuxt 5 behavior: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ future: { compatibilityVersion: 5, }, }) ``` When you set your `future.compatibilityVersion` to `5`, defaults throughout your Nuxt configuration will change to opt in to Nuxt v5 behavior, including: - **Vite Environment API**: Automatically enables the new [Vite Environment API](https://nuxt.com/docs/4.x/getting-started/upgrade#migration-to-vite-environment-api) for improved build configuration - Other Nuxt 5 improvements and changes as they become available ::note This section is subject to change until the final release, so please check back here regularly if you are testing Nuxt 5 using `future.compatibilityVersion: 5`. :: Breaking or significant changes will be noted below along with migration steps for backward/forward compatibility. ### Migration to Vite Environment API 🚦 **Impact Level**: Medium #### What Changed Nuxt 5 migrates to Vite 6's new [Environment API](https://vite.dev/guide/api-environment){rel=""nofollow""}, which formalizes the concept of environments and provides better control over configuration per environment. Previously, Nuxt used separate client and server Vite configurations. Now, Nuxt uses a shared Vite configuration with environment-specific plugins that use the `applyToEnvironment()` method to target specific environments. ::tip You can test this feature early by setting `future.compatibilityVersion: 5` (see [Testing Nuxt 5](https://nuxt.com/docs/4.x/getting-started/upgrade#testing-nuxt-5)) or by enabling it explicitly with `experimental.viteEnvironmentApi: true`. :: **Key changes:** 1. **Deprecated environment-specific `extendViteConfig()`**: The `server` and `client` options in `extendViteConfig()` are deprecated and will show warnings when used. 2. **Changed plugin registration**: Vite plugins registered with `addVitePlugin()` and only targeting one environment (by passing `server: false` or `client: false`) will not have their `config` or `configResolved` hooks called. 3. **Shared configuration**: The `vite:extendConfig` and `vite:configResolved` hooks now work with a shared configuration rather than separate client/server configs. #### Reasons for Change The Vite Environment API provides: - Better consistency between development and production builds - More granular control over environment-specific configuration - Improved performance and plugin architecture - Support for custom environments beyond just client and server #### Migration Steps ##### 1. Migrate to use Vite plugins We would recommend you use a Vite plugin instead of `extendViteConfig`, `vite:configResolved` and `vite:extendConfig`. ```ts // Before extendViteConfig((config) => { config.optimizeDeps.include.push('my-package') }, { server: false }) nuxt.hook('vite:extendConfig' /* or vite:configResolved */, (config, { isClient }) => { if (isClient) { config.optimizeDeps.include.push('my-package') } }) // After addVitePlugin(() => ({ name: 'my-plugin', config (config) { // you can set global vite configuration here }, configResolved (config) { // you can access the fully resolved vite configuration here }, configEnvironment (name, config) { // you can set environment-specific vite configuration here if (name === 'client') { config.optimizeDeps ||= {} config.optimizeDeps.include ||= [] config.optimizeDeps.include.push('my-package') } }, applyToEnvironment (environment) { return environment.name === 'client' }, })) ``` ##### 2. Migrate Vite plugins to use environments Instead of using `addVitePlugin` with `server: false` or `client: false`, you can instead use the new `applyToEnvironment` hook within your plugin. ```ts // Before addVitePlugin(() => ({ name: 'my-plugin', config (config) { config.optimizeDeps.include.push('my-package') }, }), { client: false }) // After addVitePlugin(() => ({ name: 'my-plugin', config (config) { // you can set global vite configuration here }, configResolved (config) { // you can access the fully resolved vite configuration here }, configEnvironment (name, config) { // you can set environment-specific vite configuration here if (name === 'client') { config.optimizeDeps ||= {} config.optimizeDeps.include ||= [] config.optimizeDeps.include.push('my-package') } }, applyToEnvironment (environment) { return environment.name === 'client' }, })) ``` ::read-more{target="_blank" to="https://vite.dev/guide/api-environment"} Learn more about Vite's Environment API :: ## Migrating to Nuxt 4 Nuxt 4 includes significant improvements and changes. This guide will help you migrate your existing Nuxt 3 application to Nuxt 4. First, upgrade to Nuxt 4: ::code-group{sync="pm"} ```bash [npm] npm install nuxt@^4.0.0 ``` ```bash [yarn] yarn add nuxt@^4.0.0 ``` ```bash [pnpm] pnpm add nuxt@^4.0.0 ``` ```bash [bun] bun add nuxt@^4.0.0 ``` ```bash [deno] deno add npm:nuxt@^4.0.0 ``` :: After upgrading, most Nuxt 4 behaviors are now the default. However, some features can still be configured if you need to maintain backward compatibility during your migration. The following sections detail the key changes and migrations needed when upgrading to Nuxt 4. Breaking or significant changes are documented below along with migration steps and available configuration options. ### Migrating Using Codemods To facilitate the upgrade process, we have collaborated with the [Codemod](https://github.com/codemod/codemod){rel=""nofollow""} team to automate many migration steps with some open-source codemods. ::note If you encounter any issues, please report them to the Codemod team with `npx codemod feedback` 🙏 :: For a complete list of Nuxt 4 codemods, detailed information on each, their source, and various ways to run them, visit the [Codemod Registry](https://app.codemod.com/registry){rel=""nofollow""}. You can run all the codemods mentioned in this guide using the following `codemod` recipe: ::code-group ```bash [npm] # Using pinned version due to https://github.com/codemod/codemod/issues/1710 npx codemod@0.18.7 nuxt/4/migration-recipe ``` ```bash [yarn] # Using pinned version due to https://github.com/codemod/codemod/issues/1710 yarn dlx codemod@0.18.7 nuxt/4/migration-recipe ``` ```bash [pnpm] # Using pinned version due to https://github.com/codemod/codemod/issues/1710 pnpm dlx codemod@0.18.7 nuxt/4/migration-recipe ``` ```bash [bun] # Using pinned version due to https://github.com/codemod/codemod/issues/1710 bun x codemod@0.18.7 nuxt/4/migration-recipe ``` ```bash [deno] # Using pinned version due to https://github.com/codemod/codemod/issues/1710 deno x codemod@0.18.7 nuxt/4/migration-recipe ``` :: This command will execute all codemods in sequence, with the option to deselect any that you do not wish to run. Each codemod is also listed below alongside its respective change and can be executed independently. ### New Directory Structure 🚦 **Impact Level**: Significant Nuxt now defaults to a new directory structure, with backwards compatibility (so if Nuxt detects you are using the old structure, such as with a top-level `app/pages/` directory, this new structure will not apply). 👉 [See full RFC](https://github.com/nuxt/nuxt/issues/26444){rel=""nofollow""} #### What Changed - the new Nuxt default `srcDir` is `app/` by default, and most things are resolved from there. - `serverDir` now defaults to `/server` rather than `/server` - `layers/`, `modules/` and `public/` are resolved relative to `` by default - if using [Nuxt Content v2.13+](https://github.com/nuxt/content/pull/2649){rel=""nofollow""}, `content/` is resolved relative to `` - a new `dir.app` is added, which is the directory we look for `router.options.ts` and `spa-loading-template.html` - this defaults to `/` An example v4 folder structure. ```sh .output/ .nuxt/ app/ assets/ components/ composables/ layouts/ middleware/ pages/ plugins/ utils/ app.config.ts app.vue router.options.ts content/ layers/ modules/ node_modules/ public/ shared/ server/ api/ middleware/ plugins/ routes/ utils/ nuxt.config.ts ``` ::note With this new structure, the `~` alias now points to the `app/` directory by default (your `srcDir`). This means `~/components` resolves to `app/components/`, `~/pages` to `app/pages/`, etc. :: 👉 For more details, see the [PR implementing this change](https://github.com/nuxt/nuxt/pull/27029){rel=""nofollow""}. #### Reasons for Change 1. **Performance** - placing all your code in the root of your repo causes issues with `.git/` and `node_modules/` folders being scanned/included by FS watchers which can significantly delay startup on non-Mac OSes. 2. **IDE type-safety** - `server/` and the rest of your app are running in two entirely different contexts with different global imports available, and making sure `server/` isn't *inside* the same folder as the rest of your app is a big first step to ensuring you get good auto-completes in your IDE. :video-accordion{platform="vimeo" title="Watch a video from Vue School on the new directory structure" video-id="1031028378"} #### Migration Steps 1. Create a new directory called `app/`. 2. Move your `assets/`, `components/`, `composables/`, `app/layouts/`, `app/middleware/`, `app/pages/`, `app/plugins/` and `utils/` folders under it, as well as `app.vue`, `error.vue`, `app.config.ts`. If you have an `app/router-options.ts` or `app/spa-loading-template.html`, these paths remain the same. 3. Make sure your `nuxt.config.ts`, `content/`, `layers/`, `modules/`, `public/` and `server/` folders remain outside the `app/` folder, in the root of your project. 4. Remember to update any third-party configuration files to work with the new directory structure, such as your `tailwindcss` or `eslint` configuration (if required - `@nuxtjs/tailwindcss` should automatically configure `tailwindcss` correctly). ::tip You can automate this migration by running `npx codemod@latest nuxt/4/file-structure` :: However, migration is *not required*. If you wish to keep your current folder structure, Nuxt should auto-detect it. (If it does not, please raise an issue.) The one exception is that if you *already* have a custom `srcDir`. In this case, you should be aware that your `modules/`, `public/` and `server/` folders will be resolved from your `rootDir` rather than from your custom `srcDir`. You can override this by configuring `dir.modules`, `dir.public` and `serverDir` if you need to. You can also force a v3 folder structure with the following configuration: ```ts [nuxt.config.ts] export default defineNuxtConfig({ // This reverts the new srcDir default from `app` back to your root directory srcDir: '.', // This specifies the directory prefix for `router.options.ts` and `spa-loading-template.html` dir: { app: 'app', }, }) ``` ### Singleton Data Fetching Layer 🚦 **Impact Level**: Moderate #### What Changed Nuxt's data fetching system (`useAsyncData` and `useFetch`) has been significantly reorganized for better performance and consistency: 1. **Shared refs for the same key**: All calls to `useAsyncData` or `useFetch` with the same key now share the same `data`, `error` and `status` refs. This means that it is important that all calls with an explicit key must not have conflicting `deep`, `transform`, `pick`, `getCachedData` or `default` options. 2. **More control over `getCachedData`**: The `getCachedData` function is now called every time data is fetched, even if this is caused by a watcher or calling `refreshNuxtData`. (Previously, new data was always fetched and this function was not called in these cases.) To allow more control over when to use cached data and when to refetch, the function now receives a context object with the cause of the request. 3. **Reactive key support**: You can now use computed refs, plain refs or getter functions as keys, which enables automatic data refetching (and stores data separately). 4. **Data cleanup**: When the last component using data fetched with `useAsyncData` is unmounted, Nuxt will remove that data to avoid ever-growing memory usage. #### Reasons for Change These changes have been made to improve memory usage and increase consistency with loading states across calls of `useAsyncData`. #### Migration Steps 1. **Check for inconsistent options**: Review any components using the same key with different options or fetch functions. ```ts // This will now trigger a warning const { data: users1 } = useAsyncData('users', () => $fetch('/api/users'), { deep: false }) const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { deep: true }) ``` It may be beneficial to extract any calls to `useAsyncData` that share an explicit key (and have custom options) into their own composable: ```ts [app/composables/useUserData.ts] export function useUserData (userId: string) { return useAsyncData( `user-${userId}`, () => fetchUser(userId), { deep: true, transform: user => ({ ...user, lastAccessed: new Date() }), }, ) } ``` 2. **Update `getCachedData` implementations**: ```diff useAsyncData('key', fetchFunction, { - getCachedData: (key, nuxtApp) => { - return cachedData[key] - } + getCachedData: (key, nuxtApp, ctx) => { + // ctx.cause - can be 'initial' | 'refresh:hook' | 'refresh:manual' | 'watch' + + // Example: Don't use cache on manual refresh + if (ctx.cause === 'refresh:manual') return undefined + + return cachedData[key] + } }) ``` Alternatively, for now, you can disable this behaviour with: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { granularCachedData: false, purgeCachedData: false, }, }) ``` ### Corrected Module Loading Order in Layers 🚦 **Impact Level**: Minimal #### What Changed The order in which modules are loaded when using [Nuxt layers](https://nuxt.com/docs/4.x/guide/going-further/layers) has been corrected. Previously, modules from the project root were loaded before modules from extended layers, which was the reverse of the expected behavior. Now modules are loaded in the correct order: 1. **Layer modules first** (in extend order - deeper layers first) 2. **Project modules last** (highest priority) This affects both: - Modules defined in the `modules` array in `nuxt.config.ts` - Auto-discovered modules from the `modules/` directory #### Reasons for Change This change ensures that: - Extended layers have lower priority than the consuming project - Module execution order matches the intuitive layer inheritance pattern - Module configuration and hooks work as expected in multi-layer setups #### Migration Steps **Most projects will not need changes**, as this corrects the loading order to match expected behavior. However, if your project was relying on the previous incorrect order, you may need to: 1. **Review module dependencies**: Check if any modules depend on specific loading order 2. **Adjust module configuration**: If modules were configured to work around the incorrect order 3. **Test thoroughly**: Ensure all functionality works as expected with the corrected order Example of the new correct order: ```ts // Layer: my-layer/nuxt.config.ts export default defineNuxtConfig({ modules: ['layer-module-1', 'layer-module-2'], }) // Project: nuxt.config.ts export default defineNuxtConfig({ extends: ['./my-layer'], modules: ['project-module-1', 'project-module-2'], }) // Loading order (corrected): // 1. layer-module-1 // 2. layer-module-2 // 3. project-module-1 (can override layer modules) // 4. project-module-2 (can override layer modules) ``` If you encounter issues with module order dependencies due to needing to register a hook, consider using the [`modules:done` hook](https://nuxt.com/docs/4.x/guide/modules/recipes-advanced) for modules that need to call a hook. This is run after all other modules have been loaded, which means it is safe to use. 👉 See [PR #31507](https://github.com/nuxt/nuxt/pull/31507){rel=""nofollow""} and [issue #25719](https://github.com/nuxt/nuxt/issues/25719){rel=""nofollow""} for more details. ### Deduplication of Route Metadata 🚦 **Impact Level**: Minimal #### What Changed It's possible to set some route metadata using `definePageMeta`, such as the `name`, `path`, and so on. Previously these were available both on the route and on route metadata (for example, `route.name` and `route.meta.name`). Now, they are only accessible on the route object. #### Reasons for Change This is a result of enabling `experimental.scanPageMeta` by default, and is a performance optimization. #### Migration Steps The migration should be straightforward: ```diff const route = useRoute() - console.log(route.meta.name) + console.log(route.name) ``` ### Normalized Component Names 🚦 **Impact Level**: Moderate Vue will now generate component names that match the Nuxt pattern for component naming. #### What Changed By default, if you haven't set it manually, Vue will assign a component name that matches the filename of the component. ```bash [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 `` with it, or identify it in the Vue DevTools, you would need to use this name. But in order to auto-import it, you would need to use `SomeFolderMyComponent`. With this change, these two values will match, and Vue will generate a component name that matches the Nuxt pattern for component naming. #### Migration Steps Ensure that you use the updated name in any tests which use `findComponent` from `@vue/test-utils` and in any `` which depends on the name of your component. Alternatively, for now, you can disable this behaviour with: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { normalizeComponentNames: false, }, }) ``` ### Unhead v2 🚦 **Impact Level**: Minimal #### What Changed [Unhead](https://unhead.unjs.io/){rel=""nofollow""}, used to generate `` tags, has been updated to version 2. While mostly compatible it includes several breaking changes for lower-level APIs. - Removed props: `vmid`, `hid`, `children`, `body`. - Promise input no longer supported. - Tags are now sorted using Capo.js by default. #### Migration Steps The above changes should have minimal impact on your app. If you have issues you should verify: - You're not using any of the removed props. ```diff useHead({ meta: [{ name: 'description', // meta tags don't need a vmid, or a key - vmid: 'description' - hid: 'description' }] }) ``` - If you're using [Template Params](https://unhead.unjs.io/docs/head/guides/plugins/template-params){rel=""nofollow""} or [Alias Tag Sorting](https://unhead.unjs.io/docs/head/guides/plugins/alias-sorting){rel=""nofollow""}, you will need to explicitly opt in to these features now. ```ts import { AliasSortingPlugin, TemplateParamsPlugin } from '@unhead/vue/plugins' export default defineNuxtPlugin({ setup () { const unhead = injectHead() unhead.use(TemplateParamsPlugin) unhead.use(AliasSortingPlugin) }, }) ``` While not required it's recommended to update any imports from `@unhead/vue` to `#imports` or `nuxt/app`. ```diff -import { useHead } from '@unhead/vue' +import { useHead } from '#imports' ``` If you still have issues you may revert to the v1 behavior by enabling the `head.legacy` config. ```ts export default defineNuxtConfig({ unhead: { legacy: true, }, }) ``` ### New DOM Location for SPA Loading Screen 🚦 **Impact Level**: Minimal #### What Changed When rendering a client-only page (with `ssr: false`), we optionally render a loading screen (from `~/app/spa-loading-template.html` - note that this has also changed to `~/spa-loading-template.html` in Nuxt 4), within the Nuxt app root: ```html
``` Now, we default to rendering the template alongside the Nuxt app root: ```html
``` #### Reasons for Change This allows the spa loading template to remain in the DOM until the Vue app suspense resolves, preventing a flash of white. #### Migration Steps If you were targeting the spa loading template with CSS or `document.queryElement` you will need to update your selectors. For this purpose you can use the new `app.spaLoaderTag` and `app.spaLoaderAttrs` configuration options. Alternatively, you can revert to the previous behaviour with: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { spaLoadingTemplateLocation: 'within', }, }) ``` ### Parsed `error.data` 🚦 **Impact Level**: Minimal It was possible to throw an error with a `data` property, but this was not parsed. Now, it is parsed and made available in the `error` object. Although a fix, this is technically a breaking change if you were relying on the previous behavior and parsing it manually. #### Migration Steps Update your custom `error.vue` to remove any additional parsing of `error.data`: ```diff ``` ### More Granular Inline Styles 🚦 **Impact Level**: Moderate Nuxt will now only inline styles for Vue components, not global CSS. #### What Changed Previously, Nuxt would inline all CSS, including global styles, and remove `` elements to separate CSS files. Now, Nuxt will only do this for Vue components (which previously produced separate chunks of CSS). We think this is a better balance of reducing separate network requests (just as before, there will not be separate requests for individual `.css` files per-page or per-component on the initial load), as well as allowing caching of a single global CSS file and reducing the document download size of the initial request. #### Migration Steps This feature is fully configurable and you can revert to the previous behavior by setting `inlineStyles: true` to inline global CSS as well as per-component CSS. ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ features: { inlineStyles: true, }, }) ``` ### Scan Page Meta After Resolution 🚦 **Impact Level**: Minimal #### What Changed We now scan page metadata (defined in `definePageMeta`) *after* calling the `pages:extend` hook rather than before. #### Reasons for Change This was to allow scanning metadata for pages that users wanted to add in `pages:extend`. We still offer an opportunity to change or override page metadata in a new `pages:resolved` hook. #### Migration Steps If you want to override page metadata, do that in `pages:resolved` rather than in `pages:extend`. ```diff export default defineNuxtConfig({ hooks: { - 'pages:extend'(pages) { + 'pages:resolved'(pages) { const myPage = pages.find(page => page.path === '/') myPage.meta ||= {} myPage.meta.layout = 'overridden-layout' } } }) ``` Alternatively, you can revert to the previous behaviour with: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { scanPageMeta: true, }, }) ``` ### Shared Prerender Data 🚦 **Impact Level**: Medium #### What Changed We enabled a previously experimental feature to share data from `useAsyncData` and `useFetch` calls, across different pages. See [original PR](https://github.com/nuxt/nuxt/pull/24894){rel=""nofollow""}. #### Reasons for Change This feature automatically shares payload *data* between pages that are prerendered. This can result in a significant performance improvement when prerendering sites that use `useAsyncData` or `useFetch` and fetch the same data in different pages. For example, if your site requires a `useFetch` call for every page (for example, to get navigation data for a menu, or site settings from a CMS), this data would only be fetched once when prerendering the first page that uses it, and then cached for use when prerendering other pages. #### Migration Steps Make sure that any unique key of your data is always resolvable to the same data. For example, if you are using `useAsyncData` to fetch data related to a particular page, you should provide a key that uniquely matches that data. (`useFetch` should do this automatically for you.) ```ts [app/pages/test/[slug\\].vue] // This would be unsafe in a dynamic page (e.g. `[slug].vue`) because the route slug makes a difference // to the data fetched, but Nuxt can't know that because it's not reflected in the key. const route = useRoute() const { data } = await useAsyncData(async () => { return await $fetch(`/api/my-page/${route.params.slug}`) }) // Instead, you should use a key that uniquely identifies the data fetched. const { data } = await useAsyncData(route.params.slug, async () => { return await $fetch(`/api/my-page/${route.params.slug}`) }) ``` Alternatively, you can disable this feature with: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { sharedPrerenderData: false, }, }) ``` ### Default `data` and `error` values in `useAsyncData` and `useFetch` 🚦 **Impact Level**: Minimal #### What Changed `data` and `error` objects returned from `useAsyncData` will now default to `undefined`. #### Reasons for Change Previously `data` was initialized to `null` but reset in `clearNuxtData` to `undefined`. `error` was initialized to `null`. This change is to bring greater consistency. #### Migration Steps If you were checking if `data.value` or `error.value` were `null`, you can update these checks to check for `undefined` instead. ::tip You can automate this step by running `npx codemod@latest nuxt/4/default-data-error-value` :: ### Removal of deprecated `boolean` values for `dedupe` option when calling `refresh` in `useAsyncData` and `useFetch` 🚦 **Impact Level**: Minimal #### What Changed Previously it was possible to pass `dedupe: boolean` to `refresh`. These were aliases of `cancel` (`true`) and `defer` (`false`). ```ts [app/app.vue] twoslash // @errors: 2322 const { refresh } = await useAsyncData(() => Promise.resolve({ message: 'Hello, Nuxt!' })) async function refreshData () { await refresh({ dedupe: true }) } ``` #### Reasons for Change These aliases were removed, for greater clarity. The issue came up when adding `dedupe` as an option to `useAsyncData`, and we removed the boolean values as they ended up being *opposites*. `refresh({ dedupe: false })` meant **do not *cancel* existing requests in favour of this new one**. But passing `dedupe: true` within the options of `useAsyncData` means **do not make any new requests if there is an existing pending request.** (See [PR](https://github.com/nuxt/nuxt/pull/24564#pullrequestreview-1764584361){rel=""nofollow""}.) #### Migration Steps The migration should be straightforward: ```diff const { refresh } = await useAsyncData(async () => ({ message: 'Hello, Nuxt 3!' })) async function refreshData () { - await refresh({ dedupe: true }) + await refresh({ dedupe: 'cancel' }) - await refresh({ dedupe: false }) + await refresh({ dedupe: 'defer' }) } ``` ::tip You can automate this step by running `npx codemod@latest nuxt/4/deprecated-dedupe-value` :: ### Respect defaults when clearing `data` in `useAsyncData` and `useFetch` 🚦 **Impact Level**: Minimal #### What Changed If you provide a custom `default` value for `useAsyncData`, this will now be used when calling `clear` or `clearNuxtData` and it will be reset to its default value rather than simply unset. #### Reasons for Change Often users set an appropriately empty value, such as an empty array, to avoid the need to check for `null`/`undefined` when iterating over it. This should be respected when resetting/clearing the data. ### Alignment of `pending` value in `useAsyncData` and `useFetch` 🚦 **Impact Level**: Medium The `pending` object returned from `useAsyncData`, `useFetch`, `useLazyAsyncData` and `useLazyFetch` is now a computed property that is `true` only when `status` is also pending. #### What Changed Now, when `immediate: false` is passed, `pending` will be `false` until the first request is made. This is a change from the previous behavior, where `pending` was always `true` until the first request was made. #### Reasons for Change This aligns the meaning of `pending` with the `status` property, which is also `pending` when the request is in progress. #### Migration Steps If you rely on the `pending` property, ensure that your logic accounts for the new behavior where `pending` will only be `true` when the status is also pending. ```diff ``` Alternatively, you can temporarily revert to the previous behavior with: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { pendingWhenIdle: true, }, }) ``` ### Key Change Behavior in `useAsyncData` and `useFetch` 🚦 **Impact Level**: Medium #### What Changed When using reactive keys in `useAsyncData` or `useFetch`, Nuxt automatically refetches data when the key changes. When `immediate: false` is set, `useAsyncData` will only fetch data when the key changes if the data has already been fetched once. Previously, `useFetch` had slightly different behavior. It would always fetch data when the key changed. Now, `useFetch` and `useAsyncData` behave consistently - by only fetch data when the key changes if the data has already been fetched once. #### Reasons for Change This ensures consistent behavior between `useAsyncData` and `useFetch`, and prevents unexpected fetches. If you have set `immediate: false`, then you must call `refresh` or `execute` or data will never be fetched in `useFetch` or `useAsyncData`. #### Migration Steps This change should generally improve the expected behavior, but if you were expecting changing the key or options of a non-immediate `useFetch`, you now will need to trigger it manually the first time. ```diff const id = ref('123') const { data, execute } = await useFetch('/api/test', { query: { id }, immediate: false ) + watch(id, () => execute(), { once: true }) ``` To opt out of this behavior: ```ts // Or globally in your Nuxt config export default defineNuxtConfig({ experimental: { alwaysRunFetchOnKeyChange: true, }, }) ``` ### Shallow Data Reactivity in `useAsyncData` and `useFetch` 🚦 **Impact Level**: Minimal The `data` object returned from `useAsyncData`, `useFetch`, `useLazyAsyncData` and `useLazyFetch` is now a `shallowRef` rather than a `ref`. #### What Changed When new data is fetched, anything depending on `data` will still be reactive because the entire object is replaced. But if your code changes a property *within* that data structure, this will not trigger any reactivity in your app. #### Reasons for Change This brings a **significant** performance improvement for deeply nested objects and arrays because Vue does not need to watch every single property/array for modification. In most cases, `data` should also be immutable. #### Migration Steps In most cases, no migration steps are required, but if you rely on the reactivity of the data object then you have two options: 1. You can granularly opt in to deep reactivity on a per-composable basis: ```diff - const { data } = useFetch('/api/test') + const { data } = useFetch('/api/test', { deep: true }) ``` 2. You can change the default behavior on a project-wide basis (not recommended): ```ts \[nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { defaults: { useAsyncData: { deep: true, }, }, }, }) ``` ::tip If you need to, you can automate this step by running `npx codemod@latest nuxt/4/shallow-function-reactivity` :: ### Absolute Watch Paths in `builder:watch` 🚦 **Impact Level**: Minimal #### What Changed The Nuxt `builder:watch` hook now emits a path which is absolute rather than relative to your project `srcDir`. #### Reasons for Change This allows us to support watching paths which are outside your `srcDir`, and offers better support for layers and other more complex patterns. #### Migration Steps We have already proactively migrated the public Nuxt modules which we are aware use this hook. See [issue #25339](https://github.com/nuxt/nuxt/issues/25339){rel=""nofollow""}. However, if you are a module author using the `builder:watch` hook and wishing to remain backwards/forwards compatible, you can use the following code to ensure that your code works the same in both Nuxt v3 and Nuxt v4: ```diff + import { relative, resolve } from 'node:fs' // ... nuxt.hook('builder:watch', async (event, path) => { + path = relative(nuxt.options.srcDir, resolve(nuxt.options.srcDir, path)) // ... }) ``` ::tip You can automate this step by running `npx codemod@latest nuxt/4/absolute-watch-path` :: ### Removal of `window.__NUXT__` object #### What Changed We are removing the global `window.__NUXT__` object after the app finishes hydration. #### Reasons for Change This opens the way to multi-app patterns ([#21635](https://github.com/nuxt/nuxt/issues/21635){rel=""nofollow""}) and enables us to focus on a single way to access Nuxt app data - `useNuxtApp()`. #### Migration Steps The data is still available, but can be accessed with `useNuxtApp().payload`: ```diff - console.log(window.__NUXT__) + console.log(useNuxtApp().payload) ``` ### Directory index scanning 🚦 **Impact Level**: Medium #### What Changed Child folders in your `app/middleware/` folder are also scanned for `index` files and these are now also registered as middleware in your project. #### Reasons for Change Nuxt scans a number of folders automatically, including `app/middleware/` and `app/plugins/`. Child folders in your `app/plugins/` folder are scanned for `index` files and we wanted to make this behavior consistent between scanned directories. #### Migration Steps Probably no migration is necessary but if you wish to revert to previous behavior you can add a hook to filter out these middleware: ```ts export default defineNuxtConfig({ hooks: { 'app:resolve' (app) { app.middleware = app.middleware.filter(mw => !/\/index\.[^/]+$/.test(mw.path)) }, }, }) ``` ### Template Compilation Changes 🚦 **Impact Level**: Minimal #### What Changed Previously, Nuxt used `lodash/template` to compile templates located on the file system using the `.ejs` file format/syntax. In addition, we provided some template utilities (`serialize`, `importName`, `importSources`) which could be used for code-generation within these templates, which are now being removed. #### Reasons for Change In Nuxt v3 we moved to a 'virtual' syntax with a `getContents()` function which is much more flexible and performant. In addition, `lodash/template` has had a succession of security issues. These do not really apply to Nuxt projects because it is being used at build-time, not runtime, and by trusted code. However, they still appear in security audits. Moreover, `lodash` is a hefty dependency and is unused by most projects. Finally, providing code serialization functions directly within Nuxt is not ideal. Instead, we maintain projects like [unjs/knitwork](https://github.com/unjs/knitwork){rel=""nofollow""} which can be dependencies of your project, and where security issues can be reported/resolved directly without requiring an upgrade of Nuxt itself. #### Migration Steps We have raised PRs to update modules using EJS syntax, but if you need to do this yourself, you have three backwards/forwards-compatible alternatives: - Moving your string interpolation logic directly into `getContents()`. - Using a custom function to handle the replacement, such as in {rel=""nofollow""}. - Use `es-toolkit/compat` (a drop-in replacement for lodash template), as a dependency of *your* project rather than Nuxt: ```diff + import { readFileSync } from 'node:fs' + import { template } from 'es-toolkit/compat' // ... addTemplate({ fileName: 'appinsights-vue.js' options: { /* some options */ }, - src: resolver.resolve('./runtime/plugin.ejs'), + getContents({ options }) { + const contents = readFileSync(resolver.resolve('./runtime/plugin.ejs'), 'utf-8') + return template(contents)({ options }) + }, }) ``` Finally, if you are using the template utilities (`serialize`, `importName`, `importSources`), you can replace them as follows with utilities from `knitwork`: ```ts import { genDynamicImport, genImport, genSafeVariableName } from 'knitwork' const serialize = (data: any) => JSON.stringify(data, null, 2).replace(/"\{(.+)\}"(?=,?$)/gm, r => JSON.parse(r).replace(/^\{(.*)\}$/, '$1')) const importSources = (sources: string | string[], { lazy = false } = {}) => { return toArray(sources).map((src) => { if (lazy) { return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}` } return genImport(src, genSafeVariableName(src)) }).join('\n') } const importName = genSafeVariableName ``` ::tip You can automate this step by running `npx codemod@latest nuxt/4/template-compilation-changes` :: ### Default TypeScript Configuration Changes 🚦 **Impact Level**: Minimal #### What Changed `compilerOptions.noUncheckedIndexedAccess` is now `true` instead of `false`. #### Reasons for Change This change is a follow up to a prior [3.12 config update](https://github.com/nuxt/nuxt/pull/27485){rel=""nofollow""} where we improved our defaults, mostly adhering to [TotalTypeScript's recommendations](https://www.totaltypescript.com/tsconfig-cheat-sheet){rel=""nofollow""}. #### Migration Steps There are two approaches: 1. Run a typecheck on your app and fix any new errors (recommended). 2. Override the new default in your `nuxt.config.ts`: ```ts export default defineNuxtConfig({ typescript: { tsConfig: { compilerOptions: { noUncheckedIndexedAccess: false, }, }, }, }) ``` ### TypeScript Configuration Splitting 🚦 **Impact Level**: Minimal #### What Changed Nuxt now generates separate TypeScript configurations for different contexts to provide better type-checking experiences: 1. **New TypeScript configuration files**: Nuxt now generates additional TypeScript configurations: - `.nuxt/tsconfig.app.json` - For your app code (Vue components, composables, etc.) - `.nuxt/tsconfig.server.json` - For your server-side code (Nitro/server directory) - `.nuxt/tsconfig.node.json` - For your build-time code (modules, `nuxt.config.ts`, etc.) - `.nuxt/tsconfig.shared.json` - For code shared between app and server contexts (like types and non-environment specific utilities) - `.nuxt/tsconfig.json` - Legacy configuration for backward compatibility 2. **Backward compatibility**: Existing projects that extend `.nuxt/tsconfig.json` will continue to work as before. 3. **Opt-in project references**: New projects or those wanting better type checking can adopt TypeScript's project references feature. 4. **Context-specific type checking**: Each context now has appropriate compiler options and includes/excludes for its specific environment. 5. **New `typescript.nodeTsConfig` option**: You can now customize the TypeScript configuration for Node.js build-time code. #### Reasons for Change This change provides several benefits: 1. **Better type safety**: Each context (app, server, build-time) gets appropriate type checking with context-specific globals and APIs. 2. **Improved IDE experience**: Better IntelliSense and error reporting for different parts of your codebase. 3. **Cleaner separation**: Server code won't incorrectly suggest client-side APIs and vice versa. 4. **Performance**: TypeScript can more efficiently check code with properly scoped configurations. For example, auto-imports are not available in your `nuxt.config.ts` (but previously this was not flagged by TypeScript). And while IDEs recognized the separate context hinted by `tsconfig.json` in your `server/` directory, this was not reflected in type-checking (requiring a separate step). #### Migration Steps **No migration is required** - existing projects will continue to work as before. However, to take advantage of improved type checking, you can opt in to the new project references approach: 1. **Update your root `tsconfig.json`** to use project references: ::note If your `tsconfig.json` currently has an `"extends": "./.nuxt/tsconfig.json"` line, **remove it** before adding the references. Project references and extends are mutually exclusive. :: ```json { // Remove "extends": "./.nuxt/tsconfig.json" if present "files": [], "references": [ { "path": "./.nuxt/tsconfig.app.json" }, { "path": "./.nuxt/tsconfig.server.json" }, { "path": "./.nuxt/tsconfig.shared.json" }, { "path": "./.nuxt/tsconfig.node.json" } ] } ``` 2. **Remove any manual server `tsconfig.json`** files (like `server/tsconfig.json`) that extended `.nuxt/tsconfig.server.json`. 3. **Update your type checking scripts** to use the build flag for project references: ```diff - "typecheck": "nuxt prepare && vue-tsc --noEmit" + "typecheck": "nuxt prepare && vue-tsc -b --noEmit" ``` 4. **Move all type augmentations into their appropriate context**: - If you are augmenting types for the app context, move the files to the `app/` directory. - If you are augmenting types for the server context, move the files to the `server/` directory. - If you are augmenting types that are **shared between the app and server**, move the files to the `shared/` directory. ::warning Augmenting types from outside the `app/`, `server/`, or `shared/` directories will not work with the new project references setup. :: 5. **Configure TypeScript options** if needed: ```ts export default defineNuxtConfig({ typescript: { // customize tsconfig.app.json tsConfig: { // ... }, // customize tsconfig.shared.json sharedTsConfig: { // ... }, // customize tsconfig.node.json nodeTsConfig: { // ... }, }, nitro: { typescript: { // customize tsconfig.server.json tsConfig: { // ... }, }, }, }) ``` 6. **Update any CI/build scripts** that run TypeScript checking to ensure they use the new project references approach. The new configuration provides better type safety and IntelliSense for projects that opt in, while maintaining full backward compatibility for existing setups. ### Removal of Experimental Features 🚦 **Impact Level**: Minimal #### What Changed Four experimental features are no longer configurable in Nuxt 4: - `experimental.treeshakeClientOnly` will be `true` (default since v3.0) - `experimental.configSchema` will be `true` (default since v3.3) - `experimental.polyfillVueUseHead` will be `false` (default since v3.4) - `experimental.respectNoSSRHeader` will be `false` (default since v3.4) - `vite.devBundler` is no longer configurable - it will use `vite-node` by default #### Reasons for Change These options have been set to their current values for some time and we do not have a reason to believe that they need to remain configurable. #### Migration Steps - `polyfillVueUseHead` is implementable in user-land with [this plugin](https://github.com/nuxt/nuxt/blob/f209158352b09d1986aa320e29ff36353b91c358/packages/nuxt/src/head/runtime/plugins/vueuse-head-polyfill.ts#L10-L11){rel=""nofollow""} - `respectNoSSRHeader`is implementable in user-land with [server middleware](https://github.com/nuxt/nuxt/blob/c660b39447f0d5b8790c0826092638d321cd6821/packages/nuxt/src/core/runtime/nitro/no-ssr.ts#L8-L9){rel=""nofollow""} ### Removal of Top-Level `generate` Configuration 🚦 **Impact Level**: Minimal #### What Changed The top-level `generate` configuration option is no longer available in Nuxt 4. This includes all of its properties: - `generate.exclude` - for excluding routes from prerendering - `generate.routes` - for specifying routes to prerender #### Reasons for Change The top level `generate` configuration was a holdover from Nuxt 2. We've supported `nitro.prerender` for a while now, and it is the preferred way to configure prerendering in Nuxt 3+. #### Migration Steps Replace `generate` configuration with the corresponding `nitro.prerender` options: ```diff export default defineNuxtConfig({ - generate: { - exclude: ['/admin', '/private'], - routes: ['/sitemap.xml', '/robots.txt'] - } + nitro: { + prerender: { + ignore: ['/admin', '/private'], + routes: ['/sitemap.xml', '/robots.txt'] + } + } }) ``` ::read-more{to="https://nitro.build/config#prerender"} Read more about Nitro's prerender configuration options. :: ## Nuxt 2 vs. Nuxt 3+ In the table below, there is a quick comparison between 3 versions of Nuxt: | Feature / Version | Nuxt 2 | Nuxt Bridge | Nuxt 3+ | | ----------------------- | ---------- | ----------- | ---------- | | Vue | 2 | 2 | 3 | | Stability | 😊 Stable | 😊 Stable | 😊 Stable | | Performance | 🏎 Fast | ✈️ Faster | 🚀 Fastest | | Nitro Engine | ❌ | ✅ | ✅ | | ESM support | 🌙 Partial | 👍 Better | ✅ | | TypeScript | ☑️ Opt-in | 🚧 Partial | ✅ | | Composition API | ❌ | 🚧 Partial | ✅ | | Options API | ✅ | ✅ | ✅ | | Components Auto Import | ✅ | ✅ | ✅ | | ` ``` ::important If you are using `resolveComponent` to handle dynamic components, make sure not to insert anything but the name of the component, which must be a literal string and not be or contain a variable. The string is statically analyzed at the compilation step. :: :video-accordion{title="Watch Daniel Roe's short video about resolveComponent()" video-id="4kq8E5IUM2U"} Alternatively, though not recommended, you can register all your components globally, which will create async chunks for all your components and make them available throughout your application. ```diff export default defineNuxtConfig({ components: { + global: true, + dirs: ['~/components'] }, }) ``` You can also selectively register some components globally by placing them in a `~/components/global` directory, or by using a `.global.vue` suffix in the filename. As noted above, each global component is rendered in a separate chunk, so be careful not to overuse this feature. ::note The `global` option can also be set per component directory. :: ## Dynamic Imports To dynamically import a component (also known as lazy-loading a component) all you need to do is add the `Lazy` prefix to the component's name. This is particularly useful if the component is not always needed. By using the `Lazy` prefix you can delay loading the component code until the right moment, which can be helpful for optimizing your JavaScript bundle size. ```vue [app/pages/index.vue] ``` ## Delayed (or Lazy) Hydration Lazy components are great for controlling the chunk sizes in your app, but they don't always enhance runtime performance, as they still load eagerly unless conditionally rendered. In real-world applications, some pages may include a lot of content and a lot of components, and most of the time not all of them need to be interactive as soon as the page is loaded. Having them all load eagerly can negatively impact performance. In order to optimize your app, you may want to delay the hydration of some components until they're visible, or until the browser is done with more important tasks. Nuxt supports this using lazy (or delayed) hydration, allowing you to control when components become interactive. ### Hydration Strategies Nuxt provides a range of built-in hydration strategies. Only one strategy can be used per lazy component. ::note Any prop change on a lazily hydrated component will trigger hydration immediately. (e.g., changing a prop on a component with `hydrate-never` will cause it to hydrate) :: ::warning Currently Nuxt's built-in lazy hydration only works in single-file components (SFCs), and requires you to define the prop in the template (rather than spreading an object of props via `v-bind`). It also does not work with direct imports from `#components`. :: #### `hydrate-on-visible` Hydrates the component when it becomes visible in the viewport. ```vue [app/pages/index.vue] ``` ::read-more --- title: IntersectionObserver options to: https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver --- Read more about the options for `hydrate-on-visible`. :: ::note Under the hood, this uses Vue's built-in [`hydrateOnVisible` strategy](https://vuejs.org/guide/components/async#hydrate-on-visible){rel=""nofollow""}. :: #### `hydrate-on-idle` Hydrates the component when the browser is idle. This is suitable if you need the component to load as soon as possible, but not block the critical rendering path. You can also pass a number which serves as a max timeout. ```vue [app/pages/index.vue] ``` ::note Under the hood, this uses Vue's built-in [`hydrateOnIdle` strategy](https://vuejs.org/guide/components/async#hydrate-on-idle){rel=""nofollow""}. :: #### `hydrate-on-interaction` Hydrates the component after a specified interaction (e.g., click, mouseover). ```vue [app/pages/index.vue] ``` If you do not pass an event or list of events, it defaults to hydrating on `pointerenter`, `click` and `focus`. ::note Under the hood, this uses Vue's built-in [`hydrateOnInteraction` strategy](https://vuejs.org/guide/components/async#hydrate-on-interaction){rel=""nofollow""}. :: #### `hydrate-on-media-query` Hydrates the component when the window matches a media query. ```vue [app/pages/index.vue] ``` ::note Under the hood, this uses Vue's built-in [`hydrateOnMediaQuery` strategy](https://vuejs.org/guide/components/async#hydrate-on-media-query){rel=""nofollow""}. :: #### `hydrate-after` Hydrates the component after a specified delay (in milliseconds). ```vue [app/pages/index.vue] ``` #### `hydrate-when` Hydrates the component based on a boolean condition. ```vue [app/pages/index.vue] ``` #### `hydrate-never` Never hydrates the component. ```vue [app/pages/index.vue] ``` ### Listening to Hydration Events All delayed hydration components emit a `@hydrated` event when they are hydrated. ```vue [app/pages/index.vue] ``` ### Caveats and Best Practices Delayed hydration can offer performance benefits, but it's essential to use it correctly: 1. **Prioritize In-Viewport Content:** Avoid delayed hydration for critical, above-the-fold content. It's best suited for content that isn't immediately needed. 2. **Conditional Rendering:** When using `v-if="false"` on a lazy component, you might not need delayed hydration. You can just use a normal lazy component. 3. **Shared State:** Be mindful of shared state (`v-model`) across multiple components. Updating the model in one component can trigger hydration in all components bound to that model. 4. **Use Each Strategy's Intended Use Case:** Each strategy is optimized for a specific purpose. - `hydrate-when` is best for components that might not always need to be hydrated. - `hydrate-after` is for components that can wait a specific amount of time. - `hydrate-on-idle` is for components that can be hydrated when the browser is idle. 5. **Avoid `hydrate-never` on interactive components:** If a component requires user interaction, it should not be set to never hydrate. ## Direct Imports You can also explicitly import components from `#components` if you want or need to bypass Nuxt's auto-importing functionality. ```vue [app/pages/index.vue] ``` ## Custom Directories By default, only the `~/components` directory is scanned. If you want to add other directories, or change how the components are scanned within a subfolder of this directory, you can add additional directories to the configuration: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ components: [ // ~/calendar-module/components/event/Update.vue => { path: '~/calendar-module/components' }, // ~/user-module/components/account/UserDeleteDialog.vue => { path: '~/user-module/components', pathPrefix: false }, // ~/components/special-components/Btn.vue => { path: '~/components/special-components', prefix: 'Special' }, // It's important that this comes last if you have overrides you wish to apply // to sub-directories of `~/components`. // // ~/components/Btn.vue => // ~/components/base/Btn.vue => '~/components', ], }) ``` ::note Any nested directories need to be added first as they are scanned in order. :: ## npm Packages If you want to auto-import components from an npm package, you can use [`addComponent`](https://nuxt.com/docs/4.x/api/kit/components#addcomponent) in a [local module](https://nuxt.com/docs/4.x/directory-structure/modules) to register them. ::code-group ```ts [~/modules/register-component.ts] twoslash import { addComponent, defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ setup () { // import { MyComponent as MyAutoImportedComponent } from 'my-npm-package' addComponent({ name: 'MyAutoImportedComponent', export: 'MyComponent', filePath: 'my-npm-package', }) }, }) ``` ```vue [app/app.vue] ``` :: ## Component Extensions By default, any file with an extension specified in the [extensions key of `nuxt.config.ts`](https://nuxt.com/docs/4.x/api/nuxt-config#extensions) is treated as a component. If you need to restrict the file extensions that should be registered as components, you can use the extended form of the components directory declaration and its `extensions` key: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ components: [ { path: '~/components', extensions: ['.vue'], // [!code ++] }, ], }) ``` ## Client Components If a component is meant to be rendered only client-side, you can add the `.client` suffix to your component. ```bash [Directory Structure] | components/ --| Comments.client.vue ``` ```vue [app/pages/example.vue] ``` ::note This feature only works with Nuxt auto-imports and `#components` imports. Explicitly importing these components from their real paths does not convert them into client-only components. :: ::important `.client` components are rendered only after being mounted. To access the rendered template using `onMounted()`, add `await nextTick()` in the callback of the `onMounted()` hook. :: ::read-more{to="https://nuxt.com/docs/4.x/api/components/client-only"} You can also achieve a similar result with the `` component. :: ## Server Components Server components allow server-rendering individual components within your client-side apps. It's possible to use server components within Nuxt, even if you are generating a static site. That makes it possible to build complex sites that mix dynamic components, server-rendered HTML and even static chunks of markup. Server components can either be used on their own or paired with a [client component](https://nuxt.com/docs/4.x/directory-structure/app/components#paired-with-a-client-component). :video-accordion{title="Watch Learn Vue video about Nuxt Server Components" video-id="u1yyXe86xJM"} ::tip --- icon: i-lucide-newspaper target: _blank to: https://roe.dev/blog/nuxt-server-components --- Read Daniel Roe's guide to Nuxt Server Components. :: ### Standalone server components Standalone server components will always be rendered on the server, also known as Islands components. When their props update, this will result in a network request that will update the rendered HTML in-place. Server components are currently experimental and in order to use them, you need to enable the 'component islands' feature in your nuxt.config: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ experimental: { componentIslands: true, }, }) ``` Now you can register server-only components with the `.server` suffix and use them anywhere in your application automatically. ```bash [Directory Structure] -| components/ ---| HighlightedMarkdown.server.vue ``` ```vue [app/pages/example.vue] ``` Server-only components use [``](https://nuxt.com/docs/4.x/api/components/nuxt-island) under the hood, meaning that `lazy` prop and `#fallback` slot are both passed down to it. ::warning Server components (and islands) must have a single root element. (HTML comments are considered elements as well.) :: ::warning Props are passed to server components via URL query parameters, and are therefore limited by the possible length of a URL, so be careful not to pass enormous amounts of data to server components via props. :: ::warning Be careful when nesting islands within other islands as each island adds some extra overhead. :: ::warning Most features for server-only components and island components, such as slots and client components, are only available for single file components. :: #### Client components within server components ::note This feature needs `experimental.componentIslands.selectiveClient` within your configuration to be true. :: You can partially hydrate a component by setting a `nuxt-client` attribute on the component you wish to be loaded client-side. ```vue [app/components/ServerWithClient.vue] ``` ::note This only works within a server component. Slots for client components are working only with `experimental.componentIsland.selectiveClient` set to `'deep'` and since they are rendered server-side, they are not interactive once client-side. :: #### Server Component Context When rendering a server-only or island component, `` makes a fetch request which comes back with a `NuxtIslandResponse`. (This is an internal request if rendered on the server, or a request that you can see in the network tab if it's rendering on client-side navigation.) This means: - A new Vue app will be created server-side to create the `NuxtIslandResponse`. - A new 'island context' will be created while rendering the component. - You can't access the 'island context' from the rest of your app and you can't access the context of the rest of your app from the island component. In other words, the server component or island is *isolated* from the rest of your app. - Your plugins will run again when rendering the island, unless they have `env: { islands: false }` set (which you can do in an object-syntax plugin). ::important Route middleware does not run when rendering island components. Middleware is a routing concept that applies to pages, not components, and is not designed to control component rendering. :: Within an island component, you can access its island context through `nuxtApp.ssrContext.islandContext`. Note that while island components are still marked as experimental, the format of this context may change. ::note Slots can be interactive and are wrapped within a `
` with `display: contents;` :: ### Paired with a Client component In this case, the `.server` + `.client` components are two 'halves' of a component and can be used in advanced use cases for separate implementations of a component on server and client side. ```bash [Directory Structure] -| components/ ---| Comments.client.vue ---| Comments.server.vue ``` ```vue [app/pages/example.vue] ``` ## Built-In Nuxt Components There are a number of components that Nuxt provides, including `` and ``. You can read more about them in the API documentation. :read-more{to="https://nuxt.com/docs/4.x/api"} ## Library Authors Making Vue component libraries with automatic tree-shaking and component registration is super easy. ✨ You can use the [`addComponentsDir`](https://nuxt.com/docs/4.x/api/kit/components#addcomponentsdir) method provided from the `@nuxt/kit` to register your components directory in your Nuxt module. Imagine a directory structure like this: ```bash [Directory Structure] -| node_modules/ ---| awesome-ui/ -----| components/ -------| Alert.vue -------| Button.vue -----| nuxt.ts -| pages/ ---| index.vue -| nuxt.config.ts ``` Then in `awesome-ui/nuxt.ts` you can use the `addComponentsDir` hook: ```ts twoslash import { addComponentsDir, createResolver, defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ setup () { const resolver = createResolver(import.meta.url) // Add ./components dir to the list addComponentsDir({ path: resolver.resolve('./components'), prefix: 'awesome', }) }, }) ``` That's it! Now in your project, you can import your UI library as a Nuxt module in your `nuxt.config` file: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ modules: ['awesome-ui/nuxt'], }) ``` ... and directly use the module components (prefixed with `awesome-`) in our `app/pages/index.vue`: ```vue ``` It will automatically import the components only if used and also support HMR when updating your components in `node_modules/awesome-ui/components/`. :link-example{to="https://nuxt.com/docs/4.x/examples/features/auto-imports"} # composables ## Usage **Method 1:** Using named export ```ts [app/composables/useFoo.ts] export const useFoo = () => { return useState('foo', () => 'bar') } ``` **Method 2:** Using default export ```ts [app/composables/use-foo.ts or composables/useFoo.ts] // It will be available as useFoo() (camelCase of file name without extension) export default function () { return useState('foo', () => 'bar') } ``` **Usage:** You can now use auto imported composable in `.js`, `.ts` and `.vue` files ```vue [app/app.vue] ``` ::note The `app/composables/` directory in Nuxt does not provide any additional reactivity capabilities to your code. Instead, any reactivity within composables is achieved using Vue's Composition API mechanisms, such as ref and reactive. Note that reactive code is also not limited to the boundaries of the `app/composables/` directory. You are free to employ reactivity features wherever they're needed in your application. :: :read-more{to="https://nuxt.com/docs/4.x/guide/concepts/auto-imports"} :link-example{to="https://nuxt.com/docs/4.x/examples/features/auto-imports"} ## Types Under the hood, Nuxt auto generates the file `.nuxt/imports.d.ts` to declare the types. Be aware that you have to run [`nuxt prepare`](https://nuxt.com/docs/4.x/api/commands/prepare), [`nuxt dev`](https://nuxt.com/docs/4.x/api/commands/dev) or [`nuxt build`](https://nuxt.com/docs/4.x/api/commands/build) in order to let Nuxt generate the types. ::note If you create a composable without having the dev server running, TypeScript will throw an error, such as `Cannot find name 'useBar'.` :: ## Examples ### Nested Composables You can use a composable within another composable using auto imports: ```ts [app/composables/test.ts] export const useFoo = () => { const nuxtApp = useNuxtApp() const bar = useBar() } ``` ### Access plugin injections You can access [plugin injections](https://nuxt.com/docs/4.x/directory-structure/app/plugins#providing-helpers) from composables: ```ts [app/composables/test.ts] export const useHello = () => { const nuxtApp = useNuxtApp() return nuxtApp.$hello } ``` ## How Files Are Scanned Nuxt only scans files at the top level of the [`app/composables/` directory](https://nuxt.com/docs/4.x/directory-structure/app/composables), e.g.: ```bash [Directory Structure] -| composables/ ---| index.ts // scanned ---| useFoo.ts // scanned ---| nested/ -----| utils.ts // not scanned ``` Only `app/composables/index.ts` and `app/composables/useFoo.ts` would be searched for imports. To get auto imports working for nested modules, you could either re-export them (recommended) or configure the scanner to include nested directories: **Example:** Re-export the composables you need from the `app/composables/index.ts` file: ```ts [app/composables/index.ts] // Enables auto import for this export export { utils } from './nested/utils.ts' ``` **Example:** Scan nested directories inside the `app/composables/` folder: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ imports: { dirs: [ // Scan top-level composables '~/composables', // ... or scan composables nested one level deep with a specific name and file extension '~/composables/*/index.{ts,js,mjs,mts}', // ... or scan all composables within given directory '~/composables/**', ], }, }) ``` # layouts ::tip{icon="i-lucide-rocket"} For best performance, components placed in this directory will be automatically loaded via asynchronous import when used. :: ## Enable Layouts Layouts are enabled by adding [``](https://nuxt.com/docs/4.x/api/components/nuxt-layout) to your [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app): ```vue [app/app.vue] ``` To use a layout: - Set a `layout` property in your page with [definePageMeta](https://nuxt.com/docs/4.x/api/utils/define-page-meta). - Set the `name` prop of ``. - Set the `appLayout` property in route rules. ::note The layout name is normalized to kebab-case, so `someLayout` becomes `some-layout`. :: ::note If no layout is specified, `app/layouts/default.vue` will be used. :: ::important If you only have a single layout in your application, we recommend using [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app) instead. :: ::important Unlike other components, your layouts must have a single root element to allow Nuxt to apply transitions between layout changes - and this root element cannot be a ``. :: ## Default Layout Add a `~/layouts/default.vue`: ```vue [app/layouts/default.vue] ``` In a layout file, the content of the page will be displayed in the `` component. ## Named Layout ```bash [Directory Structure] -| layouts/ ---| default.vue ---| custom.vue ``` Then you can use the `custom` layout in your page: ```vue [pages/about.vue] twoslash ``` ::read-more --- to: https://nuxt.com/docs/4.x/directory-structure/app/pages#page-metadata --- Learn more about `definePageMeta`. :: You can directly override the default layout for all pages using the `name` property of [``](https://nuxt.com/docs/4.x/api/components/nuxt-layout): ```vue [app/app.vue] ``` If you have a layout in nested directories, the layout's name will be based on its own path directory and filename, with duplicate segments being removed. | File | Layout Name | | --------------------------------- | ----------------- | | `~/layouts/desktop/default.vue` | `desktop-default` | | `~/layouts/desktop-base/base.vue` | `desktop-base` | | `~/layouts/desktop/index.vue` | `desktop` | For clarity, we recommend that the layout's filename matches its name: | File | Layout Name | | ---------------------------------------- | ----------------- | | `~/layouts/desktop/DesktopDefault.vue` | `desktop-default` | | `~/layouts/desktop-base/DesktopBase.vue` | `desktop-base` | | `~/layouts/desktop/Desktop.vue` | `desktop` | :link-example{to="https://nuxt.com/docs/4.x/examples/features/layouts"} ## Changing the Layout Dynamically You can also use the [`setPageLayout`](https://nuxt.com/docs/4.x/api/utils/set-page-layout) helper to change the layout dynamically: ```vue twoslash ``` You can also set layouts for specific routes using the `appLayout` property in route rules: ```ts [nuxt.config.ts] export default defineNuxtConfig({ routeRules: { // Set layout for specific route '/admin': { appLayout: 'admin' }, // Set layout for multiple routes '/dashboard/**': { appLayout: 'dashboard' }, }, }) ``` :link-example{to="https://nuxt.com/docs/4.x/examples/features/layouts"} ## Overriding a Layout on a Per-page Basis If you are using pages, you can take full control by setting `layout: false` and then using the `` component within the page. ::code-group ```vue [app/pages/index.vue] ``` ```vue [app/layouts/custom.vue] ``` :: ::important If you use `` within your pages, make sure it is not the root element (or [disable layout/page transitions](https://nuxt.com/docs/4.x/getting-started/transitions#disable-transitions)). :: # middleware Nuxt provides a customizable **route middleware** framework you can use throughout your application, ideal for extracting code that you want to run before navigating to a particular route. There are three kinds of route middleware: 1. Anonymous (or inline) route middleware are defined directly within the page. 2. Named route middleware, placed in the `app/middleware/` and automatically loaded via asynchronous import when used on a page. 3. Global route middleware, placed in the `app/middleware/` with a `.global` suffix and is run on every route change. The first two kinds of route middleware can be defined in [`definePageMeta`](https://nuxt.com/docs/4.x/api/utils/define-page-meta). ::note Name of middleware are normalized to kebab-case: `myMiddleware` becomes `my-middleware`. :: ::note Route middleware run within the Vue part of your Nuxt app. Despite the similar name, they are completely different from [server middleware](https://nuxt.com/docs/4.x/directory-structure/server#server-middleware), which are run in the Nitro server part of your app. :: :video-accordion{platform="vimeo" title="Watch a video from Vue School on all 3 kinds of middleware" video-id="761471577"} ## Usage Route middleware are navigation guards that receive the current route and the next route as arguments. ```ts [middleware/my-middleware.ts] twoslash export default defineNuxtRouteMiddleware((to, from) => { if (to.params.id === '1') { return abortNavigation() } // In a real app you would probably not redirect every route to `/` // however it is important to check `to.path` before redirecting or you // might get an infinite redirect loop if (to.path !== '/') { return navigateTo('/') } }) ``` Nuxt provides two globally available helpers that can be returned directly from the middleware. 1. [`navigateTo`](https://nuxt.com/docs/4.x/api/utils/navigate-to) - Redirects to the given route 2. [`abortNavigation`](https://nuxt.com/docs/4.x/api/utils/abort-navigation) - Aborts the navigation, with an optional error message. Unlike [navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards#Global-Before-Guards){rel=""nofollow""} from `vue-router`, a third `next()` argument is not passed, and **redirect or route cancellation is handled by returning a value from the middleware**. Possible return values are: - nothing (a simple `return` or no return at all) - does not block navigation and will move to the next middleware function, if any, or complete the route navigation - `return navigateTo('/')` - redirects to the given path and will set the redirect code to [`302` Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/302){rel=""nofollow""} if the redirect happens on the server side - `return navigateTo('/', { redirectCode: 301 })` - redirects to the given path and will set the redirect code to [`301` Moved Permanently](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301){rel=""nofollow""} if the redirect happens on the server side - `return abortNavigation()` - stops the current navigation - `return abortNavigation(error)` - rejects the current navigation with an error :read-more{to="https://nuxt.com/docs/4.x/api/utils/navigate-to"} :read-more{to="https://nuxt.com/docs/4.x/api/utils/abort-navigation"} ::important We recommend using the helper functions above for performing redirects or stopping navigation. Other possible return values described in [the vue-router docs](https://router.vuejs.org/guide/advanced/navigation-guards#Global-Before-Guards){rel=""nofollow""} may work but there may be breaking changes in future. :: ## Middleware Order Middleware runs in the following order: 1. Global Middleware 2. Page defined middleware order (if there are multiple middleware declared with the array syntax) For example, assuming you have the following middleware and component: ```bash [app/middleware/ directory] -| middleware/ ---| analytics.global.ts ---| setup.global.ts ---| auth.ts ``` ```vue [pages/profile.vue] twoslash ``` You can expect the middleware to be run in the following order: 1. `analytics.global.ts` 2. `setup.global.ts` 3. Custom inline middleware 4. `auth.ts` ### Ordering Global Middleware By default, global middleware is executed alphabetically based on the filename. However, there may be times you want to define a specific order. For example, in the last scenario, `setup.global.ts` may need to run before `analytics.global.ts`. In that case, we recommend prefixing global middleware with 'alphabetical' numbering. ```bash [Directory structure] -| middleware/ ---| 01.setup.global.ts ---| 02.analytics.global.ts ---| auth.ts ``` ::note In case you're new to 'alphabetical' numbering, remember that filenames are sorted as strings, not as numeric values. For example, `10.new.global.ts` would come before `2.new.global.ts`. This is why the example prefixes single digit numbers with `0`. :: ## When Middleware Runs If your site is server-rendered or generated, middleware for the initial page will be executed both when the page is rendered and then again on the client. This might be needed if your middleware needs a browser environment, such as if you have a generated site, aggressively cache responses, or want to read a value from local storage. However, if you want to avoid this behaviour you can do so: ```ts [middleware/example.ts] twoslash export default defineNuxtRouteMiddleware((to) => { // skip middleware on server if (import.meta.server) { return } // skip middleware on client side entirely if (import.meta.client) { return } // or only skip middleware on initial client load const nuxtApp = useNuxtApp() if (import.meta.client && nuxtApp.isHydrating && nuxtApp.payload.serverRendered) { return } }) ``` This is true even if you throw an error in your middleware on the server, and an error page is rendered. The middleware will still run again in the browser. ::note Rendering an error page is an entirely separate page load, meaning any registered middleware will run again. You can use [`useError`](https://nuxt.com/docs/4.x/getting-started/error-handling#useerror) in middleware to check if an error is being handled. :: ## Accessing Route in Middleware Always use the `to` and `from` parameters in your middleware to access the next and previous routes. Avoid using the [`useRoute()`](https://nuxt.com/docs/4.x/api/composables/use-route) composable in this context altogether. There is **no concept of a "current route" in middleware**, as middleware can abort a navigation or redirect to a different route. The `useRoute()` composable will always be inaccurate in this context. ::warning Sometimes, you might call a composable that uses `useRoute()` internally, which can trigger this warning even if there is no direct call in your middleware. This leads to the **same issue as above**, so you should structure your functions to accept the route as an argument instead when they are used in middleware. :: ::code-group ```ts [middleware/access-route.ts] twoslash // @errors: 2304 export default defineNuxtRouteMiddleware((to) => { // passing the route to the function to avoid calling `useRoute()` in middleware doSomethingWithRoute(to) // ❌ this will output a warning and is NOT recommended callsRouteInternally() }) ``` ```ts [utils/handle-route.ts] twoslash // providing the route as an argument so that it can be used in middleware correctly export function doSomethingWithRoute (route = useRoute()) { // ... } ``` ```ts [utils/dont-do-this.ts] twoslash // ❌ this function is not suitable for use in middleware export function callsRouteInternally () { const route = useRoute() // ... } ``` :: ## Adding Middleware Dynamically It is possible to add global or named route middleware manually using the [`addRouteMiddleware()`](https://nuxt.com/docs/4.x/api/utils/add-route-middleware) helper function, such as from within a plugin. ```ts twoslash export default defineNuxtPlugin(() => { addRouteMiddleware('global-test', () => { console.log('this global middleware was added in a plugin and will be run on every route change') }, { global: true }) addRouteMiddleware('named-test', () => { console.log('this named middleware was added in a plugin and would override any existing middleware of the same name') }) }) ``` ## Example ```bash [Directory Structure] -| middleware/ ---| auth.ts ``` In your page file, you can reference this route middleware: ```vue twoslash ``` Now, before navigation to that page can complete, the `auth` route middleware will be run. :link-example{to="https://nuxt.com/docs/4.x/examples/routing/middleware"} ## Setting Middleware at Build Time Instead of using `definePageMeta` on each page, you can add named route middleware within the `pages:extend` hook. ```ts [nuxt.config.ts] twoslash import type { NuxtPage } from 'nuxt/schema' export default defineNuxtConfig({ hooks: { 'pages:extend' (pages) { function setMiddleware (pages: NuxtPage[]) { for (const page of pages) { if (/* some condition */ Math.random() > 0.5) { page.meta ||= {} // Note that this will override any middleware set in `definePageMeta` in the page page.meta.middleware = ['named'] } if (page.children) { setMiddleware(page.children) } } } setMiddleware(pages) }, }, }) ``` # pages ::note To reduce your application's bundle size, this directory is **optional**, meaning that [`vue-router`](https://router.vuejs.org){rel=""nofollow""} won't be included if you only use [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app). To force the pages system, set `pages: true` in `nuxt.config` or have a [`router.options.ts`](https://nuxt.com/docs/4.x/guide/recipes/custom-routing#using-routeroptions). :: ## Usage Pages are Vue components and can have any [valid extension](https://nuxt.com/docs/4.x/api/nuxt-config#extensions) that Nuxt supports (by default `.vue`, `.js`, `.jsx`, `.mjs`, `.ts` or `.tsx`). Nuxt will automatically create a route for every page in your `~/pages/` directory. ::code-group ```vue [app/pages/index.vue] ``` ```ts [pages/index.ts] twoslash // https://vuejs.org/guide/extras/render-function.html export default defineComponent({ render () { return h('h1', 'Index page') }, }) ``` ```tsx [pages/index.tsx] twoslash // https://nuxt.com/docs/4.x/examples/advanced/jsx // https://vuejs.org/guide/extras/render-function.html#jsx-tsx export default defineComponent({ render () { return

Index page

}, }) ``` :: The `app/pages/index.vue` file will be mapped to the `/` route of your application. If you are using [`app.vue`](https://nuxt.com/docs/4.x/directory-structure/app/app), make sure to use the [``](https://nuxt.com/docs/4.x/api/components/nuxt-page) component to display the current page: ```vue [app/app.vue] ``` Pages **must have a single root element** to allow [route transitions](https://nuxt.com/docs/4.x/getting-started/transitions) between pages. HTML comments are considered elements as well. This means that when the route is server-rendered, or statically generated, you will be able to see its contents correctly, but when you navigate towards that route during client-side navigation the transition between routes will fail and you'll see that the route will not be rendered. Here are some examples to illustrate what a page with a single root element looks like: ::code-group ```vue [app/pages/working.vue] ``` ```vue [app/pages/bad-1.vue] ``` ```vue [app/pages/bad-2.vue] ``` :: ## Dynamic Routes If you place anything within square brackets, it will be turned into a [dynamic route](https://router.vuejs.org/guide/essentials/dynamic-matching){rel=""nofollow""} parameter. You can mix and match multiple parameters and even non-dynamic text within a file name or directory. If you want a parameter to be *optional*, you must enclose it in double square brackets - for example, `~/pages/[[slug]]/index.vue` or `~/pages/[[slug]].vue` will match both `/` and `/test`. ```bash [Directory Structure] -| pages/ ---| index.vue ---| users-[group]/ -----| [id].vue ``` Given the example above, you can access group/id within your component via the `$route` object: ```vue [app/pages/users-[group\\]/[id\\].vue] ``` Navigating to `/users-admins/123` would render: ```html

admins - 123

``` If you want to access the route using Composition API, there is a global [`useRoute`](https://nuxt.com/docs/4.x/api/composables/use-route) function that will allow you to access the route just like `this.$route` in the Options API. ```vue twoslash ``` ::note Named parent routes will take priority over nested dynamic routes. For the `/foo/hello` route, `~/pages/foo.vue` will take priority over `~/pages/foo/[slug].vue`. :br Use `~/pages/foo/index.vue` and `~/pages/foo/[slug].vue` to match `/foo` and `/foo/hello` with different pages,. :: :video-accordion{platform="vimeo" title="Watch a video from Vue School on dynamic routes" video-id="754465699"} ## Catch-all Route If you need a catch-all route, you create it by using a file named like `[...slug].vue`. This will match *all* routes under that path. ```vue [app/pages/[...slug\\].vue] ``` Navigating to `/hello/world` would render: ```html

["hello", "world"]

``` ## Nested Routes It is possible to display [nested routes](https://router.vuejs.org/guide/essentials/nested-routes){rel=""nofollow""} with ``. Example: ```bash [Directory Structure] -| pages/ ---| parent/ -----| child.vue ---| parent.vue ``` This file tree will generate these routes: ```js [ { path: '/parent', component: '~/pages/parent.vue', name: 'parent', children: [ { path: 'child', component: '~/pages/parent/child.vue', name: 'parent-child', }, ], }, ] ``` To display the `child.vue` component, you have to insert the `` component inside `app/pages/parent.vue`: ```vue [pages/parent.vue] ``` ```vue [pages/parent/child.vue] ``` ### Child Route Keys If you want more control over when the `` component is re-rendered (for example, for transitions), you can either pass a string or function via the `pageKey` prop, or you can define a `key` value via `definePageMeta`: ```vue [pages/parent.vue] ``` Or alternatively: ```vue [pages/parent/child.vue] twoslash ``` :link-example{to="https://nuxt.com/docs/4.x/examples/routing/pages"} ## Route Groups In some cases, you may want to group a set of routes together in a way which doesn't affect file-based routing. For this purpose, you can put files in a folder which is wrapped in parentheses - `(` and `)`. For example: ```bash [Directory structure] -| pages/ ---| index.vue ---| (marketing)/ -----| about.vue -----| contact.vue ``` This will produce `/`, `/about` and `/contact` pages in your app. The `marketing` group is ignored for purposes of your URL structure. ### Accessing Route Groups Route groups are automatically available in the route metadata as `route.meta.groups`. This allows you to access the group information in your components for conditional logic, styling, or other purposes. ```vue [pages/(marketing)/about.vue] ``` ## Page Metadata You might want to define metadata for each route in your app. You can do this using the `definePageMeta` macro, which will work both in ` ``` This data can then be accessed throughout the rest of your app from the `route.meta` object. ```vue twoslash ``` If you are using nested routes, the page metadata from all these routes will be merged into a single object. For more on route meta, see the [vue-router docs](https://router.vuejs.org/guide/advanced/meta){rel=""nofollow""}. Much like `defineEmits` or `defineProps` (see [Vue docs](https://vuejs.org/api/sfc-script-setup#defineprops-defineemits){rel=""nofollow""}), `definePageMeta` is a **compiler macro**. It will be compiled away so you cannot reference it within your component. Instead, the metadata passed to it will be hoisted out of the component. Therefore, the page meta object cannot reference the component. However, it can reference imported bindings, as well as locally defined **pure functions**. ::warning Make sure not to reference any reactive data or functions that cause side effects. This can lead to unexpected behavior. :: ```vue ``` ### Special Metadata Of course, you are welcome to define metadata for your own use throughout your app. But some metadata defined with `definePageMeta` has a particular purpose: #### `alias` You can define page aliases. They allow you to access the same page from different paths. It can be either a string or an array of strings as defined [in the vue-router documentation](https://router.vuejs.org/guide/essentials/redirect-and-alias#Alias){rel=""nofollow""}. #### `keepalive` Nuxt will automatically wrap your page in [the Vue `` component](https://vuejs.org/guide/built-ins/keep-alive#keepalive){rel=""nofollow""} if you set `keepalive: true` in your `definePageMeta`. This might be useful to do, for example, in a parent route that has dynamic child routes, if you want to preserve page state across route changes. When your goal is to preserve state for parent routes use this syntax: ``. You can also set props to be passed to `` (see [a full list](https://vuejs.org/api/built-in-components#keepalive){rel=""nofollow""}). You can set a default value for this property [in your `nuxt.config`](https://nuxt.com/docs/4.x/api/nuxt-config#keepalive). #### `key` [See above](https://nuxt.com/docs/4.x/directory-structure/app/pages#child-route-keys). #### `layout` You can define the layout used to render the route. This can be either false (to disable any layout), a string or a ref/computed, if you want to make it reactive in some way. [More about layouts](https://nuxt.com/docs/4.x/directory-structure/app/layouts). #### `layoutTransition` and `pageTransition` You can define transition properties for the `` component that wraps your pages and layouts, or pass `false` to disable the `` wrapper for that route. You can see [a list of options that can be passed](https://vuejs.org/api/built-in-components#transition){rel=""nofollow""} or read [more about how transitions work](https://vuejs.org/guide/built-ins/transition#transition){rel=""nofollow""}. You can set default values for these properties [in your `nuxt.config`](https://nuxt.com/docs/4.x/api/nuxt-config#layouttransition). #### `middleware` You can define middleware to apply before loading this page. It will be merged with all the other middleware used in any matching parent/child routes. It can be a string, a function (an anonymous/inlined middleware function following [the global before guard pattern](https://router.vuejs.org/guide/advanced/navigation-guards#Global-Before-Guards){rel=""nofollow""}), or an array of strings/functions. [More about named middleware](https://nuxt.com/docs/4.x/directory-structure/app/middleware). #### `name` You may define a name for this page's route. #### `path` You may define a path matcher, if you have a more complex pattern than can be expressed with the file name. See [the `vue-router` docs](https://router.vuejs.org/guide/essentials/route-matching-syntax#Custom-regex-in-params){rel=""nofollow""} for more information. #### `props` Allows accessing the route `params` as props passed to the page component. See [the `vue-router` docs](https://router.vuejs.org/guide/essentials/passing-props){rel=""nofollow""} for more information. ### Typing Custom Metadata If you add custom metadata for your pages, you may wish to do so in a type-safe way. It is possible to augment the type of the object accepted by `definePageMeta`: ```ts [index.d.ts] declare module '#app' { interface PageMeta { pageType?: string } } // It is always important to ensure you import/export something when augmenting a type export {} ``` ## Navigation To navigate between pages of your app, you should use the [``](https://nuxt.com/docs/4.x/api/components/nuxt-link) component. This component is included with Nuxt and therefore you don't have to import it as you do with other components. A simple link to the `index.vue` page in your `app/pages` folder: ```vue ``` ::read-more{to="https://nuxt.com/docs/4.x/api/components/nuxt-link"} Learn more about `` usage. :: ## Programmatic Navigation Nuxt allows programmatic navigation through the `navigateTo()` utility method. Using this utility method, you will be able to programmatically navigate the user in your app. This is great for taking input from the user and navigating them dynamically throughout your application. In this example, we have a simple method called `navigate()` that gets called when the user submits a search form. ::note Make sure to always `await` on `navigateTo` or chain its result by returning from functions. :: ```vue twoslash ``` ## Client-Only Pages You can define a page as [client only](https://nuxt.com/docs/4.x/directory-structure/app/components#client-components) by giving it a `.client.vue` suffix. None of the content of this page will be rendered on the server. ## Server-Only Pages You can define a page as [server only](https://nuxt.com/docs/4.x/directory-structure/app/components#server-components) by giving it a `.server.vue` suffix. While you will be able to navigate to the page using client-side navigation, controlled by `vue-router`, it will be rendered with a server component automatically, meaning the code required to render the page will not be in your client-side bundle. ::warning Server-only pages must have a single root element. (HTML comments are considered elements as well.) :: ## Custom Routing As your app gets bigger and more complex, your routing might require more flexibility. For this reason, Nuxt directly exposes the router, routes and router options for customization in different ways. :read-more{to="https://nuxt.com/docs/4.x/guide/recipes/custom-routing"} ## Multiple Pages Directories By default, all your pages should be in one `app/pages` directory at the root of your project. However, you can use [Nuxt Layers](https://nuxt.com/docs/4.x/getting-started/layers) to create groupings of your app's pages: ```bash [Directory Structure] -| some-app/ ---| nuxt.config.ts ---| pages/ -----| app-page.vue -| nuxt.config.ts ``` ```ts [some-app/nuxt.config.ts] twoslash // some-app/nuxt.config.ts export default defineNuxtConfig({ }) ``` ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ extends: ['./some-app'], }) ``` :read-more{to="https://nuxt.com/docs/4.x/guide/going-further/layers"} # plugins Nuxt automatically reads the files in the `app/plugins/` directory and loads them at the creation of the Vue application. ::note All plugins inside are auto-registered, you don't need to add them to your `nuxt.config` separately. :: ::note You can use `.server` or `.client` suffix in the file name to load a plugin only on the server or client side. :: ## Registered Plugins Only files at the top level of the directory (or index files within any subdirectories) will be auto-registered as plugins. ```bash [Directory structure] -| plugins/ ---| foo.ts // scanned ---| bar/ -----| baz.ts // not scanned -----| foz.vue // not scanned -----| index.ts // currently scanned but deprecated ``` Only `foo.ts` and `bar/index.ts` would be registered. To add plugins in subdirectories, you can use the [`app/plugins`](https://nuxt.com/docs/4.x/api/nuxt-config#plugins-1) option in `nuxt.config.ts`: ```ts [nuxt.config.ts] twoslash export default defineNuxtConfig({ plugins: [ '~/plugins/bar/baz', '~/plugins/bar/foz', ], }) ``` ## Creating Plugins The only argument passed to a plugin is [`nuxtApp`](https://nuxt.com/docs/4.x/api/composables/use-nuxt-app). ```ts [plugins/hello.ts] twoslash export default defineNuxtPlugin((nuxtApp) => { // Doing something with nuxtApp }) ``` ### Object Syntax Plugins It is also possible to define a plugin using an object syntax, for more advanced use cases. For example: ```ts [plugins/hello.ts] twoslash export default defineNuxtPlugin({ name: 'my-plugin', enforce: 'pre', // or 'post' async setup (nuxtApp) { // this is the equivalent of a normal functional plugin }, hooks: { // You can directly register Nuxt app runtime hooks here 'app:created' () { const nuxtApp = useNuxtApp() // do something in the hook }, }, env: { // Set this value to `false` if you don't want the plugin to run when rendering server-only or island components. islands: true, }, }) ``` :video-accordion{title="Watch a video from Alexander Lichter about the Object Syntax for Nuxt plugins" video-id="2aXZyXB1QGQ"} ::note If you are using the object-syntax, the properties are statically analyzed to produce a more optimized build. So you should not define them at runtime. :br For example, setting `enforce: import.meta.server ? 'pre' : 'post'` would defeat any future optimization Nuxt is able to do for your plugins. Nuxt does statically pre-load any hook listeners when using object-syntax, allowing you to define hooks without needing to worry about order of plugin registration. :: ## Registration Order You can control the order in which plugins are registered by prefixing with 'alphabetical' numbering to the file names. ```bash [Directory structure] plugins/ | - 01.myPlugin.ts | - 02.myOtherPlugin.ts ``` In this example, `02.myOtherPlugin.ts` will be able to access anything that was injected by `01.myPlugin.ts`. This is useful in situations where you have a plugin that depends on another plugin. ::note In case you're new to 'alphabetical' numbering, remember that filenames are sorted as strings, not as numeric values. For example, `10.myPlugin.ts` would come before `2.myOtherPlugin.ts`. This is why the example prefixes single digit numbers with `0`. :: ## Loading Strategy ### Parallel Plugins By default, Nuxt loads plugins sequentially. You can define a plugin as `parallel` so Nuxt won't wait until the end of the plugin's execution before loading the next plugin. ```ts [plugins/my-plugin.ts] twoslash export default defineNuxtPlugin({ name: 'my-plugin', parallel: true, async setup (nuxtApp) { // the next plugin will be executed immediately }, }) ``` ### Plugins With Dependencies If a plugin needs to wait for another plugin before it runs, you can add the plugin's name to the `dependsOn` array. ```ts [plugins/depending-on-my-plugin.ts] twoslash export default defineNuxtPlugin({ name: 'depends-on-my-plugin', dependsOn: ['my-plugin'], async setup (nuxtApp) { // this plugin will wait for the end of `my-plugin`'s execution before it runs }, }) ``` ## Using Composables You can use [composables](https://nuxt.com/docs/4.x/directory-structure/app/composables) as well as [utils](https://nuxt.com/docs/4.x/directory-structure/app/utils) within Nuxt plugins: ```ts [app/plugins/hello.ts] export default defineNuxtPlugin((nuxtApp) => { const foo = useFoo() }) ``` However, keep in mind there are some limitations and differences: ::important **If a composable depends on another plugin registered later, it might not work.** :br Plugins are called in order sequentially and before everything else. You might use a composable that depends on another plugin which has not been called yet. :: ::important **If a composable depends on the Vue.js lifecycle, it won't work.** :br Normally, Vue.js composables are bound to the current component instance while plugins are only bound to [`nuxtApp`](https://nuxt.com/docs/4.x/api/composables/use-nuxt-app) instance. :: ## Providing Helpers If you would like to provide a helper on the [`NuxtApp`](https://nuxt.com/docs/4.x/api/composables/use-nuxt-app) instance, return it from the plugin under a `provide` key. ::code-group ```ts [plugins/hello.ts] twoslash export default defineNuxtPlugin(() => { return { provide: { hello: (msg: string) => `Hello ${msg}!`, }, } }) ``` ```ts [plugins/hello-object-syntax.ts] twoslash export default defineNuxtPlugin({ name: 'hello', setup () { return { provide: { hello: (msg: string) => `Hello ${msg}!`, }, } }, }) ``` :: You can then use the helper in your components: ```vue [app/components/Hello.vue] ``` ::important Note that we highly recommend using [`composables`](https://nuxt.com/docs/4.x/directory-structure/app/composables) instead of providing helpers to avoid polluting the global namespace and keep your main bundle entry small. :: ::warning **If your plugin provides a `ref` or `computed`, it will not be unwrapped in a component `