docs: update to new website (#23743)

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Roe <daniel@roe.dev>
This commit is contained in:
Sébastien Chopin 2023-10-18 03:59:43 -07:00 committed by GitHub
parent 2e4ea2fe48
commit f26a801775
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
246 changed files with 4436 additions and 6591 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -14,3 +14,6 @@ MD033: false
MD032: false
MD046:
style: fenced
MD034: false
MD031: false
MD007: false

View File

@ -3,3 +3,6 @@
docs/0.index.md
docs/1.getting-started/1.introduction.md
docs/**/*.nuxt.config.md
docs/5.community/7.changelog.md
docs/1.getting-started/10.deployment.md
docs/2.guide/1.concepts/3.rendering.md

12
.website/.gitignore vendored
View File

@ -1,12 +0,0 @@
node_modules
*.iml
.idea
*.log*
.nuxt
.vscode
.DS_Store
coverage
dist
sw.*
.env
.output

View File

@ -1,35 +0,0 @@
# Nuxt Docs Website
This is a temporary directory until we open source the repository for nuxt.com.
The goal is to simplify the contribution in the meantime to the documentation by having the possibility to preview the changes locally.
## Setup
Install dependencies in the root of the `nuxt` folder:
```bash
pnpm i
```
Then stub the dependencies:
```bash
pnpm build:stub
```
## Development
In the root of the `nuxt` folder, run:
```bash
pnpm docs:dev
```
Then open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
Update the documentation within the `docs` folder.
---
For a detailed explanation of how things work, check out [Docus](https://docus.dev).

View File

@ -1,14 +0,0 @@
export default defineAppConfig({
docus: {
title: 'Nuxt Docs [dev]',
description: 'The best place to start your documentation.',
socials: {
twitter: 'nuxt_js',
github: 'nuxt/nuxt'
},
aside: {
level: 1,
collapsed: false,
},
}
})

View File

@ -1,20 +0,0 @@
import { createResolver } from 'nuxt/kit'
const { resolve } = createResolver(import.meta.url)
export default defineNuxtConfig({
// https://github.com/nuxt-themes/docus
extends: '@nuxt-themes/docus',
content: {
sources: {
docs: {
driver: 'fs',
prefix: '/',
base: resolve('../docs')
}
}
},
experimental: {
renderJsonPayloads: false
}
})

View File

@ -1,14 +0,0 @@
{
"name": "docus-starter",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "nuxt dev",
"build": "nuxt build",
"generate": "nuxt generate",
"preview": "nuxt preview"
},
"devDependencies": {
"@nuxt-themes/docus": "1.15.0"
}
}

View File

@ -1,3 +0,0 @@
{
"extends": "./.nuxt/tsconfig.json"
}

View File

@ -50,7 +50,7 @@ Here are a few ways you can get involved:
## Local Development
Follow the docs to [Set Up Your Local Development Environment](https://nuxt.com/docs/community/framework-contribution#set-up-your-local-development-environment) to contribute to the framework and documentation.
Follow the docs to [Set Up Your Local Development Environment](https://nuxt.com/docs/community/framework-contribution#setup) to contribute to the framework and documentation.
## Nuxt 2

View File

@ -1,216 +0,0 @@
---
title: Documentation
navigation: false
description: Learn everything you need to know about Nuxt, from beginner to master.
---
<!-- markdownlint-disable -->
<!-- @case-police-disable -->
::docs-hero
#title
Nuxt Docs
#description
Nuxt is a free and [open-source framework](https://github.com/nuxt/nuxt) 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).
::
::card-item{ .mt-4 }
---
is: 'div'
gradientBorder: false
descriptionClass: 'w-full sm:w-2/3'
buttonsWrapperClass: 'pr-[100px] sm:pr-0'
backgroundImage:
path: '/assets/docs/getting-started/views/getting-started'
width: '100'
height: '100'
format: 'png'
buttons:
- label: 'Get started'
size: 'sm'
variant: 'primary-gradient'
to: '/docs/getting-started/introduction'
- label: 'Explore Examples'
size: 'sm'
variant: 'secondary'
to: '/docs/examples/hello-world'
---
#title
Getting Started
#description
Start by learning Nuxt core features, from installation to deployment.
::
::docs-landing-section
#title
Guide
#description
From an idea to a masterpiece, guides take you on the path to becoming a Nuxter.
#extra
::card-list
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/key-concepts'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/guide/concepts/auto-imports'
---
#title
Key Concepts
#description
Get an overview of the concepts that drive the Nuxt experience.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/directory-structure'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/guide/directory-structure/nuxt'
---
#title
Directory Structure
#description
Navigate Nuxt directory structure with this handy guide.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/going-further'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/guide/going-further/internals'
---
#title
Going further
#description
Deep dive into Nuxt internals to master all the features.
:::
::
::
::docs-landing-section
#title
API
#description
Every Nuxt component, composable and utility, in detail.
#extra
::card-list
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/composables'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/api/composables/use-app-config'
---
#title
Composables
#description
From data fetching to error handling, get familiar with Nuxt built-in composables.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/components'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/api/components/client-only'
---
#title
Components
#description
Nuxt components, auto-imported and ready to use in your application.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/utils'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/api/utils/dollarfetch'
---
#title
Utils
#description
Use utility functions to get fine-grained control over your app behavior.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/advanced'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/api/advanced/hooks'
---
#title
Advanced
#description
Learn about lifecycle hooks and Kit utilities in the advanced section.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/commands'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/api/commands/add'
---
#title
Commands
#description
Meet Nuxi, Nuxt 3 command-line tool. The essential companion in your journey.
:::
:::card-item
---
gradientBorder: false
headerClass: 'justify-start px-4 pt-4 sm:px-6'
image:
path: '/assets/docs/getting-started/views/docs-landing/configuration'
width: '52'
height: '58'
format: 'svg'
contentClass: 'gap-y-2'
to: '/docs/api/configuration/nuxt-config'
---
#title
Configuration
#description
Master the Nuxt config file to customize the framework behavior.
:::
::
::

View File

@ -1,21 +1,19 @@
---
navigation.icon: uil:info-circle
title: 'Introduction'
description: Nuxt's goal is to make web development intuitive and performant with a great Developer Experience in mind.
navigation.icon: i-ph-info-duotone
---
# Introduction
Nuxt is a free and [open-source framework](https://github.com/nuxt/nuxt) 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).
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 [**anywhere, even to the edge**](/docs/getting-started/deployment).
Nuxt has no vendor lock-in, allowing you to deploy your application [**everywhere, even on the edge**](/blog/nuxt-on-the-edge).
## 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.
::list{type=success}
- **File-based routing:** define routes based on the structure of your [`pages/` directory](/docs/guide/directory-structure/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.
@ -23,7 +21,6 @@ Nuxt uses conventions and an opinionated directory structure to automate repetit
- **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://vitejs.dev) 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**.
@ -31,22 +28,18 @@ Nuxt takes care of these and provides both frontend and backend functionality so
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:
::list{type=success}
- **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.
::alert{type="info"}
Read more about the [Nuxt rendering modes](/docs/guide/concepts/rendering).
::
:read-more{title="Nuxt rendering modes" to="/docs/guide/concepts/rendering"}
### Server engine
@ -56,84 +49,30 @@ In development, it uses Rollup and Node.js workers for your server code and cont
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.
::alert{type="info"}
Read more about [Nuxt server engine](/docs/guide/concepts/server-engine).
::
:read-more{title="Nuxt server engine" to="/docs/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.
::alert{type="info"}
Discover more in the [deployment section](/docs/getting-started/deployment).
::
:read-more{title="Deployment section" to="/docs/getting-started/deployment"}
### Modular
A module system allows to extend Nuxt with custom features and integrations with third-party services.
::alert{type="info"}
Discover more about [modules](/docs/guide/concepts/modules).
::
:read-more{title="Nuxt Modules Concept" to="/docs/guide/concepts/modules"}
### Architecture
Nuxt is composed of different [core packages](https://github.com/nuxt/nuxt/tree/main/packages):
::list{type=info}
- Core Engine: [nuxt](https://github.com/nuxt/nuxt/tree/main/packages/nuxt)
- Bundlers: [@nuxt/vite-builder](https://github.com/nuxt/nuxt/tree/main/packages/vite) and [@nuxt/webpack-builder](https://github.com/nuxt/nuxt/tree/main/packages/webpack)
- Command line interface: [nuxi](https://github.com/nuxt/nuxt/tree/main/packages/nuxi)
- Server engine: [nitro](https://github.com/unjs/nitro)
- Development kit: [@nuxt/kit](https://github.com/nuxt/nuxt/tree/main/packages/kit)
- Nuxt 2 Bridge: [@nuxt/bridge](https://github.com/nuxt/bridge)
::
We recommend reading each concept to have a full vision of Nuxt capabilities and the scope of each package.
::card-list
---
cardListClass: 'grid grid-cols-1 gap-y-4'
---
:::card-item
---
gradientBorder: false
backgroundImage:
path: '/assets/docs/getting-started/views/are-you-nuxt'
width: '72px'
height: '92px'
format: 'png'
titleClass: 'text-5xl font-semibold u-text-gray-900 pb-2'
descriptionClass: 'md:mr-[64px] w-[90%]'
---
#title
Are you Nuxt?
#description
Nuxt is the backbone of your Vue.js project, giving structure to build your project with confidence while keeping flexibility.
<br>
<br>
Extendable with a strong module ecosystem and hooks engine, it makes it easy to connect your REST or GraphQL endpoints, favorite CMS, CSS frameworks and more. PWA and AMP support is only a module away from your Nuxt project.
<br>
<br>
Ready to try? Head over to the [Installation section](/docs/getting-started/installation).
:::
:::card-item
---
gradientBorder: false
backgroundImage:
path: '/assets/docs/getting-started/views/contribute'
width: '72'
height: '92'
format: 'png'
titleClass: 'text-2xl u-text-gray-900 font-semibold'
descriptionClass: 'md:mr-[64px]'
---
#title
Contribute
#description
Do you want to get involved in the evolution of Nuxt?
<br>
Follow the [contribution guide](/docs/community/contribution).
:::
::

View File

@ -1,50 +1,40 @@
---
navigation.icon: uil:rocket
description: Deploy on a Node.js server, pre-render for static hosting and to serverless or edge environments.
title: 'Deployment'
description: Learn how to deploy your Nuxt application to any hosting provider.
navigation.icon: i-ph-cloud-duotone
---
# 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.
::alert{type=info}
If you are looking for a list of cloud providers that support Nuxt 3, see the [list below](#supported-hosting-providers).
::callout
If you are looking for a list of cloud providers that support Nuxt 3, see the [Hosting providers](#hosting-providers) section.
::
## Node.js Server
Discover the Node.js server preset with Nitro to deploy on any Node hosting.
::list{type="success"}
- **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
```bash [Terminal]
node .output/server/index.mjs
```
### Example
This will launch your production Nuxt server that listens on port 3000 by default.
```bash
$ node .output/server/index.mjs
Listening on http://localhost:3000
```
### Configuring Defaults at Runtime
This preset will respect the following runtime environment variables:
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.
#### Using PM2
### PM2
To use `pm2`, use an `ecosystem.config.js`:
@ -62,7 +52,7 @@ module.exports = {
}
```
#### Using Cluster Mode
### 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) module.
@ -70,20 +60,20 @@ By default, the workload gets distributed to the workers with the round robin st
### Learn More
:ReadMore{link="https://nitro.unjs.io/deploy/node" title="the Nitro documentation for node-server preset"}
:read-more{to="https://nitro.unjs.io/deploy/node" title="the Nitro documentation for node-server preset"}
## 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 `nuxi 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 `<div id="__nuxt"></div>` where your Vue app would normally be rendered. You will lose many of the benefits of prerendering your site, so it is suggested instead to use `<ClientOnly>` to wrap the portions of your site that cannot be server rendered (if any).
- Alternatively, you can prerender your site with `ssr: false` (static single-page app). This will produce HTML pages with an empty `<div id="__nuxt"></div>` 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 [`<ClientOnly>`](/docs/api/components/client-only) to wrap the portions of your site that cannot be server rendered (if any).
### Crawl-based Pre-rendering
Use the [`nuxi generate` command](/docs/api/commands/generate) to build and pre-render your application using the [Nitro](/docs/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`.
```bash
```bash [Terminal]
npx nuxi generate
```
@ -98,15 +88,15 @@ Working of the Nitro crawler:
This is important to understand since pages that are not linked to a discoverable page can't be pre-rendered automatically.
::alert{type=info}
Read more about the [`nuxi generate` command](/docs/api/commands/generate#nuxi-generate).
::read-more{to="/docs/api/commands/generate#nuxi-generate"}
Read more about the `nuxi generate` command.
::
### Selective Pre-rendering
You can manually specify routes that [Nitro](/docs/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|js]
```ts [nuxt.config.ts]
defineNuxtConfig({
nitro: {
prerender: {
@ -119,7 +109,7 @@ defineNuxtConfig({
You can combine this with the `crawLinks` 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|js]
```ts [nuxt.config.ts]
defineNuxtConfig({
nitro: {
prerender: {
@ -132,27 +122,178 @@ defineNuxtConfig({
Setting `nitro.prerender` to `true` is similar to `nitro.prerender.crawlLinks` to `true`.
::alert{type=info}
Read more about [pre-rendering](https://nitro.unjs.io/config#prerender) in the Nitro documentation.
::read-more{to="https://nitro.unjs.io/config#prerender"}
Read more about pre-rendering in the Nitro documentation.
::
### 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 `nuxi 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|js]
```ts [nuxt.config.ts]
defineNuxtConfig({
ssr: false
})
```
## Hosting Providers
Nuxt 3 can be deployed to several cloud providers with a minimal amount of configuration:
::card-group
::card
---
title: AWS
icon: i-simple-icons-amazonaws
to: https://nitro.unjs.io/deploy/providers/aws
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Azure
icon: i-simple-icons-microsoftazure
to: https://nitro.unjs.io/deploy/providers/azure
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Cleavr
icon: i-ph-cloud-duotone
to: https://nitro.unjs.io/deploy/providers/cleavr
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Deno
icon: i-simple-icons-deno
to: https://nitro.unjs.io/deploy/providers/deno
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: CloudFlare
icon: i-simple-icons-cloudflare
to: https://nitro.unjs.io/deploy/providers/cloudflare
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: DigitalOcean
icon: i-simple-icons-digitalocean
to: https://nitro.unjs.io/deploy/providers/digitalocean
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Edgio
icon: i-ph-cloud-duotone
to: https://nitro.unjs.io/deploy/providers/edgio
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Firebase
icon: i-simple-icons-firebase
to: https://nitro.unjs.io/deploy/providers/firebase
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Flightcontrol
icon: i-ph-cloud-duotone
to: https://nitro.unjs.io/deploy/providers/flightcontrol
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: GitHub Pages
icon: i-simple-icons-github
to: https://nitro.unjs.io/deploy/providers/github-pages
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Heroku
icon: i-simple-icons-heroku
to: https://nitro.unjs.io/deploy/providers/heroku
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Lagon
icon: i-ph-cloud-duotone
to: https://nitro.unjs.io/deploy/providers/lagon
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Netlify
icon: i-simple-icons-netlify
to: https://nitro.unjs.io/deploy/providers/netlify
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Render
icon: i-simple-icons-render
to: https://nitro.unjs.io/deploy/providers/render
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Stormkit
icon: i-ph-cloud-duotone
to: https://nitro.unjs.io/deploy/providers/stormkit
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::card
---
title: Vercel
icon: i-simple-icons-vercel
to: https://nitro.unjs.io/deploy/providers/vercel
target: _blank
ui.icon.base: 'text-black dark:text-white'
---
::
::
## Presets
In addition to Node.js servers and static hosting services, a Nuxt 3 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`](/docs/guide/directory-structure/nuxt.config) file:
```js [nuxt.config.js|ts]
```js [nuxt.config.ts]
export default {
nitro: {
preset: 'node-server'
@ -162,30 +303,12 @@ export default {
... or use the `NITRO_PRESET` environment variable when running `nuxt build`:
```bash
```bash [Terminal]
NITRO_PRESET=node-server nuxt build
```
🔎 Check [the Nitro deployment](https://nitro.unjs.io/deploy) for all possible deployment presets and providers.
### Supported Hosting Providers
Nuxt 3 can be deployed to several cloud providers with a minimal amount of configuration:
- :icon{name="logos:aws" class="h-5 w-4 inline mb-2"} [AWS](https://nitro.unjs.io/deploy/providers/aws)
- :icon{name="logos:microsoft-azure" class="h-5 w-4 inline mb-2"} [Azure](https://nitro.unjs.io/deploy/providers/azure)
- :icon{name="ph:cloud-duotone" class="h-5 w-4 inline mb-2"} [Cleavr](https://nitro.unjs.io/deploy/providers/cleavr)
- :icon{name="logos:cloudflare" class="h-5 w-4 inline mb-2"} [Cloudflare](https://nitro.unjs.io/deploy/providers/cloudflare)
- :icon{name="logos:digital-ocean" class="h-5 w-4 inline mb-2"} [DigitalOcean](https://nitro.unjs.io/deploy/providers/digitalocean)
- :icon{name="ph:cloud-duotone" class="h-5 w-4 inline mb-2"} [Edgio](https://nitro.unjs.io/deploy/providers/edgio)
- :icon{name="logos:firebase" class="h-5 w-4 inline mb-2"} [Firebase](https://nitro.unjs.io/deploy/providers/firebase)
- :icon{name="logos:heroku-icon" class="h-5 w-4 inline mb-2"} [Heroku](https://nitro.unjs.io/deploy/providers/heroku)
- :icon{name="IconLagon" class="h-5 w-4 inline mb-2 text-black dark:text-white"} [Lagon](https://nitro.unjs.io/deploy/providers/lagon)
- :icon{name="logos:netlify" class="h-5 w-4 inline mb-2"} [Netlify](https://nitro.unjs.io/deploy/providers/netlify)
- :icon{name="simple-icons:render" class="h-5 w-4 inline mb-2"} [Render](https://nitro.unjs.io/deploy/providers/render)
- :icon{name="ph:cloud-duotone" class="h-5 w-4 inline mb-2"} [Stormkit](https://nitro.unjs.io/deploy/providers/stormkit)
- :icon{name="simple-icons:vercel" class="h-5 w-4 inline mb-2 text-black dark:text-white"} [Vercel](https://nitro.unjs.io/deploy/providers/vercel)
## 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".

View File

@ -1,12 +1,10 @@
---
navigation.icon: uil:check-circle
title: Testing
description: How to test your Nuxt application.
navigation.icon: i-ph-check-circle-duotone
---
# Testing
How to test your Nuxt application.
::alert{icon=👉}
::callout
Test utils are still in development and the API and behavior may change. Currently, it is in preview stage but not yet ready for testing production apps.
If you are a module author, you can find more specific information in the [Module Author's guide](/docs/guide/going-further/modules#testing)
::
@ -15,15 +13,26 @@ In Nuxt 3, we have a rewritten version of `@nuxt/test-utils`. We support [Vitest
## Installation
```bash
::code-group
```bash [yarn]
yarn add --dev @nuxt/test-utils vitest
```
```bash [npm]
npm i --save-dev @nuxt/test-utils vitest
```
```bash [pnpm]
pnpm add --dev @nuxt/test-utils vitest
```
```bash [bun]
bun add --dev @nuxt/test-utils vitest
```
::
## Setup
In each `describe` block where you are taking advantage of the `@nuxt/test-utils` helper methods, you will need to set up the test context before beginning.
```ts
```ts [test/my-test.spec.ts]
import { describe, test } from 'vitest'
import { setup, $fetch } from '@nuxt/test-utils'
@ -40,89 +49,55 @@ describe('My test', async () => {
Behind the scenes, `setup` performs a number of tasks in `beforeAll`, `beforeEach`, `afterEach` and `afterAll` to set up the Nuxt test environment correctly.
## Options
Please the options below for the `setup` method.
### Nuxt Configuration
### 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'`
- `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'`
<!--
#### config
- `config`: Object with configuration overrides.
- Type: `NuxtConfig`
- Default: `{}` -->
Object with configuration overrides.
### Timings
* Type: `NuxtConfig`
* Default: `{}` -->
- `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: `60000`
### Setup Timings
### Features
#### `setupTimeout`
- `server`: Whether to launch a server to respond to requests in the test suite.
- Type: `boolean`
- Default: `true`
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).
- `port`: If provided, set the launched test server port to the value.
- Type: `number | undefined`
- Default: `undefined`
* Type: `number`
* Default: `60000`
### Features to Enable
#### `server`
Whether to launch a server to respond to requests in the test suite.
* Type: `boolean`
* Default: `true`
#### `port`
If provided, set the launched test server port to the value.
* Type: `number | undefined`
* Default: `undefined`
#### `build`
Whether to run a separate build step.
* Type: `boolean`
* Default: `true` (`false` if `browser` or `server` is disabled)
#### `browser`
Under the hood, Nuxt test utils uses [`playwright`](https://playwright.dev/) to carry out browser testing. If this option is set, a browser will be launched and can be controlled in the subsequent test suite. (More info can be found [here](/docs/getting-started/testing).)
* 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).
#### `runner`
Specify the runner for the test suite. Currently, [Vitest](https://vitest.dev/) is recommended.
* Type: `'vitest' | 'jest'`
* Default: `'vitest'`
- `build`: Whether to run a separate build step.
- Type: `boolean`
- Default: `true` (`false` if `browser` or `server` is disabled)
- `browser`: Under the hood, Nuxt test utils uses [`playwright`](https://playwright.dev/) 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).
- `runner`: Specify the runner for the test suite. Currently, [Vitest](https://vitest.dev/) is recommended.
- Type: `'vitest' | 'jest'`
- Default: `'vitest'`
## APIs
### APIs for Rendering Testing
#### `$fetch(url)`
### `$fetch(url)`
Get the HTML of a server-rendered page.
@ -132,7 +107,7 @@ import { $fetch } from '@nuxt/test-utils'
const html = await $fetch('/')
```
#### `fetch(url)`
### `fetch(url)`
Get the response of a server-rendered page.
@ -143,7 +118,7 @@ const res = await fetch('/')
const { body, headers } = res
```
#### `url(path)`
### `url(path)`
Get the full URL for a given page (including the port the test server is running on.)
@ -156,6 +131,6 @@ const pageUrl = url('/page')
## Testing in a Browser
::alert{icon=🚧}
::callout
We are working on it, stay tuned!
::

View File

@ -1,14 +1,25 @@
---
navigation.icon: uil:arrow-up
description: Have a Nuxt 2 project to migrate? Use these guides to upgrade your applications to Nuxt 3.
title: Upgrade Guide
description: 'Learn how to upgrade to the lastest Nuxt version.'
navigation.icon: i-ph-arrow-circle-up-duotone
---
# Upgrade Guide
Have a Nuxt 2 project to migrate? Use these guides to upgrade your Nuxt applications to Nuxt 3 or take the first step in that direction with Nuxt Bridge.
If you are already using Nuxt 3 and want to upgrade to the latest release or test new features before their release, head over to the [Upgrading Nuxt 3](#upgrading-nuxt-3) section.
## Upgrading Nuxt 3
## Feature Comparison
### Latest release
To upgrade Nuxt 3 to the [latest release](https://github.com/nuxt/nuxt/releases), use the `nuxi upgrade` command.
```bash [Terminal]
npx nuxi upgrade
```
### Nightly Release Channel
To use the latest Nuxt 3 build and test features before their release, read about the [nightly release channel](/docs/guide/going-further/nightly-release-channel) guide.
## Nuxt 2 vs Nuxt 3
In the table below, there is a quick comparison between 3 versions of Nuxt:
@ -34,34 +45,14 @@ Static sites | ✅ | ✅ | ✅
The migration guide provides a step-by-step comparison of Nuxt 2 features to Nuxt 3 features and guidance to adapt your current application.
::alert{type=info}
👉 Check out the [**guide to migrating from Nuxt 2 to Nuxt 3**](/docs/migration/overview).
::
::alert{type=info}
:rocket: Migrate with confidence with our [official Nuxt 2 to Nuxt 3 workshop](/support/workshop).
::read-more{to="/docs/migration/overview"}
Check out the **guide to migrating from Nuxt 2 to Nuxt 3**.
::
## Nuxt 2 to Nuxt Bridge
If you prefer to progressively migrate your Nuxt 2 application to Nuxt 3, you can use Nuxt Bridge. Nuxt Bridge is a compatibility layer that allows you to use Nuxt 3 features in Nuxt 2 with an opt-in mechanism.
::alert{type=info icon=👉}
[**Migrate from Nuxt 2 to Nuxt Bridge**](/docs/bridge/overview)
::
## Upgrading Nuxt 3
### Latest Release
To upgrade Nuxt 3 to the [latest release](/docs/community/changelog), use the `nuxi upgrade` command.
```bash
npx nuxi upgrade
```
### Nightly Release Channel
::alert{type=info icon=👉}
To use the latest Nuxt 3 build and test features before their release, read about the [nightly release channel](/docs/guide/going-further/nightly-release-channel) guide.
::read-more{to="/docs/bridge/overview"}
**Migrate from Nuxt 2 to Nuxt Bridge**
::

View File

@ -1,22 +1,20 @@
---
navigation.icon: uil:play-circle
title: 'Installation'
description: 'Get started with Nuxt quickly with our online starters or start locally with your terminal.'
navigation.icon: i-ph-play-duotone
---
# Installation
Get started with Nuxt quickly with our online starters or start locally with your terminal.
## Play Online
You can start playing with Nuxt 3 in your browser using our online sandboxes:
:button-link[Play on StackBlitz]{href="https://nuxt.new/s/v3" blank .mr-2}
:button-link[Play on CodeSandbox]{href="https://nuxt.new/c/v3" blank}
::card-group
:card{title="Open on StackBlitz" icon="i-simple-icons-stackblitz" to="https://nuxt.new/s/v3" target="_blank"}
:card{title="Open on CodeSandbox" icon="i-simple-icons-codesandbox" to="https://nuxt.new/c/v3" target="_blank"}
::
Start with one of our starters and themes directly by opening [nuxt.new](https://nuxt.new).
:button-link[Discover nuxt.new]{href="https://nuxt.new" blank}
## New Project
<!-- TODO: need to fix upstream in nuxt/nuxt.com -->
@ -27,24 +25,23 @@ Start with one of our starters and themes directly by opening [nuxt.new](https:/
- **Text editor** - We recommend [Visual Studio Code](https://code.visualstudio.com/) with the [Volar Extension](https://marketplace.visualstudio.com/items?itemName=Vue.volar)
- **Terminal** - In order to run Nuxt commands
::alert
::details
:summary[Additional notes for an optimal setup:]
- **Node.js**: Make sure to use an even numbered version (18, 20, etc)
- **Nuxtr**: Install the community-developed [Nuxtr extension](https://marketplace.visualstudio.com/items?itemName=Nuxtr.nuxtr-vscode)
- **Volar**: Either enable [**Take Over Mode**](https://vuejs.org/guide/typescript/overview.html#volar-takeover-mode) (recommended) or add the [TypeScript Vue Plugin](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin)
::callout
::details
:summary[Additional notes for an optimal setup:]
- **Node.js**: Make sure to use an even numbered version (18, 20, etc)
- **Nuxtr**: Install the community-developed [Nuxtr extension](https://marketplace.visualstudio.com/items?itemName=Nuxtr.nuxtr-vscode)
- **Volar**: Either enable [**Take Over Mode**](https://vuejs.org/guide/typescript/overview.html#volar-takeover-mode) (recommended) or add the [TypeScript Vue Plugin](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin)
If you have enabled **Take Over Mode** or installed the **TypeScript Vue Plugin (Volar)**, you can disable generating the shim for `*.vue` files in your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file:
If you have enabled **Take Over Mode** or installed the **TypeScript Vue Plugin (Volar)**, you can disable generating the shim for `*.vue` files in your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
```ts [nuxt.config.ts]
export default defineNuxtConfig({
typescript: {
shim: false
}
})
```
::
})
```
::
::
Open a terminal (if you're using [Visual Studio Code](https://code.visualstudio.com/), you can open an [integrated terminal](https://code.visualstudio.com/docs/editor/integrated-terminal)) and use the following command to create a new starter project:
@ -67,7 +64,7 @@ bunx nuxi@latest init <project-name>
Open your project folder in Visual Studio Code:
```bash
```bash [Terminal]
code <project-name>
```
@ -115,10 +112,9 @@ pnpm dev -o
```bash [bun]
bun run dev -o
```
::
::alert{type=success icon=✨ .font-bold}
::callout{icon="i-ph-check-circle-duotone"}
Well done! A browser window should automatically open for <http://localhost:3000>.
::
@ -126,4 +122,4 @@ Well done! A browser window should automatically open for <http://localhost:3000
Now that you've created your Nuxt 3 project, you are ready to start building your application.
- Learn about the framework [concepts](/docs/guide/concepts/auto-imports)
:read-more{title="Nuxt Concepts" to="/docs/guide/concepts"}

View File

@ -1,9 +1,9 @@
---
navigation.icon: uil:wrench
description: Nuxt is configured with sensible defaults. The config file can override or extend them.
title: Configuration
description: Nuxt is configured with sensible defaults to make you productive.
navigation.icon: i-ph-gear-duotone
---
# Configuration
By default, Nuxt is configured to cover most use cases. The [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file can override or extend this default configuration.
@ -21,11 +21,11 @@ export default defineNuxtConfig({
This file will often be mentioned in the documentation, for example to add custom scripts, register modules or change rendering modes.
::alert{type=info}
Every configuration option is described in the [Configuration Reference](/docs/api/configuration/nuxt-config).
::read-more{to="/docs/api/configuration/nuxt-config"}
Every option is described in the **Configuration Reference**.
::
::alert{type=info}
::callout
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.
::
@ -46,7 +46,7 @@ export default defineNuxtConfig({
})
```
::alert{type=info}
::callout
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.
::
@ -71,14 +71,14 @@ export default defineNuxtConfig({
})
```
```text [.env]
```bash [.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`](/docs/api/composables/use-runtime-config) composable.
These variables are exposed to the rest of your application using the [`useRuntimeConfig()`](/docs/api/composables/use-runtime-config) composable.
```vue [pages/index.vue]
<script setup lang="ts">
@ -86,7 +86,7 @@ const runtimeConfig = useRuntimeConfig()
</script>
```
:ReadMore{link="/docs/guide/going-further/runtime-config"}
:read-more{to="/docs/guide/going-further/runtime-config"}
## App Configuration
@ -114,7 +114,7 @@ const appConfig = useAppConfig()
</script>
```
:ReadMore{link="/docs/guide/directory-structure/app-config"}
:read-more{to="/docs/guide/directory-structure/app-config"}
## `runtimeConfig` vs `app.config`
@ -139,10 +139,10 @@ Nuxt uses [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file a
Name | Config File | How To Configure
|---------------------------------------------|---------------------------|-------------------------
| [Nitro](https://nitro.unjs.io/) | ~~`nitro.config.ts`~~ | Use [`nitro`](/docs/api/configuration/nuxt-config#nitro) key in `nuxt.config`
| [PostCSS](https://postcss.org) | ~~`postcss.config.js`~~ | Use [`postcss`](/docs/api/configuration/nuxt-config#postcss) key in `nuxt.config`
| [Vite](https://vitejs.dev) | ~~`vite.config.ts`~~ | Use [`vite`](/docs/api/configuration/nuxt-config#vite) key in `nuxt.config`
| [webpack](https://webpack.js.org/) | ~~`webpack.config.ts`~~ | Use [`webpack`](/docs/api/configuration/nuxt-config#webpack-1) key in `nuxt.config`
| [Nitro](https://nitro.unjs.io/) | ~~`nitro.config.ts`~~ | Use [`nitro`](/docs/api/nuxt-config#nitro) key in `nuxt.config`
| [PostCSS](https://postcss.org) | ~~`postcss.config.js`~~ | Use [`postcss`](/docs/api/nuxt-config#postcss) key in `nuxt.config`
| [Vite](https://vitejs.dev) | ~~`vite.config.ts`~~ | Use [`vite`](/docs/api/nuxt-config#vite) key in `nuxt.config`
| [webpack](https://webpack.js.org/) | ~~`webpack.config.ts`~~ | Use [`webpack`](/docs/api/nuxt-config#webpack-1) key in `nuxt.config`
Here is a list of other common config files:
@ -177,7 +177,7 @@ export default defineNuxtConfig({
})
```
:ReadMore{link="/docs/guide/directory-structure/nuxt.config#vue"}
:read-more{to="/docs/api/configuration/nuxt-config#vue"}
### With webpack
@ -195,7 +195,7 @@ export default defineNuxtConfig({
})
```
:ReadMore{link="/docs/guide/directory-structure/nuxt.config#loaders"}
:read-more{to="/docs/api/configuration/nuxt-config#loaders"}
### Enabling Experimental Vue Features
@ -210,4 +210,4 @@ export default defineNuxtConfig({
})
```
:ReadMore{link="/docs/guide/directory-structure/nuxt.config#vue-1"}
:read-more{to="/docs/api/configuration/nuxt-config#vue-1"}

View File

@ -1,14 +1,12 @@
---
navigation.icon: uil:window-section
title: 'Views'
description: 'Nuxt provides several component layers to implement the user interface of your application.'
navigation.icon: i-ph-layout-duotone
---
# Views
Nuxt provides several component layers to implement the user interface of your application.
## `app.vue`
![The `app.vue` file is the entry point of your application](/assets/docs/getting-started/views/app.svg)
![The app.vue file is the entry point of your application](/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.
@ -20,7 +18,7 @@ By default, Nuxt will treat this file as the **entrypoint** and render its conte
</template>
```
::alert
::callout
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.
::
@ -28,7 +26,7 @@ If you are familiar with Vue, you might wonder where `main.js` is (the file that
![Components are reusable pieces of UI](/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 [`components/` directory](/docs/guide/directory-structure/components), and they will be automatically available across your application without having to explicitly import them.
Most components are reusable pieces of the user interface, like buttons and menus. In Nuxt, you can create these components in the [`components/`](/docs/guide/directory-structure/components) directory, and they will be automatically available across your application without having to explicitly import them.
::code-group
@ -57,9 +55,9 @@ Most components are reusable pieces of the user interface, like buttons and menu
![Pages are views tied to a specific route](/assets/docs/getting-started/views/pages.svg)
Pages represent views for each specific route pattern. Every file in the [`pages/` directory](/docs/guide/directory-structure/pages) represents a different route displaying its content.
Pages represent views for each specific route pattern. Every file in the [`pages/`](/docs/guide/directory-structure/pages) directory represents a different route displaying its content.
To use pages, create `pages/index.vue` file and add `<NuxtPage />` component to the `app.vue` (or remove `app.vue` for default entry). You can now create more pages and their corresponding routes by adding new files in the [`pages/` directory](/docs/guide/directory-structure/pages).
To use pages, create `pages/index.vue` file and add `<NuxtPage />` component to the [`app.vue`](/docs/guide/directory-structure/app) (or remove `app.vue` for default entry). You can now create more pages and their corresponding routes by adding new files in the [`pages/`](/docs/guide/directory-structure/pages) directory.
::code-group
@ -84,9 +82,7 @@ To use pages, create `pages/index.vue` file and add `<NuxtPage />` component to
::
::alert
You will learn more about pages in the [Routing section](/docs/getting-started/routing)
::
:read-more{title="Routing Section" to="/docs/getting-started/routing"}
## Layouts
@ -94,8 +90,8 @@ You will learn more about pages in the [Routing section](/docs/getting-started/r
Layouts are wrappers around pages that contain a common User Interface for several pages, such as a header and footer display. Layouts are Vue files using `<slot />` components to display the **page** content. The `layouts/default.vue` file will be used by default. Custom layouts can be set as part of your page metadata.
::alert
If you only have a single layout in your application, we recommend using app.vue with the [`<NuxtPage />` component](/docs/api/components/nuxt-page) instead.
::callout
If you only have a single layout in your application, we recommend using [`app.vue`](/docs/guide/directory-structure/app) with [`<NuxtPage />`](/docs/api/components/nuxt-page) instead.
::
::code-group
@ -135,8 +131,8 @@ If you want to create more layouts and learn how to use them in your pages, find
## Advanced: Extending the HTML template
::alert{type=info}
If you only need to modify the head, you can refer to the [SEO and meta section](/docs/getting-started/seo-meta).
::callout
If you only need to modify the `<head>`, you can refer to the [SEO and meta section](/docs/getting-started/seo-meta).
::
You can have full control over the HTML template by adding a Nitro plugin that registers a hook.
@ -154,4 +150,4 @@ export default defineNitroPlugin((nitroApp) => {
})
```
:ReadMore{link="/docs/guide/going-further/hooks"}
:read-more{to="/docs/guide/going-further/hooks"}

View File

@ -1,19 +1,19 @@
---
navigation.icon: uil:image
title: 'Assets'
description: 'Nuxt offers two options for your assets.'
navigation.icon: i-ph-image-duotone
---
# Assets
Nuxt uses two directories to handle assets like stylesheets, fonts or images.
- The [`public/` directory](/docs/guide/directory-structure/public) content is served at the server root as-is.
- The [`assets/` directory](/docs/guide/directory-structure/assets) contains by convention every asset that you want the build tool (Vite or webpack) to process.
- The [`public/`](/docs/guide/directory-structure/public) directory content is served at the server root as-is.
- The [`assets/`](/docs/guide/directory-structure/assets) directory contains by convention every asset that you want the build tool (Vite or webpack) to process.
## `public/` Directory
## Public Directory
The [`public/` directory](/docs/guide/directory-structure/public) is used as a public server for static assets publicly available at a defined URL of your application.
The [`public/`](/docs/guide/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/` directory](/docs/guide/directory-structure/public) from your application's code or from a browser by the root URL `/`.
You can get a file in the [`public/`](/docs/guide/directory-structure/public) directory from your application's code or from a browser by the root URL `/`.
### Example
@ -25,13 +25,13 @@ For example, referencing an image file in the `public/img/` directory, available
</template>
```
## `assets/` Directory
## Assets Directory
Nuxt uses [Vite](https://vitejs.dev/guide/assets.html) or [webpack](https://webpack.js.org/guides/asset-management/) 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://vitejs.dev/plugins/) (for Vite) or [loaders](https://webpack.js.org/loaders/) (for webpack) to process other kind of assets, like stylesheets, fonts or SVG. This step transforms the original file mainly for performance or caching purposes (such as stylesheets minification or browser cache invalidation).
Nuxt uses [Vite](https://vitejs.dev/guide/assets.html) (default) or [webpack](https://webpack.js.org/guides/asset-management/) 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://vitejs.dev/plugins/) (for Vite) or [loaders](https://webpack.js.org/loaders/) (for webpack) to process other kind of assets, like stylesheets, fonts or SVG. This step transforms the original file mainly for performance or caching purposes (such as stylesheets minification or browser cache invalidation).
By convention, Nuxt uses the [`assets/` directory](/docs/guide/directory-structure/assets) to store these files but there is no auto-scan functionality for this directory, and you can use any other name for it.
By convention, Nuxt uses the [`assets/`](/docs/guide/directory-structure/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 [`assets/` directory](/docs/guide/directory-structure/assets) by using the `~/assets/` path.
In your application's code, you can reference a file located in the [`assets/`](/docs/guide/directory-structure/assets) directory by using the `~/assets/` path.
### Example
@ -43,13 +43,13 @@ For example, referencing an image file that will be processed if a build tool is
</template>
```
::alert{type=info icon=💡}
Nuxt won't serve files in the [`assets/` directory](/docs/guide/directory-structure/assets) at a static URL like `/assets/my-file.png`. If you need a static URL, use the [`public/` directory](#public-directory).
::callout
Nuxt won't serve files in the [`assets/`](/docs/guide/directory-structure/assets) directory at a static URL like `/assets/my-file.png`. If you need a static URL, use the [`public/`](#public-directory) directory.
::
### Global Styles Imports
To globally insert statements in your Nuxt components styles, you can use the [`Vite`](/docs/api/configuration/nuxt-config#vite) option at your [`nuxt.config`](/docs/api/configuration/nuxt-config) file.
To globally insert statements in your Nuxt components styles, you can use the [`Vite`](/docs/api/nuxt-config#vite) option at your [`nuxt.config`](/docs/api/nuxt-config) file.
#### Example

View File

@ -1,9 +1,9 @@
---
navigation.icon: uil:palette
title: 'Styling'
description: 'Learn how to style your Nuxt application.'
navigation.icon: i-ph-palette-duotone
---
# 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.
@ -30,7 +30,7 @@ import('~/assets/css/first.css')
</style>
```
::alert{type=info}
::callout
The stylesheets will be inlined in the HTML rendered by Nuxt.
::
@ -45,7 +45,7 @@ export default defineNuxtConfig({
})
```
::alert{type=info}
::callout
The stylesheets will be inlined in the HTML rendered by Nuxt, injected globally and present in all pages.
::
@ -77,7 +77,7 @@ h1 {
You can also reference stylesheets that are distributed through npm. Let's use the popular `animate.css` library as an example.
```bash
```bash [Terminal]
npm install animate.css
```
@ -105,7 +105,7 @@ export default defineNuxtConfig({
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 like this.
You can manipulate the head with the [`app.head`](/docs/api/configuration/nuxt-config#head) property of your Nuxt configuration:
You can manipulate the head with the [`app.head`](/docs/api/nuxt-config#head) property of your Nuxt configuration:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@ -120,8 +120,7 @@ export default defineNuxtConfig({
You can use the useHead composable to dynamically set a value in your head in your code.
::ReadMore{link="/docs/api/composables/use-head"}
::
:read-more{to="/docs/api/composables/use-head"}
```ts
useHead({
@ -184,7 +183,7 @@ export default defineNuxtConfig({
})
```
::alert{type=info}
::callout
In both cases, the compiled stylesheets will be inlined in the HTML rendered by Nuxt.
::
@ -453,24 +452,23 @@ Use different styles for different layouts.
</style>
```
::ReadMore{link="/docs/guide/directory-structure/layouts"}
::
:read-more{to="/docs/guide/directory-structure/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/) or [Tailwind CSS](https://tailwindcss.com/).
The community and the Nuxt team have developed plenty of Nuxt modules to makes the integration easier.
You can discover them on the [modules section](https://nuxt.com/modules) of the website.
You can discover them on the [modules section](/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
- [UnoCSS](/modules/unocss): Instant on-demand atomic CSS engine
- [Tailwind CSS](/modules/tailwindcss): Utility-first CSS framework
- [Fontaine](https://github.com/nuxt-modules/fontaine): Font metric fallback
- [Pinceau](https://pinceau.dev/): Adaptable styling framework
- [Nuxt UI](https://ui.nuxt.com): A UI Library for Modern Web Apps
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](/docs/guide/directory-structure/plugins) and/or [make your own module](/docs/guide/going-further/modules). Share them with the [community](https://nuxt.com/modules) if you do!
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](/docs/guide/directory-structure/plugins) and/or [make your own module](/docs/guide/going-further/modules). Share them with the [community](/modules) if you do!
### Easily Load Webfonts
@ -484,14 +482,13 @@ If you are using [UnoCSS](https://unocss.dev/integrations/nuxt), note that it co
Nuxt comes with the same `<Transition>` element that Vue has, and also has support for the experimental [View Transitions API](/docs/getting-started/transitions#view-transitions-api-experimental).
::ReadMore{link="/docs/features/transitions"}
::
:read-more{to="/docs/getting-started/transitions"}
### Font Advanced Optimization
We would recommend using [Fontaine](https://github.com/nuxt-modules/fontaine) to reduce your [CLS](https://web.dev/cls/). If you need something more advanced, consider creating a Nuxt module to extend the build process or the Nuxt runtime.
::alert{type="info"}
::callout
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!
::

View File

@ -1,10 +1,10 @@
---
navigation.icon: uil:sign-alt
title: 'Routing'
description: Nuxt file-system routing creates a route for every file in the pages/ directory.
navigation.icon: i-ph-signpost-duotone
---
# Routing
One core feature of Nuxt is the file system router. Every Vue file inside the [`pages/` directory](/docs/guide/directory-structure/pages) 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.
One core feature of Nuxt is the file system router. Every Vue file inside the [`pages/`](/docs/guide/directory-structure/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
@ -14,15 +14,15 @@ This file system routing uses naming conventions to create dynamic and nested ro
::code-group
```text [pages/ directory]
pages/
--| about.vue
--| index.vue
--| posts/
----| [id].vue
```bash [Directory Structure]
| pages/
---| about.vue
---| index.vue
---| posts/
-----| [id].vue
```
```js [Generated Router file]
```json [Generated Router File]
{
"routes": [
{
@ -43,13 +43,13 @@ pages/
::
:ReadMore{link="/docs/guide/directory-structure/pages"}
:read-more{to="/docs/guide/directory-structure/pages"}
## Navigation
The `<NuxtLink>` component links pages between them. It renders an `<a>` 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.
The [`<NuxtLink>`](/docs/api/components/nuxt-link) component links pages between them. It renders an `<a>` 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 `<NuxtLink>` 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.
When a [`<NuxtLink>`](/docs/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 [pages/app.vue]
<template>
@ -65,11 +65,11 @@ When a `<NuxtLink>` enters the viewport on the client side, Nuxt will automatica
</template>
```
:ReadMore{link="/docs/api/components/nuxt-link"}
:read-more{to="/docs/api/components/nuxt-link"}
## Route Parameters
The `useRoute()` composable can be used in a `<script setup>` block or a `setup()` method of a Vue component to access the current route details.
The [`useRoute()`](/docs/api/composables/use-route) composable can be used in a `<script setup>` block or a `setup()` method of a Vue component to access the current route details.
```vue [pages/posts/[id\\].vue]
<script setup lang="ts">
@ -80,20 +80,20 @@ console.log(route.params.id)
</script>
```
:ReadMore{link="/docs/api/composables/use-route"}
:read-more{to="/docs/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.
::alert{type=info}
::callout
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.
::
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 [`middleware/` directory](/docs/guide/directory-structure/middleware) 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`.)
2. Named route middleware, which are placed in the [`middleware/`](/docs/guide/directory-structure/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 [`middleware/` directory](/docs/guide/directory-structure/middleware) (with a `.global` suffix) and will be automatically run on every route change.
Example of an `auth` middleware protecting the `/dashboard` page:
@ -123,11 +123,11 @@ definePageMeta({
::
:ReadMore{link="/docs/guide/directory-structure/middleware"}
:read-more{to="/docs/guide/directory-structure/middleware"}
## Route Validation
Nuxt offers route validation via the `validate` property in [`definePageMeta`](/docs/api/utils/define-page-meta) in each page you wish to validate.
Nuxt offers route validation via the `validate` property in [`definePageMeta()`](/docs/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`, and another match can't be found, this will cause a 404 error. You can also directly return an object with `statusCode`/`statusMessage` to respond immediately with an error (other matches will not be checked).
@ -143,3 +143,5 @@ definePageMeta({
})
</script>
```
:read-more{to="/docs/api/utils/define-page-meta"}

View File

@ -1,19 +1,13 @@
---
navigation.icon: uil:file-search-alt
title: SEO and Meta
description: Improve your Nuxt app's SEO with powerful head config, composables and components.
navigation.icon: i-ph-file-search-duotone
---
# SEO and Meta
Improve your Nuxt app's SEO with powerful head config, composables and components.
## Defaults
Out-of-the-box, Nuxt provides sane defaults, which you can override if needed.
- `charset`: `utf-8`
- `viewport`: `width=device-width, initial-scale=1`
```ts [nuxt.config.ts]
export default defineNuxtConfig({
app: {
@ -25,9 +19,9 @@ export default defineNuxtConfig({
})
```
Providing an [`app.head`](/docs/api/configuration/nuxt-config#head) property in your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) allows you to customize the head for your entire app.
Providing an [`app.head`](/docs/api/nuxt-config#head) property in your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) allows you to customize the head for your entire app.
::alert{type=info}
::callout
This method does not allow you to provide reactive data. We recommend to use `useHead()` in `app.vue`.
::
@ -57,9 +51,9 @@ useHead({
We recommend to take a look at the [`useHead`](/docs/api/composables/use-head) and [`useHeadSafe`](/docs/api/composables/use-head-safe) composables.
## `useSeoMeta` and `useServerSeoMeta`
## `useSeoMeta`
The `useSeoMeta` and [`useServerSeoMeta`](/docs/api/composables/use-server-seo-meta) composables let you define your site's SEO meta tags as a flat object with full TypeScript support.
The [`useSeoMeta`](/docs/api/composables/use-seo-meta) composable lets you define your site's SEO meta tags as a flat object with full TypeScript support.
This helps you avoid typos and common mistakes, such as using `name` instead of `property`.
@ -76,7 +70,7 @@ useSeoMeta({
</script>
```
Read more on the [`useSeoMeta`](/docs/api/composables/use-seo-meta) and [`useServerSeoMeta`](/docs/api/composables/use-server-seo-meta) composables.
:read-more{to="/docs/api/composables/use-seo-meta"}
## Components
@ -108,7 +102,7 @@ const title = ref('Hello World')
## Types
Below are the non-reactive types used for [`useHead`](/docs/api/composables/use-head), [`app.head`](/docs/api/configuration/nuxt-config#head) and components.
Below are the non-reactive types used for [`useHead`](/docs/api/composables/use-head), [`app.head`](/docs/api/nuxt-config#head) and components.
```ts
interface MetaObject {
@ -226,7 +220,7 @@ Within your [`pages/` directory](/docs/guide/directory-structure/pages), you can
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]
```vue [pages/some-page.vue]
<script setup lang="ts">
definePageMeta({
title: 'Some Page'
@ -236,7 +230,7 @@ definePageMeta({
And then in your layout file, you might use the route's metadata you have previously set:
```vue{}[layouts/default.vue]
```vue [layouts/default.vue]
<script setup lang="ts">
const route = useRoute()
@ -246,9 +240,9 @@ useHead({
</script>
```
:LinkExample{link="/docs/examples/features/meta-tags"}
:link-example{to="/docs/examples/features/meta-tags"}
:ReadMore{link="/docs/guide/directory-structure/pages/#page-metadata"}
:read-more{to="/docs/guide/directory-structure/pages/#page-metadata"}
### Dynamic Title

View File

@ -1,11 +1,12 @@
---
navigation.icon: uil:moon-eclipse
description: Nuxt leverages Vue's Transition component to apply transitions between pages and layouts.
title: 'Transitions'
description: Apply transitions between pages and layouts with Vue or native browser View Transitions.
navigation.icon: i-ph-exclude-square-duotone
---
# Transitions
::callout
Nuxt leverages Vue's [`<Transition>`](https://vuejs.org/guide/built-ins/transition.html#the-transition-component) component to apply transitions between pages and layouts.
::
## Page transitions
@ -19,7 +20,7 @@ export default defineNuxtConfig({
})
```
::alert{type=warning}
::callout
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](/docs/getting-started/transitions#layout-transitions).
::
@ -245,7 +246,7 @@ export default defineNuxtConfig({
})
```
::alert{type="info"}
::callout
If you change the `name` property, you also have to rename the CSS classes accordingly.
::
@ -290,7 +291,7 @@ defineNuxtConfig({
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://greensock.com/gsap/) or [Tween.js](https://createjs.com/tweenjs).
This way presents perfect use-cases for JavaScript animation libraries such as [GSAP](https://gsap.com/).
```vue [pages/some-page.vue]
<script setup lang="ts">
@ -308,7 +309,7 @@ definePageMeta({
</script>
```
::alert{type="info"}
::callout
Learn more about additional [JavaScript hooks](https://vuejs.org/guide/built-ins/transition.html#javascript-hooks) available in the `Transition` component.
::
@ -405,7 +406,7 @@ When `<NuxtPage />` is used in `app.vue`, transition-props can be passed directl
</template>
```
::alert{type="warning"}
::callout
Remember, this page transition cannot be overridden with `definePageMeta` on individual pages.
::

View File

@ -1,11 +1,12 @@
---
navigation.icon: uil:channel
title: 'Data fetching'
description: Nuxt provides composables to handle data fetching within your application.
navigation.icon: i-ph-plugs-connected-duotone
---
# Data fetching
Nuxt comes with two composables and a built-in library to perform data-fetching in browser or server environments: `useFetch`, [`useAsyncData`](/docs/api/composables/use-async-data) and `$fetch`.
Nuxt comes with two composables and a built-in library to perform data-fetching in browser or server environments: `useFetch`, [`useAsyncData`](/docs/api/composables/use-async-data) and `$fetch` . In a nutshell:
In a nutshell:
- [`useFetch`](/docs/api/composables/use-fetch) is the most straightforward way to handle data fetching in a component setup function.
- [`$fetch`](/docs/api/utils/dollarfetch) is great to make network requests based on user interaction.
@ -17,7 +18,7 @@ Before that, it's imperative to know why these composables exist in the first pl
## Why using specific composables?
When using a framework like Nuxt that can perform calls and render pages on both client and server environments, some challenges must be addressed. This is why Nuxt provides composables to wrap your queries, instead of letting the developer rely on `$fetch` calls alone.
When using a framework like Nuxt that can perform calls and render pages on both client and server environments, some challenges must be addressed. This is why Nuxt provides composables to wrap your queries, instead of letting the developer rely on [`$fetch`](/docs/api/utils/dollarfetch) calls alone.
### Network calls duplication
@ -25,18 +26,14 @@ The [`useFetch`](/docs/api/composables/use-fetch) and [`useAsyncData`](/docs/api
The payload is a JavaScript object accessible through [`useNuxtApp().payload`](/docs/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.
::alert{icon=⚙️}
Use the [Nuxt DevTools](https://devtools.nuxt.com) to inspect this data in the payload tab.
::callout
Use the [Nuxt DevTools](https://devtools.nuxt.com) to inspect this data in the **Payload tab**.
::
### Suspense
Nuxt uses Vues [`<Suspense>`](https://vuejs.org/guide/built-ins/suspense) 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-calls basis.
::alert{icon=👉}
These composables are auto-imported and can be used in `setup` functions or lifecycle hooks
::
## `useFetch`
The [`useFetch`](/docs/api/composables/use-fetch) composable is the most straightforward way to perform data fetching.
@ -53,11 +50,9 @@ const { data: count } = await useFetch('/api/count')
This composable is a wrapper around the [`useAsyncData`](/docs/api/composables/use-async-data) composable and `$fetch` utility.
::ReadMore{link="/docs/api/composables/use-fetch"}
::
:read-more{to="/docs/api/composables/use-fetch"}
::LinkExample{link="/docs/examples/features/data-fetching"}
::
:link-example{to="/docs/examples/features/data-fetching"}
## `$fetch`
@ -67,7 +62,7 @@ Nuxt includes the `ofetch` library, and is auto-imported as the `$fetch` alias g
const users = await $fetch('/api/users').catch((error) => error.data)
```
::alert{type="warning"}
::callout
Beware that using only `$fetch` will not provide [network calls de-duplication and navigation prevention](#why-using-specific-composables). It is recommended to use `$fetch` when posting data to an event handler, when doing client-side only logic, or combined with `useAsyncData`.
::
@ -79,11 +74,12 @@ The `ofetch` library is built on top of [the `fetch` API](https://developer.mozi
- Auto-retry
- Interceptors
::alert{icon=📘}
[Read the full documentation of ofetch](https://github.com/unjs/ofetch)
::read-more{title="ofetch" to="https://github.com/unjs/ofetch" target="_blank"}
Read the full documentation of `ofetch`
::
::ReadMore{link="/docs/api/utils/dollarfetch"}
::read-more{to="/docs/api/utils/dollarfetch"}
Read more about `$fetch`
::
## `useAsyncData`
@ -123,7 +119,8 @@ const { data: discounts, pending } = await useAsyncData('cart-discount', async (
})
```
::ReadMore{link="/docs/api/composables/use-async-data"}
::read-more{to="/docs/api/composables/use-async-data"}
Read more about `useAsyncData`
::
## Options
@ -160,10 +157,12 @@ You can alternatively use [`useLazyFetch`](/docs/api/composables/use-lazy-fetch)
const { pending, data: posts } = useLazyFetch('/api/posts')
```
::ReadMore{link="/docs/api/composables/use-lazy-fetch"}
::read-more{to="/docs/api/composables/use-lazy-fetch"}
Read more about `useLazyFetch`
::
::ReadMore{link="/docs/api/composables/use-lazy-async-data"}
::read-more{to="/docs/api/composables/use-lazy-async-data"}
Read more about `useLazyAsyncData`
::
### Client-only fetching
@ -211,7 +210,7 @@ const { data: mountains } = await useFetch('/api/mountains', {
})
```
::alert{type="warning"}
::callout
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.
::
@ -224,7 +223,7 @@ Both `pick` and `transform` don't prevent the unwanted data from being fetched i
- [`useFetch`](/docs/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`](/docs/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.
::alert{icon=📘}
::callout
To get the cached data by key, you can use [`useNuxtData`](/docs/api/composables/use-nuxt-data)
::
@ -247,7 +246,7 @@ const { data, error, execute, refresh } = await useFetch('/api/users')
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](#not-immediate).
::alert{icon=📘}
::callout
To globally refetch or invalidate cached data, see [`clearNuxtData`](/docs/api/utils/clear-nuxt-data) and [`refreshNuxtData`](/docs/api/utils/refresh-nuxt-data).
::
@ -376,7 +375,7 @@ const { data } = await useFetch('/api/me', { headers })
</script>
```
::alert{type="warning"}
::callout
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`
@ -435,19 +434,18 @@ export default defineNuxtComponent({
</script>
```
::Alert
::callout
Using `<script setup lang="ts">` is the recommended way of declaring Vue components in Nuxt 3.
::
::ReadMore{link="/docs/api/utils/define-nuxt-component"}
::
:read-more{to="/docs/api/utils/define-nuxt-component"}
## Serialization
When fetching data from the `server` directory, the response is serialized using `JSON.stringify`. However, since serialization is limited to only JavaScript primitive types, Nuxt does its best to convert the return type of `$fetch` and [`useFetch`](/docs/api/composables/use-fetch) to match the actual value.
::alert{icon=👉}
You can learn more about `JSON.stringify` limitations [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description).
::read-more{icon="i-simple-icons-mdnwebdocs" color="gray" to="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description" target="_blank"}
Learn more about `JSON.stringify` limitations.
::
### Example

View File

@ -1,31 +1,29 @@
---
navigation.icon: uil:database
title: 'State Management'
description: Nuxt provides powerful state management libraries and the useState composable to create a reactive and SSR-friendly shared state.
navigation.icon: i-ph-database-duotone
---
# State Management
Nuxt provides the [`useState`](/docs/api/composables/use-state) composable to create a reactive and SSR-friendly shared state across components.
[`useState`](/docs/api/composables/use-state) is an SSR-friendly [`ref`](https://vuejs.org/api/reactivity-core.html#ref) replacement. Its value will be preserved after server-side rendering (during client-side hydration) and shared across all components using a unique key.
::ReadMore{link="/docs/api/composables/use-state"}
::callout
Because the data inside [`useState`](/docs/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.
::
::alert{icon=👉}
[`useState`](/docs/api/composables/use-state) only works during `setup` or [`Lifecycle Hooks`](https://vuejs.org/api/composition-api-lifecycle.html#composition-api-lifecycle-hooks).
::
::alert{type=warning}
Because the data inside [`useState`](/docs/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="/docs/api/composables/use-state"}
Read more about `useState` composable.
::
## Best Practices
::alert{type=danger icon=🚨}
::callout{color="amber" icon="i-ph-warning-duotone"}
Never define `const state = ref()` outside of `<script setup>` or `setup()` function.<br>
Such state will be shared across all users visiting your website and can lead to memory leaks!
::
::alert{type=success icon=✅}
::callout{color="green" icon="i-ph-check-circle-duotone"}
Instead use `const useX = () => useState('x')`
::
@ -53,24 +51,23 @@ const counter = useState('counter', () => Math.round(Math.random() * 1000))
</template>
```
::LinkExample{link="/docs/examples/features/state-management"}
::
:link-example{to="/docs/examples/features/state-management"}
::ReadMore{link="/docs/api/composables/use-state"}
::
::alert{icon=📘}
To globally invalidate cached state, see [`clearNuxtState`](/docs/api/utils/clear-nuxt-state).
::callout
To globally invalidate cached state, see [`clearNuxtState`](/docs/api/utils/clear-nuxt-state) util.
::
### Advanced Usage
In this example, we use a composable that detects the user's default locale from the HTTP request headers and keeps it in a `locale` state.
::code-group
```ts [composables/locale.ts]
import type { Ref } from 'vue'
export const useLocale = () => useState<string>('locale', () => useDefaultLocale().value)
export const useLocale = () => {
return useState<string>('locale', () => useDefaultLocale().value)
}
export const useDefaultLocale = (fallback = 'en-US') => {
const locale = ref(fallback)
@ -127,10 +124,10 @@ const date = useLocaleDate(new Date('2016-10-26'))
</div>
</template>
```
::LinkExample{link="/docs/examples/advanced/locale"}
::
:link-example{to="/docs/examples/advanced/locale"}
## Shared State
By using [auto-imported composables](/docs/guide/directory-structure/composables) we can define global type-safe states and import them across the app.

View File

@ -1,104 +1,88 @@
---
navigation.icon: uil:bug
title: 'Error Handling'
description: 'Learn how to catch and handle errors in Nuxt.'
navigation.icon: i-ph-bug-beetle-duotone
---
# Error handling
Learn how to catch errors in different lifecycle.
## Handling Errors
Nuxt 3 is a full-stack framework, which means there are several sources of unpreventable user runtime errors that can happen in different contexts:
1. Errors during the Vue rendering lifecycle (SSR + SPA)
1. Errors during API or Nitro server lifecycle
1. Server and client startup errors (SSR + SPA)
1. Errors downloading JS chunks
- Errors during the Vue rendering lifecycle (SSR & CSR)
- Errors during Nitro server lifecycle ([`server/`](/docs/guide/directory-structure/server) directory)
- Server and client startup errors (SSR + CSR)
- Errors downloading JS chunks
### Errors During the Vue Rendering Lifecycle (SSR + SPA)
::callout
**SSR** stands for **Server-Side Rendering** and **CSR** for **Client-Side Rendering**.
::
## Vue Rendering Lifecycle
You can hook into Vue errors using [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle.html#onerrorcaptured).
In addition, Nuxt provides a `vue:error` hook that will be called if any errors propagate up to the top level.
In addition, Nuxt provides a [`vue:error`](/docs/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.html#app-config-errorhandler). It will receive all Vue errors, even if they are handled.
#### Example With Global Error Reporting Framework
```js
```ts [plugins/error-handler.ts]
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.config.errorHandler = (error, context) => {
// ...
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
})
})
```
### Server and Client Startup Errors (SSR + SPA)
::callout
Note that the `vue:error` hook is based on [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle.html#onerrorcaptured) 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](/docs/guide/directory-structure/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
* running Nuxt plugins
* processing `app:created` and `app:beforeMount` hooks
* rendering your Vue app to HTML (on the server)
* 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 Lifecycle
### Errors During API or Nitro Server Lifecycle
You cannot currently define a server-side handler for these errors, but can render an error page, see the [Render an Error Page](#error-page) section.
You cannot currently define a server-side handler for these errors, but can render an error page (see the next section).
### Errors downloading JS chunks
## 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) for ideas.
## Rendering an Error Page
## Error Page
::callout
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.
This 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
An error 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`).
The lifecycle hooks are listed [here](/docs/api/advanced/hooks).
You can customize this error page by adding `~/error.vue` in the source directory of your application, alongside `app.vue`. Although it is called an 'error page' it's not a route and shouldn't be placed in your `~/pages` directory. For the same reason, you shouldn't use `definePageMeta` within this page.
The error page has a single prop - `error` which contains an error for you to handle.
The `error` object provides the fields: `url`, `statusCode`, `statusMessage`, `message`, `description` and `data`. If you have an error with custom fields they will be lost; you should assign them to `data` instead. For custom errors we highly recommend to use `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
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.hook('vue:error', (err) => {
//
})
})
```
When you are ready to remove the error page, you can call the `clearError` helper function, which takes an optional path to redirect to (for example, if you want to navigate to a 'safe' page).
::alert{type="warning"}
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.
::
::alert{type="warning"}
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). We recommend using a newer version of Node as Node 16 will reach end-of-life in September 2023.
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="/docs/api/advanced/hooks"}
Discover all the Nuxt lifecycle hooks.
::
### Example
Customize the default error page by adding `~/error.vue` in the source directory of your application, alongside `app.vue`.
```vue [error.vue]
<script setup lang="ts">
@ -110,78 +94,145 @@ const handleError = () => clearError({ redirect: '/' })
</script>
<template>
<div>
<h2>{{ error.statusCode }}</h2>
<button @click="handleError">Clear errors</button>
</div>
</template>
```
## Error Helper Methods
::callout
Although it is called an 'error page' it's not a route and shouldn't be placed in your `~/pages` directory. For the same reason, you shouldn't use `definePageMeta` within this page.
::
The error page has a single prop - `error` which contains an error for you to handle.
The `error` object provides the fields:
```ts
{
url: string
statusCode: number
statusMessage: string
message: string
description: string
data: any
}
```
If you have an error with custom fields they will be lost; you should assign them to `data` instead:
```ts
throw createError({
statusCode: 404,
statusMessage: 'Page Not Found',
data: {
myCustomField: true
}
})
```
For custom errors we highly recommend to use `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]
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.hook('vue:error', (err) => {
//
})
})
```
When you are ready to remove the error page, you can call the [`clearError`](/docs/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).
::callout
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.
::
::callout
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). We recommend using a newer version of Node as Node 16 reached end-of-life in September 2023.
::
## Error Utils
### `useError`
* `function useError (): Ref<Error | { url, statusCode, statusMessage, message, description, data }>`
```ts [TS Signature]
function useError (): Ref<Error | { url, statusCode, statusMessage, message, description, data }>
```
This function will return the global Nuxt error that is being handled.
::ReadMore{link="/docs/api/composables/use-error"}
::read-more{to="/docs/api/composables/use-error"}
Read more about `useError` composable.
::
### `createError`
* `function createError (err: { cause, data, message, name, stack, statusCode, statusMessage, fatal }): Error`
```ts [TS Signature]
function createError (err: { cause, data, message, name, stack, statusCode, statusMessage, fatal }): Error
```
You can use this function to create an error object with additional metadata. It is usable in both the Vue and Nitro portions of your app, and is meant to be thrown.
Create an error object with additional metadata. 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`.
* 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`.
### Example
- on server-side, it will trigger a full-screen error page which you can clear with [`clearError`](#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]
<script setup lang="ts">
const route = useRoute()
const { data } = await useFetch(`/api/movies/${route.params.slug}`)
if (!data.value) {
throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
throw createError({
statusCode: 404,
statusMessage: 'Page Not Found'
})
}
</script>
```
::read-more{to="/docs/api/utils/create-error"}
Read more about `createError` util.
::
### `showError`
* `function showError (err: string | Error | { statusCode, statusMessage }): Error`
```ts [TS Signature]
function showError (err: string | Error | { statusCode, statusMessage }): 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`.
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`](#clearerror).
It is recommended instead to use `throw createError()`.
::ReadMore{link="/docs/api/utils/show-error"}
::read-more{to="/docs/api/utils/show-error"}
Read more about `showError` util.
::
### `clearError`
* `function clearError (options?: { redirect?: string }): Promise<void>`
```ts [TS Signature]
function clearError (options?: { redirect?: string }): Promise<void>
```
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).
::ReadMore{link="/docs/api/utils/clear-error"}
::read-more{to="/docs/api/utils/clear-error"}
Read more about `clearError` util.
::
## Rendering Errors Within Your App
## Render Error in Component
Nuxt also provides a `<NuxtErrorBoundary>` component that allows you to handle client-side errors within your app, without replacing your entire site with an error page.
Nuxt also provides a [`<NuxtErrorBoundary>`](/docs/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.)
::alert{type="info"}
::callout
If you navigate to another route, the error will be cleared automatically.
::
### Example
```vue [pages/index.vue]
<template>
<!-- some content -->
@ -197,5 +248,4 @@ If you navigate to another route, the error will be cleared automatically.
</template>
```
::LinkExample{link="/docs/examples/advanced/error-handling"}
::
:link-example{to="/docs/examples/advanced/error-handling"}

View File

@ -1,14 +1,12 @@
---
navigation.icon: uil:laptop-connection
title: 'Server'
description: Build full-stack applications, fetch data from your database, create APIs, or even generate static server-side content like a sitemap or a RSS feed, from a single codebase.
navigation.icon: i-ph-computer-tower-duotone
---
# Server
Nuxt's server framework allows you to build **full-stack applications**. For example, you can fetch data from a database or another server, create an API or even generate static server-side content like a sitemap or an RSS feed - all from a single codebase.
::ReadMore{link="/docs/guide/directory-structure/server"}
::
:read-more{to="/docs/guide/directory-structure/server"}
## Powered by Nitro
@ -27,7 +25,7 @@ With Nitro, you can easily manage the server part of your Nuxt app, from API end
Both endpoints and middleware can be defined like this:
```ts [server/api/test.ts]
export default defineEventHandler({
export default defineEventHandler(async (event) => {
// ... Do whatever you want here
})
```
@ -36,27 +34,30 @@ And you can directly return `text`, `json`, `html` or even a `stream`.
Out-of-the-box, Nitro supports **hot module replacement** and **auto-import** like the other parts of your Nuxt application.
::ReadMore{link="/docs/guide/directory-structure/server"}
::
:read-more{to="/docs/guide/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="/blog/nuxt-on-the-edge"}
Today, Nitro offers more than 15 presets to build your Nuxt app for different cloud providers and servers, including:
- [Cloudflare Workers](https://workers.cloudflare.com/)
- [Netlify Functions](https://www.netlify.com/products/functions/)
- [Vercel Edge Network](https://vercel.com/docs/edge-network/introduction)
- [Lagon](https://lagon.app/)
Or for other runtimes:
- [Deno](https://deno.land/)
- [Bun](https://bun.sh/)
::ReadMore{link="/docs/getting-started/deployment"}
::card-group
:card{icon="i-logos-deno" title="Deno" to="https://deno.land" target="_blank"}
:card{icon="i-logos-bun" title="Bun" to="https://bun.sh" target="_blank"}
::
:read-more{to="/docs/getting-started/deployment"}
## Hybrid Rendering
Do you need both static and dynamic pages in your Nuxt app? Nitro has your back!
@ -66,21 +67,27 @@ Nitro has a powerful feature called `routeRules` which allows you to define a se
```ts [nuxt.config.ts]
export default defineNuxtConfig({
routeRules: {
'/': { prerender: true }, // Generated at build time for SEO purpose
'/api/*': { cache: { maxAge: 60 * 60 } }, // Cached for 1 hour
'/old-page': { redirect: { to: '/new-page', statusCode: 302 } } // Redirection to avoid 404
// 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 }
}
// ...
}
})
```
[More rules are available](https://nuxt.com/docs/guide/concepts/rendering#hybrid-rendering) to customize the rendering mode of your routes.
::read-more{to="/docs/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` and `experimentalNoScripts`) that are not Nitro rules but affect Nuxt's behavior when rendering your pages to HTML.
In addition, there are some route rules (for example, `ssr` and `experimentalNoScripts`) that are not Nuxt specific to change the behavior when rendering your pages to HTML.
Some route rules (`redirect` and `prerender`) also affect client-side behavior.
Nitro is used to build the app for server side rendering, as well as pre-rendering.
::ReadMore{link="/docs/guide/concepts/rendering"}
::
:read-more{to="/docs/guide/concepts/rendering"}

View File

@ -1,24 +1,23 @@
---
navigation.icon: uil:layer-group
title: 'Layers'
description: Nuxt provides a powerful system that allows you to extend the default files, configs, and much more.
navigation.icon: i-ph-stack-duotone
---
# Layers
One of the core features of Nuxt 3 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.
Some use cases:
## Use Cases
::list{type="success"}
- Share reusable configuration presets across projects using `nuxt.config` and `app.config`
- Create a component library using [`components/` directory](/docs/guide/directory-structure/components)
- Create utility and composable library using [`composables/` directory](/docs/guide/directory-structure/composables) and [`utils/` directory](/docs/guide/directory-structure/utils)
- Create [Nuxt themes](https://github.com/nuxt-themes)
- Create a component library using [`components/`](/docs/guide/directory-structure/components) directory
- Create utility and composable library using [`composables/`](/docs/guide/directory-structure/composables) and [`utils/`](/docs/guide/directory-structure/utils) directories
- Create Nuxt module presets
- Share standard setup across projects
::
- Create [Nuxt themes](https://github.com/nuxt-themes)
You can extend a layer by adding the [extends](/docs/api/configuration/nuxt-config#extends) property to the [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file.
## Usage
You can extend a layer by adding the [extends](/docs/api/nuxt-config#extends) property to the [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file.
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@ -30,13 +29,13 @@ export default defineNuxtConfig({
})
```
A quick video made by [Learn Vue](https://go.learnvue.co) to showcase the power of `extends`:
::read-more{to="/docs/guide/going-further/layers"}
Read more about layers in the **Layer Author Guide**.
::
:video-player{src="https://www.youtube.com/watch?v=lnFCM7c9f7I"}
## Authoring Nuxt Layers
See [Layer Author Guide](/docs/guide/going-further/layers) to learn more.
::callout{color="blue" icon="i-ph-video-duotone" to="https://www.youtube.com/watch?v=lnFCM7c9f7I" target="_blank"}
Watch Learn Vue video about Nuxt Layers.
::
## Examples

View File

@ -1,3 +1,3 @@
title: Get Started
titleTemplate: '%s · Get Started with Nuxt'
image: '/socials/get-started.jpg'
icon: i-ph-rocket-launch-duotone

19
docs/2.guide/0.index.md Normal file
View File

@ -0,0 +1,19 @@
---
title: 'Nuxt Guide'
titleTemplate: '%s'
description: 'Lean how Nuxt works with in-depth guides.'
navigation: false
surround: false
---
::card-group{class="sm:grid-cols-1"}
::card{icon="i-ph-medal-duotone" title="Key Concepts" to="/docs/guide/concepts"}
Discover the main concepts behind Nuxt, from auto-import, hybrid rendering to its TypeScript support.
::
::card{icon="i-ph-folders-duotone" title="Directory Structure" to="/docs/guide/directory-structure"}
Learn about Nuxt directory structure and what benefits each directory or file offers.
::
::card{icon="i-ph-star-duotone" title="Going Further" to="/docs/guide/going-further"}
Master Nuxt with advanced concepts like experimental features, hooks, modules, and more.
::
::

View File

@ -1,43 +1,43 @@
---
description: "Nuxt auto-imports helper functions, composables and Vue APIs."
title: Auto-imports
description: "Nuxt auto-imports components, composables, helper functions and Vue APIs."
---
# Auto-imports
Nuxt auto-imports components, composables and [Vue.js APIs](https://vuejs.org/api/) to use across your application without explicitly importing them.
## Composables and Helper Functions
```vue [app.vue]
<script setup lang="ts">
const count = ref(1) // ref is auto-imported
</script>
```
Nuxt auto-imports helper functions, composables and Vue APIs to use across your application without explicitly importing them. Based on the directory structure, every Nuxt application can also use auto-imports for its own components, composables and plugins. Components, composables or plugins can use these functions.
Thanks to its opiniated directory structure, Nuxt can auto-import your [`components/`](/docs/guide/directory-structure/components), [`composables/`](/docs/guide/directory-structure/components) and [`utils/`](/docs/guide/directory-structure/components).
Contrary to a classic global declaration, Nuxt preserves typings and IDEs completions and hints, and only includes what is actually used in your production code.
Contrary to a classic global declaration, Nuxt preserves typings, IDEs completions and hints, and **only includes what is used in your production code**.
::alert{type=info icon=💡}
In the documentation, every function that is not explicitly imported is auto-imported by Nuxt and can be used as-is in your code.
You can find a reference for auto-imported [composables](/docs/api/composables/use-async-data) and [utilities](/docs/api/utils/dollarfetch) in the API section.
::callout{color="blue" icon="i-ph-lightbulb-duotone"}
In the docs, every function that is not explicitly imported is auto-imported by Nuxt and can be used as-is in your code. You can find a reference for auto-imported components, composables and utilities in the [API section](/docs/api).
::
::alert{type=info}
In the [server directory](/docs/guide/directory-structure/server), we auto import exported functions and variables from `server/utils/`.
::callout
In the [`server`](/docs/guide/directory-structure/server) directory, Nuxt auto-imports exported functions and variables from `server/utils/`.
::
::alert
You can also auto-import functions exported from custom folders or third-party packages by configuring the [`imports` section](/docs/api/configuration/nuxt-config#imports) of your `nuxt.config` file.
::callout
You can also auto-import functions exported from custom folders or third-party packages by configuring the [`imports`](/docs/api/nuxt-config#imports) section of your `nuxt.config` file.
::
### Built-in Auto-imports
#### Nuxt Auto-imports
## Built-in Auto-imports
Nuxt auto-imports functions and composables to perform [data fetching](/docs/getting-started/data-fetching), get access to the [app context](/docs/api/composables/use-nuxt-app) and [runtime config](/docs/guide/going-further/runtime-config), manage [state](/docs/getting-started/state-management) or define components and plugins.
```vue
<script setup lang="ts">
/* useAsyncData() and $fetch() are auto-imported */
const { data, refresh, pending } = await useAsyncData('/api/hello', () => $fetch('/api/hello'))
const { data, refresh, pending } = await useFetch('/api/hello')
</script>
```
#### Vue Auto-imports
Vue 3 exposes Reactivity APIs like `ref` or `computed`, as well as lifecycle hooks and helpers that are auto-imported by Nuxt.
```vue
@ -48,7 +48,7 @@ const double = computed(() => count.value * 2)
</script>
```
#### Using Vue and Nuxt composables
### Vue and Nuxt composables
<!-- TODO: move to separate page with https://github.com/nuxt/nuxt/issues/14723 and add more information -->
@ -60,14 +60,15 @@ That means that (with very few exceptions) you cannot use them outside a Nuxt pl
If you get an error message like `Nuxt instance is unavailable` then it probably means you are calling a Nuxt composable in the wrong place in the Vue or Nuxt lifecycle.
See the full explanation in this [comment](https://github.com/nuxt/nuxt/issues/14269#issuecomment-1397352832).
::NeedContribution
::read-more{to="/docs/guide/going-further/experimental-features#asynccontext" icon="i-ph-star-duotone"}
Checkout the `asyncContext` experimental feature to use Nuxt composables in async functions.
::
##### Example
::read-more{to="https://github.com/nuxt/nuxt/issues/14269#issuecomment-1397352832" target="_blank"}
See the full explanation in this GitHub comment.
::
**Example:** Breaking code:
**Example of breaking code:**
```ts [composables/example.ts]
// trying to access runtime config outside a composable
@ -78,7 +79,7 @@ export const useMyComposable = () => {
}
```
**Example:** Fixing the error:
**Example of working code:**
```ts [composables/example.ts]
export const useMyComposable = () => {
@ -90,7 +91,7 @@ export const useMyComposable = () => {
}
```
### Directory-based Auto-imports
## Directory-based Auto-imports
Nuxt directly auto-imports files created in defined directories:
@ -98,6 +99,8 @@ Nuxt directly auto-imports files created in defined directories:
- `composables/` for [Vue composables](/docs/guide/directory-structure/composables).
- `utils/` for helper functions and other utilities.
:link-example{to="/docs/examples/features/auto-imports"}
### Explicit Imports
Nuxt exposes every auto-import with the `#imports` alias that can be used to make the import explicit if needed:
@ -129,7 +132,7 @@ This will disable auto-imports completely but it's still possible to use [explic
Nuxt also automatically imports components from your `~/components` directory, although this is configured separately from auto-importing composables and utility functions.
:ReadMore{link="/docs/guide/directory-structure/components"}
:read-more{to="/docs/guide/directory-structure/components"}
To disable auto-importing components from your own `~/components` directory, you can set `components.dirs` to an empty array (though note that this will not affect components added by modules).
@ -145,7 +148,7 @@ export default defineNuxtConfig({
Nuxt also allows auto-importing from third-party packages.
::alert
::callout
If you are using the Nuxt module for that package, it is likely that the module has already configured auto-imports for that package.
::

View File

@ -1,15 +1,17 @@
---
description: "Nuxt uses Vue and adds features such as component auto-imports and file-based routing."
title: 'Vue.js Development'
description: "Nuxt uses Vue.js and adds features such as component auto-imports, file-based routing and composables for a SSR-friendly usage."
---
# Vue.js Development
Nuxt integrates Vue 3, the new major release of Vue that enables new patterns for Nuxt users.
Nuxt uses Vue as a frontend framework and adds features such as component auto-imports and file-based routing. Nuxt 3 integrates Vue 3, the new major release of Vue that enables new patterns for Nuxt users.
::callout
While an in-depth knowledge of Vue is not required to use Nuxt, we recommend that you read the documentation and go through some of the examples on [vuejs.org](https://vuejs.org/).
::
> While an in-depth knowledge of Vue is not required to use Nuxt, we recommend that you read the documentation and go through some of the examples on [vuejs.org](https://vuejs.org/).
>
Nuxt has always used Vue as a frontend framework.
Nuxt has always used Vue as a frontend framework. We chose to build Nuxt on top of Vue for these reasons:
We chose to build Nuxt on top of Vue for these reasons:
- The reactivity model of Vue, where a change in data automatically triggers a change in the interface.
- The component-based templating, while keeping HTML as the common language of the web, enables intuitive patterns to keep your interface consistent, yet powerful.
@ -19,34 +21,21 @@ Nuxt has always used Vue as a frontend framework. We chose to build Nuxt on top
### Single File Components
[Vues single-file components](https://v3.vuejs.org/guide/single-file-component.html) (SFC, or `*.vue` files) encapsulate the markup (`<template>`), logic (`<script>`) and styling (`<style>`) of a Vue component. Nuxt provides a zero-config experience for SFCs with [Hot Module Replacement](https://webpack.js.org/concepts/hot-module-replacement/) that offers a seamless developer experience.
[Vues single-file components](https://v3.vuejs.org/guide/single-file-component.html) (SFC or `*.vue` files) encapsulate the markup (`<template>`), logic (`<script>`) and styling (`<style>`) of a Vue component. Nuxt provides a zero-config experience for SFCs with [Hot Module Replacement](https://vitejs.dev/guide/features.html#hot-module-replacement) that offers a seamless developer experience.
### Components Auto-imports
### Auto-imports
Every Vue component created in the [`components/` directory](/docs/guide/directory-structure/components) of a Nuxt project will be available in your project without having to import it. If a component is not used anywhere, your productions code will not include it.
Every Vue component created in the [`components/`](/docs/guide/directory-structure/components) directoryof a Nuxt project will be available in your project without having to import it. If a component is not used anywhere, your productions code will not include it.
:read-more{to="/docs/guide/concepts/auto-imports"}
### Vue Router
Most applications need multiple pages and a way to navigate between them. This is called **routing**. Nuxt uses a [`pages/` directory](/docs/guide/directory-structure/pages) and naming conventions to directly create routes mapped to your files using the official [Vue Router library](https://router.vuejs.org/).
Most applications need multiple pages and a way to navigate between them. This is called **routing**. Nuxt uses a [`pages/`](/docs/guide/directory-structure/pages) directory and naming conventions to directly create routes mapped to your files using the official [Vue Router library](https://router.vuejs.org/).
### Example
:read-more{to="/docs/getting-started/routing"}
:button-link[Open on StackBlitz]{href="https://stackblitz.com/edit/github-9hzuns?file=app.vue" blank .mr-2}
:button-link[Open on CodeSandbox]{href="https://codesandbox.io/s/nuxt-3-components-auto-import-2xq9z?file=/app.vue" blank}
The `app.vue` file is the entry point, which represents the page displayed in the browser window.
Inside the `<template>` of the component, we use the `<Welcome>` component created in the [`components/` directory](/docs/guide/directory-structure/components) without having to import it.
Try to replace the `<template>`s content with a custom welcome message. The browser window on the right will automatically render the changes without reloading.
::alert{type="info"}
💡 If you're familiar with Vue, you might be looking for the `main.js` file that creates a Vue app instance. Nuxt automatically handles this behind the scenes.
::
**If you were a previous user of Nuxt 2 or Vue 2, keep reading to get a feel of the differences between Vue 2 and Vue 3, and how Nuxt integrates those evolutions.**
**Otherwise, go to the next chapter to discover another key feature of Nuxt: [Rendering modes](/docs/guide/concepts/rendering)**.
:link-example{to="/docs/examples/features/auto-imports"}
## Differences with Nuxt 2 / Vue 2
@ -93,10 +82,10 @@ The [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) i
Used with the `setup` keyword in the `<script>` definition, here is the above component rewritten with Composition API and Nuxt 3s auto-imported Reactivity APIs:
```vue
```vue [components/Counter.vue]
<script setup lang="ts">
const count = ref(0);
const increment = () => count.value++;
const count = ref(0)
const increment = () => count.value++
</script>
```
@ -107,8 +96,8 @@ The goal of Nuxt 3 is to provide a great developer experience around the Composi
### TypeScript Support
Both Vue 3 and Nuxt 3 are written in TypeScript. A fully typed codebase prevents mistakes and documents APIs usage. This doesnt mean that you have to write your application in TypeScript to take advantage of it. With Nuxt 3, you can opt-in by renaming your file from `.js` to `.ts` , or add `<script lang="ts">` in a component.
Both Vue 3 and Nuxt 3 are written in TypeScript. A fully typed codebase prevents mistakes and documents APIs usage. This doesnt mean that you have to write your application in TypeScript to take advantage of it. With Nuxt 3, you can opt-in by renaming your file from `.js` to `.ts` , or add `<script setup lang="ts">` in a component.
::alert{type="info"}
🔎 [Read the details about TypeScript in Nuxt 3](/docs/guide/concepts/typescript)
::read-more{to="/docs/guide/concepts/typescript"}
Read the details about TypeScript in Nuxt 3
::

View File

@ -1,14 +1,13 @@
---
description: "Nuxt supports different rendering modes, universal rendering, client-side rendering but also offers hybrid-rendering and the possibility to render on CDN Edge Servers."
title: 'Rendering Modes'
description: 'Learn about the different rendering modes available in Nuxt.'
---
# Rendering Modes
Nuxt supports different rendering modes, [universal rendering](#universal-rendering), [client-side rendering](#client-side-rendering) but also offers [hybrid-rendering](#hybrid-rendering) and the possibility to render your application on [CDN Edge Servers](#edge-side-rendering).
Both the browser and server can interpret JavaScript code to turn Vue.js components into HTML elements. This step is called **rendering**. Nuxt supports both **universal** and **client-side** rendering. The two approaches have benefits and downsides that we will cover.
By default, Nuxt uses **universal rendering** to provide better user experience, performance and to optimize search engine indexing, but you can switch rendering modes in [one line of configuration](/docs/api/configuration/nuxt-config#ssr).
By default, Nuxt uses **universal rendering** to provide better user experience, performance and to optimize search engine indexing, but you can switch rendering modes in [one line of configuration](/docs/api/nuxt-config#ssr).
## Universal Rendering
@ -16,12 +15,11 @@ When the browser requests a URL with universal (server-side + client-side) rende
To not lose the benefits of the client-side rendering method, such as dynamic interfaces and pages transitions, the Client (browser) loads the JavaScript code that runs on the Server in the background once the HTML document has been downloaded. The browser interprets it again (hence **Universal rendering**) and Vue.js takes control of the document and enables interactivity.
Making a static page interactive in the browser is called "Hydration."
Making a static page interactive in the browser is called "Hydration".
Universal rendering allows a Nuxt application to provide quick page load times while preserving the benefits of client-side rendering. Furthermore, as the content is already present in the HTML document, crawlers can index it without overhead.
![Users can access the static content when the HTML document is loaded. Hydration then allows page's interactivity](/assets/docs/concepts/rendering/light/ssr.svg){.light-img.dark:hidden}
![Users can access the static content when the HTML document is loaded. Hydration then allows page's interactivity](/assets/docs/concepts/rendering/dark/ssr.svg){.dark-img.hidden.dark:block}
![Users can access the static content when the HTML document is loaded. Hydration then allows page's interactivity](/assets/docs/concepts/rendering/ssr.svg)
**Benefits of server-side rendering:**
- **Performance**: Users can get immediate access to the page's content because browsers can display static content much faster than JavaScript-generated one. At the same time, Nuxt preserves the interactivity of a web application when the hydration process happens.
@ -33,11 +31,11 @@ Universal rendering allows a Nuxt application to provide quick page load times w
Universal rendering is very versatile and can fit almost any use case, and is especially appropriate for any content-oriented websites: **blogs, marketing websites, portfolios, e-commerce sites, and marketplaces.**
::alert
::callout
For more examples about writing Vue code without hydration mismatch, see [the Vue docs](https://vuejs.org/guide/scaling-up/ssr.html#hydration-mismatch).
::
::alert{type=warning}
::callout{icon="i-ph-warning-duotone" color="amber"}
When importing a library that relies on browser APIs and has side effects, make sure the component importing it is only called client-side. Bundlers do not treeshake imports of modules containing side effects.
::
@ -45,8 +43,7 @@ When importing a library that relies on browser APIs and has side effects, make
Out of the box, a traditional Vue.js application is rendered in the browser (or **client**). Then, Vue.js generates HTML elements after the browser downloads and parses all the JavaScript code containing the instructions to create the current interface.
![Users have to wait for the browser to download, parse and execute the JavaScript before seeing the page's content](/assets/docs/concepts/rendering/light/csr.svg){.light-img.dark:hidden}
![Users have to wait for the browser to download, parse and execute the JavaScript before seeing the page's content](/assets/docs/concepts/rendering/dark/csr.svg){.dark-img.hidden.dark:block}
![Users have to wait for the browser to download, parse and execute the JavaScript before seeing the page's content](/assets/docs/concepts/rendering/csr.svg)
**Benefits of client-side rendering:**
- **Development speed**: When working entirely on the client-side, we don't have to worry about the server compatibility of the code, for example, by using browser-only APIs like the `window` object.
@ -67,9 +64,9 @@ export default defineNuxtConfig({
})
```
::alert{type=info}
::callout
If you do use `ssr: false`, you should also place an HTML file in `~/app/spa-loading-template.html` with some HTML you would like to use to render a loading screen that will be rendered until your app is hydrated.
:ReadMore{link="/docs/api/configuration/nuxt-config#spaloadingtemplate"}
:read-more{title="SPA Loading Template" to="/docs/api/configuration/nuxt-config#spaloadingtemplate"}
::
## Hybrid Rendering
@ -82,8 +79,6 @@ Nuxt 3 includes route rules and hybrid rendering support. Using route rules you
Nuxt server will automatically register corresponding middleware and wrap routes with cache handlers using [Nitro caching layer](https://nitro.unjs.io/guide/cache).
**Example:**
```ts [nuxt.config.ts]
export default defineNuxtConfig({
routeRules: {
@ -103,6 +98,8 @@ export default defineNuxtConfig({
})
```
### Route Rules
The different properties you can use are the following:
- `redirect: string`{lang=ts} - Define server-side redirects.
- `ssr: boolean`{lang=ts} - Disables server-side rendering for sections of your app and make them SPA-only with `ssr: false`
@ -115,12 +112,24 @@ The different properties you can use are the following:
Whenever possible, route rules will be automatically applied to the deployment platform's native rules for optimal performances (Netlify and Vercel are currently supported).
::alert{type="warning"}
Note that Hybrid Rendering is not available when using `nuxt generate`.
::callout{icon="i-ph-warning-duotone" color="amber"}
Note that Hybrid Rendering is not available when using [`nuxt generate`](/docs/api/commands/generate).
::
**Examples:**
- [Nuxt + Vercel integration with hybrid rendering](https://github.com/danielroe/nuxt-vercel-isr)
::card-group
::card
---
icon: i-simple-icons-github
title: Nuxt Vercel ISR
to: https://github.com/danielroe/nuxt-vercel-isr
target: _blank
ui.icon.base: text-black dark:text-white
---
Example of a Nuxt application with hybrid rendering deployed on Vercel.
::
::
## Edge-Side Rendering
@ -141,7 +150,27 @@ The current platforms where you can leverage ESR are:
Note that **Hybrid Rendering** can be used when using Edge-Side Rendering with route rules.
You can explore open source examples deployed on some of the platform mentioned above:
- [Nuxt Todos Edge](https://github.com/atinux/nuxt-todos-edge): A todos application with user authentication, SSR and SQLite.
- [Atinotes](https://github.com/atinux/atinotes): An editable website with universal rendering.
::card-group
::card
---
icon: i-simple-icons-github
title: Nuxt Todos Edge
to: https://github.com/atinux/nuxt-todos-edge
target: _blank
ui.icon.base: text-black dark:text-white
---
A todos application with user authentication, SSR and SQLite.
::
::card
---
icon: i-simple-icons-github
title: Atinotes
to: https://github.com/atinux/atinotes
target: _blank
ui.icon.base: text-black dark:text-white
---
An editable website with universal rendering based on CloudFlare KV.
::
::
<!-- TODO: link to templates with ESR category for examples -->

View File

@ -1,15 +1,18 @@
# Server Engine
---
title: Server Engine
description: 'Nuxt 3 is powered by a new server engine: Nitro.'
---
Nuxt 3 is powered by a new server engine, [Nitro](https://nitro.unjs.io/).
While building Nuxt 3, we created a new server engine: [Nitro](https://nitro.unjs.io/).
It is shipped with many features:
::list{type=success}
- Cross-platform support for Node.js, Browsers, service-workers and more.
- Serverless support out-of-the-box.
- API routes support.
- Automatic code-splitting and async-loaded chunks.
- Hybrid mode for static + serverless sites.
- Development server with hot module reloading.
::
## API Layer
@ -23,15 +26,15 @@ Key features include:
Check out [the h3 docs](https://github.com/unjs/h3) for more information.
::alert{type="info" icon=}
Learn more about the API layer in the [`server/` directory](/docs/guide/directory-structure/server).
::read-more{to="/docs/guide/directory-structure/server#server-routes"}
Learn more about the API layer in the `server/` directory.
::
## Direct API Calls
Nitro allows 'direct' calling of routes via the globally-available `$fetch` helper. This will make an API call to the server if run on the browser, but will directly call the relevant function if run on the server, **saving an additional API call**.
Nitro allows 'direct' calling of routes via the globally-available [`$fetch`](/docs/api/utils/dollarfetch) helper. This will make an API call to the server if run on the browser, but will directly call the relevant function if run on the server, **saving an additional API call**.
`$fetch` API is using [ofetch](https://github.com/unjs/ofetch), with key features including:
[`$fetch`](/docs/api/utils/dollarfetch) API is using [ofetch](https://github.com/unjs/ofetch), with key features including:
- Automatic parsing of JSON responses (with access to raw response if needed)
- Request body and params are automatically handled, with correct `Content-Type` headers
@ -42,7 +45,7 @@ For more information on `$fetch` features, check out [ofetch](https://github.com
When using API routes (or middleware), Nitro will generate typings for these routes as long as you are returning a value instead of using `res.end()` to send a response.
You can access these types when using `$fetch()` or `useFetch()`.
You can access these types when using [`$fetch()`](/docs/api/utils/dollarfetch) or [`useFetch()`](/docs/api/composables/use-fetch).
## Standalone Server
@ -54,6 +57,6 @@ Nuxt 3 generates this dist when running `nuxt build` into a [`.output`](/docs/gu
The output contains runtime code to run your Nuxt server in any environment (including experimental browser service workers!) and serve your static files, making it a true hybrid framework for the JAMstack. In addition, Nuxt implements a native storage layer, supporting multi-source drivers and local assets.
::alert{type="info" icon=}
Check out the Nitro engine on GitHub: [unjs/nitro](https://github.com/unjs/nitro).
::read-more{color="gray" icon="i-simple-icons-github" to="https://github.com/unjs/nitro" target="_blank"}
Read more anout Nitro engine on GitHub.
::

View File

@ -1,27 +1,25 @@
---
title: 'Modules'
description: "Nuxt provides a module system to extend the framework core and simplify integrations."
---
# Modules
Nuxt provides a module system to extend the framework core and simplify integrations. You don't need to develop everything from scratch or maintain boilerplate if there is already a Nuxt module for it. Adding Nuxt modules is possible using [`nuxt.config`](/docs/api/configuration/nuxt-config#modules).
## Exploring Nuxt Modules
When developing production-grade applications with Nuxt you might find that the framework's core functionality is not enough. Nuxt can be extended with configuration options and plugins, but maintaining these customizations across multiple projects can be tedious, repetitive and time-consuming. On the other hand, supporting every project's needs out of the box would make Nuxt very complex and hard to use.
This is one of the reasons why Nuxt provides a module system that makes it possible to extend the core. Nuxt modules are async functions that sequentially run when starting Nuxt in development mode using `nuxi dev` or building a project for production with `nuxi build`. They can override templates, configure webpack loaders, add CSS libraries, and perform many other useful tasks.
This is one of the reasons why Nuxt provides a module system that makes it possible to extend the core. Nuxt modules are async functions that sequentially run when starting Nuxt in development mode using [`nuxi dev`](/docs/api/commands/dev) or building a project for production with [`nuxi build`](/docs/api/commands/build). They can override templates, configure webpack loaders, add CSS libraries, and perform many other useful tasks.
Best of all, Nuxt modules can be distributed in npm packages. This makes it possible for them to be reused across projects and shared with the community, helping create an ecosystem of high-quality add-ons.
::ReadMore{link="/modules" title="Nuxt 3 Compatible Modules"}
::read-more{to="/modules"}
Explore Nuxt Modules
::
## The `modules` Property
## Add Nuxt Modules
Once you have installed the modules you can then add them to your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file under the `modules` property. Module developers usually provide additional steps and details for usage.
Once you have installed the modules you can add them to your [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file under the `modules` property. Module developers usually provide additional steps and details for usage.
```ts{}[nuxt.config.ts]
```ts [nuxt.config.ts]
export default defineNuxtConfig({
modules: [
// Using package name (recommended usage)
@ -39,13 +37,12 @@ export default defineNuxtConfig({
})
```
::alert{type="warning" icon=⚠️}
::callout{color="amber" icon="i-ph-warning-duotone"}
Nuxt modules are now build-time-only, and the `buildModules` property used in Nuxt 2 is deprecated in favor of `modules`.
::
## Module Development
## Create a Nuxt Module
Everyone has the opportunity to develop modules. Read more about developing modules in the [Module Author Guide](/docs/guide/going-further/modules).
Everyone has the opportunity to develop modules and we cannot wait to see what you will build.
::ReadMore{link="/docs/guide/going-further/modules" title="Module Author Guide"}
::
:read-more{to="/docs/guide/going-further/modules" title="Module Author Guide"}

View File

@ -1,9 +1,8 @@
---
title: 'ES Modules'
description: "Nuxt 3 (and Bridge) uses Native ES Modules."
---
# ES Modules
This guide helps explain what ES Modules are and how to make a Nuxt app (or upstream library) compatible with ESM.
## Background
@ -76,7 +75,7 @@ For a long time module authors have been producing ESM-syntax builds but using c
However, if you try to import a package with an `.esm.js` file in a Node.js ESM context, it won't work, and you'll get an error like:
```bash
```bash [Terminal]
(node:22145) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
/path/to/index.js:1
@ -93,7 +92,7 @@ SyntaxError: Unexpected token 'export'
You might also get this error if you have a named import from an ESM-syntax build that Node.js thinks is CJS:
```bash
```bash [Terminal]
file:///path/to/index.mjs:5
import { named } from 'sample-library'
^^^^^

View File

@ -1,17 +1,48 @@
---
description: "Nuxt 3 is fully typed and provides accurate type information when you are coding."
title: 'TypeScript'
description: "Nuxt 3 is fully typed and provides helpful shortcuts to ensure you have access to accurate type information when you are coding."
---
# TypeScript
Nuxt 3 is fully typed and provides helpful shortcuts to ensure you have access to accurate type information when you are coding.
## Type-checking
By default, Nuxt doesn't check types when you run `nuxi dev` or `nuxi build`, for performance reasons. However, you can enable type-checking at build or development time by installing `vue-tsc` and `typescript` as devDependencies and either enabling [the `typescript.typeCheck` option in your `nuxt.config` file](/docs/api/configuration/nuxt-config#typescript) or [manually checking your types with nuxi](/docs/api/commands/typecheck).
By default, Nuxt doesn't check types when you run [`nuxi dev`](/docs/api/commands/dev) or [`nuxi build`](/docs/api/commands/build), for performance reasons.
```bash
yarn nuxi typecheck
To enable type-checking at build or development time, install `vue-tsc` and `typescript` as development dependency:
::code-group
```bash [yarn]
yarn add --dev vue-tsc typescript
```
```bash [npm]
npm install --save-dev vue-tsc typescript
```
```bash [pnpm]
pnpm add -D vue-tsc typescript
```
```bash [bun]
bun add -D vue-tsc typescript
```
::
Then, run [`nuxi typecheck`](/docs/api/commands/typecheck) command to check your types:
```bash [Terminal]
npx nuxi typecheck
```
To enable type-checking at build time, you can also use the [`typescript.typeCheck`](/docs/api/nuxt-config#typecheck) option in your `nuxt.config` file:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
typescript: {
typeCheck: true
}
})
```
## Auto-generated Types
@ -30,15 +61,15 @@ This file contains the recommended basic TypeScript configuration for your proje
[Read more about how to extend this configuration](/docs/guide/directory-structure/tsconfig).
::alert{icon=👉}
::callout
Nitro also [auto-generates types](/docs/guide/concepts/server-engine#typed-api-routes) for API routes. Plus, Nuxt also generates types for globally available components and [auto-imports from your composables](/docs/guide/directory-structure/composables), plus other core functionality.
::
::alert
::callout
Keep in mind that all options extended from `./.nuxt/tsconfig.json` will be overwritten by the options defined in your `tsconfig.json`.
Overwriting options such as `"compilerOptions.paths"` with your own configuration will lead TypeScript to not factor in the module resolutions from `./.nuxt/tsconfig.json`. This can lead to module resolutions such as `#imports` not being recognized.
In case you need to extend options provided by `./.nuxt/tsconfig.json` further, you can use the [`alias` property](/docs/api/configuration/nuxt-config#alias) within your `nuxt.config`. `nuxi` will pick them up and extend `./.nuxt/tsconfig.json` accordingly.
:br :br
In case you need to extend options provided by `./.nuxt/tsconfig.json` further, you can use the [`alias` property](/docs/api/nuxt-config#alias) within your `nuxt.config`. `nuxi` will pick them up and extend `./.nuxt/tsconfig.json` accordingly.
::
## Stricter Checks
@ -49,7 +80,7 @@ Once youve converted your codebase to TypeScript and felt familiar with it, y
In order to enable strict type checking, you have to update `nuxt.config`:
```js
```ts [nuxt.config.ts]
export default defineNuxtConfig({
typescript: {
strict: true

View File

@ -1,4 +1,3 @@
title: Key Concepts
titleTemplate: '%s · Nuxt Concepts'
navigation.icon: uil:award-alt
image: '/socials/key-concepts.jpg'
icon: i-ph-medal-duotone

View File

@ -1,4 +0,0 @@
---
navigation: false
redirect: /guide/concepts/auto-imports
---

View File

@ -1,20 +1,20 @@
---
navigation.icon: IconDirectory
title: ".nuxt"
description: "Nuxt uses the .nuxt/ directory in development to generate your Vue application."
head.title: ".nuxt/"
navigation.icon: i-ph-folder-duotone
---
# .nuxt Directory
Nuxt uses the [`.nuxt/` directory](/docs/guide/directory-structure/nuxt) in development to generate your Vue application.
::alert{type=warning}
You should not touch any files inside since the whole directory will be re-created when running `nuxt dev`.
::callout{icon="i-ph-warning-duotone" color="amber"}
This directory should be added to your [`.gitignore`](/docs/guide/directory-structure/gitignore) file to avoid pushing the dev build output to your repository.
::
This directory is interesting if you want to learn more about the files Nuxt generates based on your directory structure.
## Virtual File System
Nuxt also provides a Virtual File System (VFS) for modules to add templates to this directory without writing them to disk.
Nuxt also provides a Virtual File System (VFS) for modules to add templates to this directory without writing them to disk. You can explore the generated files by navigating to <http://localhost:3000/_vfs>
You can explore the generated files by opening the [Nuxt DevTools](https://devtools.nuxt.com) in development mode and navigating to the **Virtual Files** tab.
::callout{icon="i-ph-warning-duotone" color="amber"}
You should not touch any files inside since the whole directory will be re-created when running [`nuxt dev`](/docs/api/commands/dev).
::

View File

@ -1,16 +1,18 @@
---
navigation.icon: IconDirectory
title: ".output"
description: "Nuxt creates the .output/ directory when building your application for production."
head.title: ".output/"
navigation.icon: i-ph-folder-duotone
---
# Output Directory
Nuxt creates the [`.output/` directory](/docs/guide/directory-structure/output) when building your application for production.
::alert{type=warning}
You should not touch any files inside since the whole directory will be re-created when running `nuxt build`.
::callout{icon="i-ph-warning-duotone" color="amber"}
This directory should be added to your [`.gitignore`](/docs/guide/directory-structure/gitignore) file to avoid pushing the build output to your repository.
::
Use this directory to deploy your Nuxt application to production. Learn more in our [deployment section](/docs/getting-started/deployment).
Use this directory to deploy your Nuxt application to production.
:read-more{to="/docs/getting-started/deployment"}
::callout{icon="i-ph-warning-duotone" color="amber"}
You should not touch any files inside since the whole directory will be re-created when running [`nuxt build`](/docs/api/commands/build).
::

View File

@ -1,14 +1,10 @@
---
navigation.icon: IconDirectory
title: "assets"
description: "The assets/ directory is used to add all the website's assets that the build tool will process."
head.title: "assets/"
navigation.icon: i-ph-folder-duotone
---
# Assets Directory
The [`assets/` directory](/docs/guide/directory-structure/assets) is used to add all the website's assets that the build tool (webpack or Vite) will process.
The directory usually contains the following types of files:
- Stylesheets (CSS, SASS, etc.)
@ -17,4 +13,4 @@ The directory usually contains the following types of files:
If you want to serve assets from the server, we recommend taking a look at the [`public/`](/docs/guide/directory-structure/public) directory.
::ReadMore{link="/docs/getting-started/assets"}
:read-more{to="/docs/getting-started/assets"}

View File

@ -1,33 +1,146 @@
---
navigation.icon: IconDirectory
title: "components"
description: "The components/ directory is where you put all your Vue components."
head.title: "components/"
description: "The components/ directory is where you put all your Vue components."
navigation.icon: i-ph-folder-duotone
---
# Components Directory
Nuxt automatically imports any components in this directory (along with components that are registered by any modules you may be using).
The [`components/` directory](/docs/guide/directory-structure/components) is where you put all your Vue components which can then be imported inside your pages or other components ([learn more](https://vuejs.org/guide/essentials/component-basics.html#components-basics)).
Nuxt automatically imports any components in your [`components/` directory](/docs/guide/directory-structure/components) (along with components that are registered by any modules you may be using).
```bash
```bash [Directory Structure]
| components/
--| TheHeader.vue
--| TheFooter.vue
--| AppHeader.vue
--| AppFooter.vue
```
```html [layouts/default.vue]
```html [app.vue]
<template>
<div>
<TheHeader />
<slot />
<TheFooter />
<AppHeader />
<NuxtPage />
<AppFooter />
</div>
</template>
```
## Custom directories
## Component Names
If you have a component in nested directories such as:
```bash [Directory Structure]
| components/
--| base/
----| foo/
------| Button.vue
```
... then the component's name will be based on its own path directory and filename, with duplicate segments being removed. Therefore, the component's name will be:
```html
<BaseFooButton />
```
::callout
For clarity, we recommend that the component's filename matches its name. So, in the example above, you could rename `Button.vue` to be `BaseFooButton.vue`.
::
If you want to auto-import components based only on its name, not path, then you need to set `pathPrefix` option to `false` using extended form of the configuration object:
```diff [nuxt.config.ts]
export default defineNuxtConfig({
components: [
{
path: '~/components',
+ pathPrefix: false,
},
],
});
```
This registers the components using the same strategy as used in Nuxt 2. For example, `~/components/Some/MyComponent.vue` will be usable as `<MyComponent>` and not `<SomeMyComponent>`.
## Dynamic Components
If you want to use the Vue `<component :is="someComputedComponent">`{lang=vue} syntax, you need to use the `resolveComponent` helper provided by Vue or import the component directly from `#components` and pass it into `is` prop.
For example:
```vue [pages/index.vue]
<script setup lang="ts">
import { SomeComponent } from '#components'
const MyButton = resolveComponent('MyButton')
</script>
<template>
<component :is="clickable ? MyButton : 'div'" />
<component :is="SomeComponent" />
</template>
```
::callout
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 string and not a variable.
::
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.
::callout
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.
```html [pages/index.vue]
<script setup>
const show = ref(false)
</script>
<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
</div>
</template>
```
## Direct Imports
You can also explicitly import components from `#components` if you want or need to bypass Nuxt's auto-importing functionality.
```html [pages/index.vue]
<script setup lang="ts">
import { NuxtLink, LazyMountainsList } from '#components'
const show = ref(false)
</script>
<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
<NuxtLink to="/">Home</NuxtLink>
</div>
</template>
```
## 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:
@ -53,13 +166,13 @@ export default defineNuxtConfig({
})
```
::alert
::callout
Any nested directories need to be added first as they are scanned in order.
::
## Component extensions
## Component Extensions
By default, any file with an extension specified in the [extensions key of `nuxt.config.ts`](/docs/api/configuration/nuxt-config#extensions) is treated as a component.
By default, any file with an extension specified in the [extensions key of `nuxt.config.ts`](/docs/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:
```diff
@ -73,141 +186,122 @@ export default defineNuxtConfig({
})
```
## Component Names
## Client Components
If you have a component in nested directories such as:
If a component is meant to be rendered only client-side, you can add the `.client` suffix to your component.
```bash
```bash [Directory Structure]
| components/
--| base/
----| foo/
------| Button.vue
--| Comments.client.vue
```
... then the component's name will be based on its own path directory and filename, with duplicate segments being removed. Therefore, the component's name will be:
```html
<BaseFooButton />
```html [pages/example.vue]
<template>
<div>
<!-- this component will only be rendered on client side -->
<Comments />
</div>
</template>
```
::alert
For clarity, we recommend that the component's filename matches its name. (So, in the example above, you could rename `Button.vue` to be `BaseFooButton.vue`.)
::callout
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.
::
If you want to auto-import components based only on its name, not path, then you need to set `pathPrefix` option to `false` using extended form of the configuration object:
::callout{color="amber" icon="i-ph-warning-duotone"}
`.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.
::
```diff
## 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](#paired-with-a-client-component).
::callout{color="blue" icon="i-ph-video-duotone" to="https://www.youtube.com/watch?v=u1yyXe86xJM" target="_blank"}
Watch Learn Vue video about Nuxt Server Components.
::
::callout{color="blue" icon="i-ph-article-duotone" to="https://roe.dev/blog/nuxt-server-components" target="_blank"}
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]
export default defineNuxtConfig({
components: [
{
path: '~/components',
+ pathPrefix: false,
},
],
});
experimental: {
componentIslands: true
}
})
```
This registers the components using the same strategy as used in Nuxt 2. For example, `~/components/Some/MyComponent.vue` will be usable as `<MyComponent>` and not `<SomeMyComponent>`.
Now you can register server-only components with the `.server` suffix and use them anywhere in your application automatically.
## Dynamic Components
If you want to use the Vue `<component :is="someComputedComponent">` syntax, you need to use the `resolveComponent` helper provided by Vue or import the component directly from `#components` and pass it into `is` prop.
For example:
```vue
<script setup lang="ts">
import { SomeComponent } from '#components'
const MyButton = resolveComponent('MyButton')
</script>
<template>
<component :is="clickable ? MyButton : 'div'" />
<component :is="SomeComponent" />
</template>
```bash [Directory Structure]
| components/
--| HighlightedMarkdown.server.vue
```
::alert{type=warning}
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 string and not a variable.
::
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.
::alert{type=info}
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.
```html [layouts/default.vue]
```html [pages/example.vue]
<template>
<div>
<TheHeader />
<slot />
<LazyTheFooter />
<!--
this will automatically be rendered on the server, meaning your markdown parsing + highlighting
libraries are not included in your client bundle.
-->
<HighlightedMarkdown markdown="# Headline" />
</div>
</template>
```
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.
Server-only components use [`<NuxtIsland>`](/docs/api/components/nuxt-island) under the hood, meaning that `lazy` prop and `#fallback` slot are both passed down to it.
```html [pages/index.vue]
<script>
export default {
data() {
return {
show: false
}
}
}
</script>
#### Server Component Context
<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
</div>
</template>
When rendering a server-only or island component, `<NuxtIsland>` 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).
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.
::callout
Slots can be interactive and are wrapped within a `<div>` 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
```
## Direct Imports
You can also explicitly import components from `#components` if you want or need to bypass Nuxt's auto-importing functionality.
```html [pages/index.vue]
<script setup lang="ts">
import { NuxtLink, LazyMountainsList } from '#components'
const show = ref(false)
</script>
```html [pages/example.vue]
<template>
<div>
<h1>Mountains</h1>
<LazyMountainsList v-if="show" />
<button v-if="!show" @click="show = true">Show List</button>
<NuxtLink to="/">Home</NuxtLink>
<!-- this component will render Comments.server on the server then Comments.client once mounted in the browser -->
<Comments />
</div>
</template>
```
## `<ClientOnly>` Component
Nuxt provides the `<ClientOnly>` component for purposely rendering a component only on client side. To import a component only on the client, register the component in a client-side only plugin.
Nuxt provides the [`<ClientOnly>`](/docs/api/components/client-only) component for purposely rendering a component only on client side.
```html [pages/example.vue]
<template>
@ -241,115 +335,10 @@ Use a slot as fallback until `<ClientOnly>` is mounted on client side.
```
<!-- TODO: Add back after passing treeshakeClientOnly experiment -->
<!-- ::alert{type=warning}
<!-- ::callout
Make sure not to _nest_ `<ClientOnly>` components or other client-only components. Nuxt performs an optimization to remove the contents of these components from the server-side render, which can break in this case.
:: -->
## .client Components
If a component is meant to be rendered only client-side, you can add the `.client` suffix to your component.
```bash
| components/
--| Comments.client.vue
```
```html [pages/example.vue]
<template>
<div>
<!-- this component will only be rendered on client side -->
<Comments />
</div>
</template>
```
::alert{type=warning}
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.
::
::alert{type=warning}
`.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.
::
## .server Components
`.server` components can either be used on their own or paired with a `.client` component.
### Standalone server components
Standalone server components will always be rendered on the server. When their props update, this will result in a network request that will update the rendered HTML in-place.
:video-player{src="https://www.youtube.com/watch?v=u1yyXe86xJM"}
> A video made by [LearnVue](https://go.learnvue.co) for the Nuxt documentation.
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]
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
| components/
--| HighlightedMarkdown.server.vue
```
```html [pages/example.vue]
<template>
<div>
<!--
this will automatically be rendered on the server, meaning your markdown parsing + highlighting
libraries are not included in your client bundle.
-->
<HighlightedMarkdown markdown="# Headline" />
</div>
</template>
```
Server-only components use `<NuxtIsland>` under the hood, meaning that `lazy` prop and `#fallback` slot are both passed down to `<NuxtIsland>`.
#### Server Component Context
When rendering a server-only or island component, `<NuxtIsland>` 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).
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.
::alert{type=info}
Slots can be interactive and are wrapped within a `<div>` 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
| components/
--| Comments.client.vue
--| Comments.server.vue
```
```html [pages/example.vue]
<template>
<div>
<!-- this component will render Comments.server on the server then Comments.client once mounted in the browser -->
<Comments />
</div>
</template>
```
## `<DevOnly>` Component
Nuxt provides the `<DevOnly>` component to render a component only during development.
@ -400,7 +389,7 @@ You can use the `components:dirs` hook to extend the directory list without requ
Imagine a directory structure like this:
```bash
```bash [Directory Structure]
| node_modules/
---| awesome-ui/
------| components/
@ -452,4 +441,4 @@ export default defineNuxtConfig({
It will automatically import the components only if used and also support HMR when updating your components in `node_modules/awesome-ui/components/`.
:LinkExample{link="/docs/examples/features/auto-imports"}
:link-example{to="/docs/examples/features/auto-imports"}

View File

@ -1,18 +1,10 @@
---
navigation.icon: IconDirectory
title: 'composables'
head.title: 'composables/'
description: Use the composables/ directory to auto-import your Vue composables into your application.
navigation.icon: i-ph-folder-duotone
---
# Composables Directory
Nuxt 3 uses the [`composables/` directory](/docs/guide/directory-structure/composables) to automatically import your Vue composables into your application using [auto-imports](/docs/guide/concepts/auto-imports)!
Under the hood, Nuxt auto generates the file `.nuxt/imports.d.ts` to declare the types.
Be aware that you have to run `nuxi prepare`, `nuxi dev` or `nuxi build` in order to let Nuxt generate the types. If you create a composable without having the dev server running, TypeScript will throw an error, such as `Cannot find name 'useBar'.`
## Usage
**Method 1:** Using named export
@ -46,7 +38,18 @@ const foo = useFoo()
</template>
```
::LinkExample{link="/docs/examples/features/auto-imports"}
:read-more{to="/docs/guide/concepts/auto-imports"}
:link-example{to="/docs/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 [`nuxi prepare`](/docs/api/commands/prepare), [`nuxi dev`](/docs/api/commands/dev) or [`nuxi build`](/docs/api/commands/build) in order to let Nuxt generate the types.
::callout
If you create a composable without having the dev server running, TypeScript will throw an error, such as `Cannot find name 'useBar'.`
::
## Examples
@ -77,12 +80,12 @@ export const useHello = () => {
Nuxt only scans files at the top level of the [`composables/` directory](/docs/guide/directory-structure/composables), e.g.:
```bash
composables
| - index.ts // scanned
| - useFoo.ts // scanned
| - nested
| --- utils.ts // not scanned
```bash [Directory Structure]
| composables/
---| index.ts // scanned
---| useFoo.ts // scanned
-----| nested/
-------| utils.ts // not scanned
```
Only `composables/index.ts` and `composables/useFoo.ts` would be searched for imports.

View File

@ -1,65 +1,32 @@
---
navigation.icon: IconDirectory
title: 'content'
head.title: 'content/'
description: The Content module reads the content/ directory to create a file-based CMS for your application.
description: Use the content/ directory to create a file-based CMS for your application.
navigation.icon: i-ph-folder-duotone
---
# Content Directory
The [Nuxt Content module](https://content.nuxtjs.org) reads the [`content/` directory](/docs/guide/directory-structure/content) in your project and parses `.md`, `.yml`, `.csv` and `.json` files to create a file-based CMS for your application.
::list{type=success}
[Nuxt Content](https://content.nuxt.com) reads the [`content/` directory](/docs/guide/directory-structure/content) in your project and parses `.md`, `.yml`, `.csv` and `.json` files to create a file-based CMS for your application.
- Render your content with built-in components.
- Query your content with a MongoDB-like API.
- Use your Vue components in Markdown files with the MDC syntax.
- Automatically generate your navigation.
::read-more{to="https://content.nuxt.com" target="_blank"}
Learn more in **Nuxt Content** documentation.
::
## Get Started
## Enable Nuxt Content
### Installation
Install the `@nuxt/content` module in your project as well as adding it to your `nuxt.config.ts` with one command:
Install the `@nuxt/content` module in your project:
::code-group
```bash [yarn]
yarn add --dev @nuxt/content
```
```bash [npm]
npm install --save-dev @nuxt/content
```
```bash [pnpm]
pnpm add -D @nuxt/content
```
```bash [bun]
bun add -D @nuxt/content
```
::
Then, add `@nuxt/content` to the `modules` section of `nuxt.config.ts`:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
modules: [
'@nuxt/content'
],
content: {
// https://content.nuxtjs.org/api/configuration
}
})
```bash [Terminal]
npx nuxi module add content
```
### Create Content
## Create Content
Place your markdown files inside the [`content/` directory](/docs/guide/directory-structure/content) in the root directory of your project:
Place your markdown files inside the `content/` directory:
```md [content/index.md]
# Hello Content
@ -67,20 +34,20 @@ Place your markdown files inside the [`content/` directory](/docs/guide/director
The module automatically loads and parses them.
### Render Pages
## Render Content
To render content pages, add a [catch-all route](/docs/guide/directory-structure/pages/#catch-all-route) using the `ContentDoc` component:
To render content pages, add a [catch-all route](/docs/guide/directory-structure/pages/#catch-all-route) using the [`<ContentDoc>`](https://content.nuxt.com/components/content-doc) component:
```vue [pages/[...slug\\].vue]
<template>
<main>
<ContentDoc />
<ContentDoc :path="$route.path" />
</main>
</template>
```
## Documentation
::alert{type=info}
Head over to <https://content.nuxtjs.org> to learn more about the Content module features, such as how to build queries and use Vue components in your Markdown files with the MDC syntax.
::callout
Head over to <https://content.nuxt.com> to learn more about the Content module features, such as how to build queries and use Vue components in your Markdown files with the MDC syntax.
::

View File

@ -1,58 +1,86 @@
---
navigation.icon: IconDirectory
title: "layouts"
description: "Nuxt provides a layouts framework to extract common UI patterns into reusable layouts."
head.title: "layouts/"
description: "Nuxt provides a layouts framework to extract common UI patterns into reusable layouts."
navigation.icon: i-ph-folder-duotone
---
# Layouts Directory
::callout{icon="i-ph-rocket-launch-duotone"}
For best performance, components placed in this directory will be automatically loaded via asynchronous import when used.
::
Nuxt provides a customizable layouts framework you can use throughout your application, ideal for extracting common UI or code patterns into reusable layout components.
## Enable Layouts
Layouts are placed in the [`layouts/` directory](/docs/guide/directory-structure/layouts) and will be automatically loaded via asynchronous import when used. Layouts are used by adding `<NuxtLayout>` to your `app.vue`, and either setting a `layout` property as part of your page metadata (if you are using the `~/pages` integration), or by manually specifying it as a prop to `<NuxtLayout>`. (**Note**: The layout name is normalized to kebab-case, so `someLayout` becomes `some-layout`.)
Layouts are enabled by adding [`<NuxtLayout>`](/docs/api/components/nuxt-layout) to your [`app.vue`](/docs/guide/directory-structure/app):
If you only have a single layout in your application, we recommend using [app.vue](/docs/guide/directory-structure/app) instead.
```vue [app.vue]
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
```
::alert{type=warning}
To use a layout:
- Set a `layout` property in your with with [definePageMeta](/docs/api/utils/define-page-meta)
- Set the `name` prop of `<NuxtLayout>`.
::callout{color="blue" icon="i-ph-info-duotone"}
The layout name is normalized to kebab-case, so `someLayout` becomes `some-layout`.
::
::callout{color="blue" icon="i-ph-info-duotone"}
If not layout is specified, `layouts/default.vue` will be used.
::
::callout{icon="i-ph-lightbulb-duotone"}
If you only have a single layout in your application, we recommend using [`app.vue`](/docs/guide/directory-structure/app) instead.
::
::callout{color="amber" icon="i-ph-warning-duotone"}
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 `<slot />`.
::
## Enabling the Default Layout
## Default Layout
Add a `~/layouts/default.vue`:
```vue [layouts/default.vue]
<template>
<div>
Some default layout shared across all pages
<p>Some default layout content shared across all pages</p>
<slot />
</div>
</template>
```
In a layout file, the content of the layout will be loaded in the `<slot />`, rather than using a special component.
In a layout file, the content of the page will be displayed in the `<slot />` component.
If you use a `app.vue` you will also need to add `<NuxtLayout>`:
## Named Layout
```vue [app.vue]
<template>
<NuxtLayout>
some page content
</NuxtLayout>
</template>
```
## Setting Another Layout
```bash
```bash [Directory Structure]
-| layouts/
---| default.vue
---| custom.vue
```
You can directly override the default layout like this:
Then you can use the `custom` layout in your page:
```vue{}[app.vue]
```vue [pages/about.vue]
<script setup lang="ts">
definePageMeta({
layout: 'custom'
})
</script>
```
::read-more{to="/docs/guide/directory-structure/pages#page-metadata"}
Learn more about `definePageMeta`.
::
You can directly override the default layout for all pages using the `name` property of [`<NuxtLayout>`](/docs/api/components/nuxt-layout):
```vue [app.vue]
<script setup lang="ts">
// You might choose this based on an API call or logged-in status
const layout = "custom";
@ -65,54 +93,27 @@ const layout = "custom";
</template>
```
Alternatively, you can override the default layout per-page like this:
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.
::code-group
File | Layout Name
-- | --
`~/layouts/desktop/default.vue` | `desktop-default`
`~/layouts/desktop-base/base.vue` | `desktop-base`
`~/layouts/desktop/index.vue` | `desktop`
```vue{}[pages/index.vue]
<script>
// This will work in both `<script setup>` and `<script>`
definePageMeta({
layout: "custom",
});
</script>
```
For clarity, we recommend that the layout's filename matches its name:
```vue{}[app.vue]
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
```
File | Layout Name
-- | --
`~/layouts/desktop/DesktopDefault.vue` | `desktop-default`
`~/layouts/desktop-base/DesktopBase.vue` | `desktop-base`
`~/layouts/desktop/Desktop.vue` | `desktop`
```vue [layouts/custom.vue]
<template>
<div>
Some *custom* layout
<slot />
</div>
</template>
```
```vue [layouts/default.vue]
<template>
<div>
A *default* layout
<slot />
</div>
</template>
```
::
::alert{type=info}
Learn more about [defining page meta](/docs/guide/directory-structure/pages#page-metadata).
::
:link-example{to="/docs/examples/features/layouts"}
## Changing the Layout Dynamically
You can also use a ref or computed property for your layout.
You can also use the [`setPageLayout`](/docs/api/utils/set-page-layout) helper to change the layout dynamically:
```vue
<script setup lang="ts">
@ -131,12 +132,11 @@ definePageMeta({
</template>
```
::LinkExample{link="/docs/examples/features/layouts"}
::
:link-example{to="/docs/examples/features/layouts"}
## Overriding a Layout on a Per-page Basis
If you are using the `~/pages` integration, you can take full control by setting `layout: false` and then using the `<NuxtLayout>` component within the page.
If you are using pages, you can take full control by setting `layout: false` and then using the `<NuxtLayout>` component within the page.
::code-group
@ -144,7 +144,7 @@ If you are using the `~/pages` integration, you can take full control by setting
<script setup lang="ts">
definePageMeta({
layout: false,
});
})
</script>
<template>
@ -175,27 +175,6 @@ definePageMeta({
::
::alert{type=warning}
If you use `<NuxtLayout>` within your pages, make sure it is not the root element (or disable layout/page transitions).
::
## Layout Names
If you have a layout in nested directories such as:
```bash
| layouts/
--| base/
----| foo/
------| Layout.vue
```
... then the layout's name will be based on its own path directory and filename, with duplicate segments being removed. Therefore, the layout's name will be:
```html
<BaseFooLayout />
```
::alert
For clarity, we recommend that the layout's filename matches its name. (So, in the example above, you could rename `Layout.vue` to be `BaseFooLayout.vue`.)
::callout
If you use `<NuxtLayout>` within your pages, make sure it is not the root element (or [disable layout/page transitions](/docs/getting-started/transitions#disable-transitions)).
::

View File

@ -1,31 +1,33 @@
---
navigation.icon: IconDirectory
title: "middleware"
description: "Nuxt provides middleware to run code before navigating to a particular route."
head.title: "middleware/"
navigation.icon: i-ph-folder-duotone
---
# Middleware Directory
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.
::alert{type=info}
Route middleware run 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.
::
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 [`middleware/` directory](/docs/guide/directory-structure/middleware) 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 [`middleware/` directory](/docs/guide/directory-structure/middleware) (with a `.global` suffix) and will be automatically run on every route change.
1. Anonymous (or inline) route middleware are defined directly within the page
2. Named route middleware, placed in the `middleware/` and automatically loaded via asynchronous import when used on a page.
3. Global route middleware, placed in the `middleware/` with a `.global` suffix and is run on every route change.
The first two kinds of route middleware can be [defined in `definePageMeta`](/docs/guide/directory-structure/pages).
The first two kinds of route middleware can be defined in [`definePageMeta`](/docs/api/utils/define-page-meta).
## Format
::callout
Name of middleware are normalized to kebab-case: `myMiddleware` becomes `my-middleware`.
::
::callout
Route middleware run within the Vue part of your Nuxt app. Despite the similar name, they are completely different from [server middleware](/docs/guide/directory-structure/server#server-middleware), which are run in the Nitro server part of your app.
::
## Usage
Route middleware are navigation guards that receive the current route and the next route as arguments.
```js
```ts [middleware/my-middleware.ts]
export default defineNuxtRouteMiddleware((to, from) => {
if (to.params.id === '1') {
return abortNavigation()
@ -39,31 +41,29 @@ export default defineNuxtRouteMiddleware((to, from) => {
})
```
Nuxt provides two globally available helpers that can be returned directly from the middleware:
Nuxt provides two globally available helpers that can be returned directly from the middleware.
1. `navigateTo (to: RouteLocationRaw | undefined | null, options?: { replace: boolean, redirectCode: number, external: boolean )` - Redirects to the given route, within plugins or middleware. It can also be called directly to perform page navigation.
2. `abortNavigation (err?: string | Error)` - Aborts the navigation, with an optional error message.
1. [`navigateTo`](/docs/api/utils/navigate-to) - Redirects to the given route
2. [`abortNavigation`](/docs/api/utils/abort-navigation) - Aborts the navigation, with an optional error message.
Unlike navigation guards in [the vue-router docs](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards), a third `next()` argument is not passed, and redirects or route cancellation is handled by returning a value from the middleware. Possible return values are:
Unlike [navigation guards](https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards) 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 - does not block navigation and will move to the next middleware function, if any, or complete the route navigation
* `return navigateTo('/')` or `return navigateTo({ path: '/' })` - redirects to the given path and will set the redirect code to [`302` Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) if the redirect happens on the server side
* `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/Status/302) 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/Status/301) if the redirect happens on the server side
::ReadMore{link="/docs/api/utils/navigate-to"}
::
* `return abortNavigation()` - stops the current navigation
* `return abortNavigation(error)` - rejects the current navigation with an error
::ReadMore{link="/docs/api/utils/abort-navigation"}
::
:read-more{to="/docs/api/utils/navigate-to"}
:read-more{to="/docs/api/utils/abort-navigation"}
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
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.html#global-before-guards) may work but there may be breaking changes in future.
::
## What Order Middleware Runs In
## Middleware Order
Middleware runs in the following order:
@ -105,14 +105,14 @@ 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.
```text [middleware/ directory]
```text [Directory structure]
middleware/
--| 01.setup.global.ts
--| 02.analytics.global.ts
--| auth.ts
```
::alert{type=info icon=💡}
::callout{color="blue" icon="i-ph-info-duotone"}
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`.
::
@ -122,7 +122,7 @@ If your site is server-rendered or generated, middleware for the initial page wi
However, if you want to avoid this behaviour you can do so:
```js
```js [middleware/example.ts]
export default defineNuxtRouteMiddleware(to => {
// skip middleware on server
if (process.server) return
@ -136,7 +136,7 @@ export default defineNuxtRouteMiddleware(to => {
## Adding Middleware Dynamically
It is possible to add global or named route middleware manually using the `addRouteMiddleware()` helper function, such as from within a plugin.
It is possible to add global or named route middleware manually using the [`addRouteMiddleware()`](/docs/api/utils/add-route-middleware) helper function, such as from within a plugin.
```ts
export default defineNuxtPlugin(() => {
@ -150,9 +150,9 @@ export default defineNuxtPlugin(() => {
})
```
## Example: A Named Route Middleware
## Example
```bash
```bash [Directory Structure]
-| middleware/
---| auth.ts
```
@ -170,5 +170,4 @@ definePageMeta({
Now, before navigation to that page can complete, the `auth` route middleware will be run.
::LinkExample{link="/docs/examples/routing/middleware"}
::
:link-example{to="/docs/examples/routing/middleware"}

View File

@ -1,13 +1,11 @@
---
navigation.icon: IconDirectory
title: 'modules'
head.title: 'modules/'
description: Use the modules/ directory to automatically register local modules within your application.
navigation.icon: i-ph-folder-duotone
---
# Modules Directory
Nuxt scans the [`modules/` directory](/docs/guide/directory-structure/modules) and loads them before starting. It is a good place to place any local modules you develop while building your application.
It is a good place to place any local modules you develop while building your application.
The auto-registered files patterns are:
- `modules/*/index.ts`
@ -50,11 +48,11 @@ When starting Nuxt, the `hello` module will be registered and the `/api/hello` r
Local modules are registered in alphabetical order. You can change the order by adding a number to the front of each directory name:
```md
```bash [Directory structure]
modules/
1.first-module/
index.ts
2.second-module.ts
```
:ReadMore{link="/docs/guide/going-further/modules"}
:read-more{to="/docs/guide/going-further/modules"}

View File

@ -1,10 +1,12 @@
---
navigation.icon: IconDirectory
title: "node_modules"
description: "The package manager stores the dependencies of your project in the node_modules/ directory."
head.title: "node_modules/"
navigation.icon: i-ph-folder-duotone
---
# Node modules Directory
The package manager ([`npm`](https://docs.npmjs.com/cli/commands/npm) or [`yarn`](https://yarnpkg.com/) or [`pnpm`](https://pnpm.io/cli/install) or [`bun`](https://bun.sh/package-manager)) creates this directory to store the dependencies of your project.
The package manager ([`npm`](https://docs.npmjs.com/cli/commands/npm) or [`yarn`](https://yarnpkg.com/) or [`pnpm`](https://pnpm.io/cli/install) or [`bun`](https://bun.sh/package-manager)) creates the [`node_modules/` directory](/docs/guide/directory-structure/node_modules) to store the dependencies of your project.
::callout
This directory should be added to your [`.gitignore`](/docs/guide/directory-structure/gitignore) file to avoid pushing the dependencies to your repository.
::

View File

@ -1,21 +1,19 @@
---
navigation.icon: IconDirectory
title: "pages"
description: "Nuxt provides a file-based routing to create routes within your web application."
head.title: "pages/"
navigation.icon: i-ph-folder-duotone
---
# Pages Directory
Nuxt provides a file-based routing to create routes within your web application using [Vue Router](https://router.vuejs.org) under the hood.
::alert{type="info"}
This directory is **optional**, meaning that [`vue-router`](https://router.vuejs.org) won't be included if you only use [app.vue](/docs/guide/directory-structure/app) (unless you set `pages: true` in `nuxt.config` or have a [`app/router.options.ts`](/docs/guide/directory-structure/pages#router-options)), reducing your application's bundle size.
::callout
To reduce your application's bundle size, this directory is **optional**, meaning that [`vue-router`](https://router.vuejs.org) won't be included if you only use [`app.vue`](/docs/guide/directory-structure/app). To force the pages sytem, set `pages: true` in `nuxt.config` or have a [`app/router.options.ts`](/docs/guide/directory-structure/pages#router-options).
::
## Usage
Pages are Vue components and can have any [valid extension](https://nuxt.com/docs/api/configuration/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.
Pages are Vue components and can have any [valid extension](/docs/api/configuration/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
@ -48,7 +46,7 @@ export default defineComponent({
The `pages/index.vue` file will be mapped to the `/` route of your application.
If you are using [app.vue](/docs/guide/directory-structure/app), make sure to use the `<NuxtPage/>` component to display the current page:
If you are using [`app.vue`](/docs/guide/directory-structure/app), make sure to use the [`<NuxtPage/>`](/docs/api/components/nuxt-page) component to display the current page:
```vue [app.vue]
<template>
@ -59,7 +57,7 @@ If you are using [app.vue](/docs/guide/directory-structure/app), make sure to us
</template>
```
Pages **must have a single root element** to allow route transitions between pages. (HTML comments are considered elements as well.)
Pages **must have a single root element** to allow [route transitions](/docs/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.
@ -99,9 +97,7 @@ If you place anything within square brackets, it will be turned into a [dynamic
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`.
### Example
```bash
```bash [Directory Structure]
-| pages/
---| index.vue
---| users-[group]/
@ -134,8 +130,8 @@ if (route.params.group === 'admins' && !route.params.id) {
</script>
```
::alert{type="info"}
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` . Use `~/pages/foo/index.vue` and `~/pages/foo/[slug].vue` to match `/foo` and `/foo/hello` with different pages,.
::callout
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,.
::
## Catch-all Route
@ -160,7 +156,7 @@ It is possible to display [nested routes](https://next.router.vuejs.org/guide/es
Example:
```bash
```bash [Directory Structure]
-| pages/
---| parent/
------| child.vue
@ -220,8 +216,7 @@ definePageMeta({
</script>
```
::LinkExample{link="/docs/examples/routing/pages"}
::
:link-example{to="/docs/examples/routing/pages"}
## Page Metadata
@ -276,7 +271,7 @@ Nuxt will automatically wrap your page in [the Vue `<KeepAlive>` component](http
When your goal is to preserve state for parent routes use this syntax: `<NuxtPage keepalive />`. You can also set props to be passed to `<KeepAlive>` (see a full list [here](https://vuejs.org/api/built-in-components.html#keepalive)).
You can set a default value for this property [in your `nuxt.config`](/docs/api/configuration/nuxt-config#keepalive).
You can set a default value for this property [in your `nuxt.config`](/docs/api/nuxt-config#keepalive).
#### `key`
@ -290,7 +285,7 @@ You can define the layout used to render the route. This can be either false (to
You can define transition properties for the `<transition>` component that wraps your pages and layouts, or pass `false` to disable the `<transition>` wrapper for that route. You can see a list of options that can be passed [here](https://vuejs.org/api/built-in-components.html#transition) or read [more about how transitions work](https://vuejs.org/guide/built-ins/transition.html#transition).
You can set default values for these properties [in your `nuxt.config`](/docs/api/configuration/nuxt-config#layouttransition).
You can set default values for these properties [in your `nuxt.config`](/docs/api/nuxt-config#layouttransition).
#### `middleware`
@ -333,8 +328,8 @@ A simple link to the `index.vue` page in your `pages` folder:
</template>
```
::alert{type="info"}
Learn more about [`<NuxtLink>`](/docs/api/components/nuxt-link) usage.
::read-more{to="/docs/api/components/nuxt-link"}
Learn more about `<NuxtLink>` usage.
::
## Programmatic Navigation
@ -364,32 +359,32 @@ function navigate(){
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.
:ReadMore{link="/docs/guide/going-further/custom-routing"}
:read-more{to="/docs/guide/going-further/custom-routing"}
## Multiple pages directories
By default, all your pages should be in one `pages` directory at the root of your project.
However, you can use Layers to create groupings of your app's pages.
Example:
However, you can use [Nuxt Layers](/docs/getting-started/layers) to create groupings of your app's pages:
```bash
-| nuxt.config.ts
```bash [Directory Structure]
-| some-app/
---| nuxt.config.ts
---| pages
-----| app-page.vue
-| nuxt.config.ts
```
```ts
```ts [some-app/nuxt.config.ts]
// some-app/nuxt.config.ts
export default defineNuxtConfig({
})
```
// nuxt.config.ts
```ts [nuxt.config.ts]
export default defineNuxtConfig({
extends: ['./some-app'],
})
```
:ReadMore{link="/docs/guide/going-further/layers"}
:read-more{to="/docs/guide/going-further/layers"}

View File

@ -1,40 +1,51 @@
---
navigation.icon: IconDirectory
title: "plugins"
description: "Nuxt reads the files in your plugins directory and loads them at the creation of the Vue application."
description: "Nuxt has a plugins system to use Vue plugins and more at the creation of your Vue application."
head.title: "plugins/"
navigation.icon: i-ph-folder-duotone
---
# Plugins Directory
Nuxt automatically reads the files in the `plugins/` directory and loads them at the creation of the Vue application.
Nuxt automatically reads the files in your `plugins` directory and loads them at the creation of the Vue application. You can use `.server` or `.client` suffix in the file name to load a plugin only on the server or client side.
::alert{type=warning}
All plugins in your [`plugins/` directory](/docs/guide/directory-structure/plugins) are auto-registered, so you should not add them to your `nuxt.config` separately.
::callout{color="blue" icon="i-ph-info-duotone"}
All plugins inside are auto-registered, you don't need not add them to your `nuxt.config` separately.
::
## Which Files Are Registered
::callout{color="yellow" icon="i-ph-lightbulb-duotone"}
You can use `.server` or `.client` suffix in the file name to load a plugin only on the server or client side.
::
Only files at the top level of the [`plugins/` directory](/docs/guide/directory-structure/plugins) (or index files within any subdirectories) will be registered as plugins.
## Registered Plugins
For example:
Only files at the top level of the directory (or index files within any subdirectories) will be auto-registered as plugins.
```bash
plugins
| - myPlugin.ts // scanned
| - myOtherPlugin
| --- supportingFile.ts // not scanned
| --- componentToRegister.vue // not scanned
| --- index.ts // currently scanned but deprecated
```bash [Directory sturcture]
-| plugins/
---| foo.ts // scanned
---| bar/
-----| baz.ts // not scanned
-----| foz.vue // not scanned
-----| index.ts // currently scanned but deprecated
```
Only `myPlugin.ts` and `myOtherPlugin/index.ts` would be registered. You can configure [`plugins`](/docs/api/configuration/nuxt-config#plugins-1) to include unscanned files.
Only `foo.ts` and `bar/index.ts` would be registered.
To add plugins in subdirectories, you can use the [`plugins`](/docs/api/nuxt-config#plugins-1) option in `nuxt.config.ts`:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
plugins: [
'~/plugins/bar/baz',
'~/plugins/bar/foz'
]
})
```
## Creating Plugins
The only argument passed to a plugin is [`nuxtApp`](/docs/api/composables/use-nuxt-app).
```ts
```ts [plugins/hello.ts]
export default defineNuxtPlugin(nuxtApp => {
// Doing something with nuxtApp
})
@ -44,7 +55,7 @@ export default defineNuxtPlugin(nuxtApp => {
It is also possible to define a plugin using an object syntax, for more advanced use cases. For example:
```ts
```ts [plugins/hello.ts]
export default defineNuxtPlugin({
name: 'my-plugin',
enforce: 'pre', // or 'post'
@ -52,32 +63,29 @@ export default defineNuxtPlugin({
// this is the equivalent of a normal functional plugin
},
hooks: {
// You can directly register Nuxt app hooks here
// You can directly register Nuxt app runtime hooks here
'app:created'() {
const nuxtApp = useNuxtApp()
//
}
},
env: {
// Set this value to `false` if you don't want the plugin to run when rendering server-only or island components.
islands: true
}
})
```
You can also use the `env` property to define the environments in which your plugin will run.
- **islands**
- **default**: `true`
- **description**: You can set this value to `false` if you don't want the plugin to run when rendering server-only or island components.
::alert
If you are using an object-syntax plugin, the properties may be statically analyzed in future to produce a more optimized build. So you should not define them at runtime. For example, setting `enforce: process.server ? 'pre' : 'post'` would defeat any future optimization Nuxt is able to do for your plugins.
::callout
If you are using the object-syntax, the properties may be statically analyzed in future to produce a more optimized build. So you should not define them at runtime. :br
For example, setting `enforce: process.server ? 'pre' : 'post'` would defeat any future optimization Nuxt is able to do for your plugins.
::
## Plugin Registration Order
## Registration Order
You can control the order in which plugins are registered by prefixing with 'alphabetical' numbering to the file names.
For example:
```bash
```bash [Directory structure]
plugins/
| - 01.myPlugin.ts
| - 02.myOtherPlugin.ts
@ -87,15 +95,15 @@ In this example, `02.myOtherPlugin.ts` will be able to access anything that was
This is useful in situations where you have a plugin that depends on another plugin.
::alert{type=info icon=💡}
::callout{color="blue" icon="i-ph-info-duotone"}
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
## Loading Strategy
By default, Nuxt loads plugins sequentially. You can define a plugin as `parallel` so Nuxt won't wait the end of the plugin's execution before loading the next plugin.
```ts
```ts [plugins/hello.ts]
export default defineNuxtPlugin({
name: 'my-plugin',
parallel: true,
@ -105,31 +113,35 @@ export default defineNuxtPlugin({
})
```
## Using Composables Within Plugins
## Using Composables
You can use [composables](/docs/guide/directory-structure/composables) within Nuxt plugins:
You can use [composables](/docs/guide/directory-structure/composables) as well as [utils](/docs/guide/directory-structure/utils) within Nuxt plugins:
```ts
export default defineNuxtPlugin((NuxtApp) => {
```ts [plugins/hello.ts]
export default defineNuxtPlugin((nuxtApp) => {
const foo = useFoo()
})
```
However, keep in mind there are some limitations and differences:
**If a composable depends on another plugin registered later, it might not work.**
::callout
**If a composable depends on another plugin registered later, it might not work.** :br
**Reason:** 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.
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.
::
**If a composable depends on the Vue.js lifecycle, it won't work.**
::callout
**If a composable depends on the Vue.js lifecycle, it won't work.** :br
**Reason:** Normally, Vue.js composables are bound to the current component instance while plugins are only bound to `nuxtApp` instance.
Normally, Vue.js composables are bound to the current component instance while plugins are only bound to [`nuxtApp`](/docs/api/composables/use-nuxt-app) instance.
::
## Automatically Providing Helpers
## Providing Helpers
If you would like to provide a helper on the `NuxtApp` instance, return it from the plugin under a `provide` key. For example:
If you would like to provide a helper on the [`NuxtApp`](/docs/api/composables/use-nuxt-app) instance, return it from the plugin under a `provide` key.
```ts
```ts [plugins/hello.ts]
export default defineNuxtPlugin(() => {
return {
provide: {
@ -139,9 +151,9 @@ export default defineNuxtPlugin(() => {
})
```
In another file you can use this:
You can then use the helper in your components:
```vue
```vue [components/Hello.vue]
<script setup lang="ts">
// alternatively, you can also use it here
const { $hello } = useNuxtApp()
@ -154,16 +166,18 @@ const { $hello } = useNuxtApp()
</template>
```
::callout{color="amber" icon="i-ph-warning-duotone"}
Note that we highly recommend using [`composables`](/docs/guide/directory-structure/composables) instead of providing helpers to avoid polluting the global namespace and keep your main bundle entry small.
::
## Typing Plugins
If you return your helpers from the plugin, they will be typed automatically; you'll find them typed for the return of `useNuxtApp()` and within your templates.
::alert
If you need to use a provided helper _within_ another plugin, you can call `useNuxtApp()` to get the typed version. But in general, this should be avoided unless you are certain of the plugins' order.
::callout
If you need to use a provided helper _within_ another plugin, you can call [`useNuxtApp()`](/docs/api/composables/use-nuxt-app) to get the typed version. But in general, this should be avoided unless you are certain of the plugins' order.
::
### Advanced
For advanced use-cases, you can declare the type of injected properties like this:
```ts [index.d.ts]
@ -179,10 +193,10 @@ declare module 'vue' {
}
}
export { }
export {}
```
::alert{type=warning}
::callout
If you are using WebStorm, you may need to augment `@vue/runtime-core` until [this issue](https://youtrack.jetbrains.com/issue/WEB-59818/VUE-TypeScript-WS-PS-does-not-correctly-display-type-of-globally-injected-properties) is resolved.
::
@ -190,15 +204,26 @@ If you are using WebStorm, you may need to augment `@vue/runtime-core` until [th
If you want to use Vue plugins, like [vue-gtag](https://github.com/MatteoGabriele/vue-gtag) to add Google Analytics tags, you can use a Nuxt plugin to do so.
First, install the plugin you want.
First, install the Vue plugin dependency:
```bash
::code-group
```bash [yarn]
yarn add --dev vue-gtag-next
```
```bash [npm]
npm install --save-dev vue-gtag-next
```
```bash [pnpm]
pnpm add -D vue-gtag-next
```
```bash [bun]
bun add -D vue-gtag-next
```
::
Then create a plugin file `plugins/vue-gtag.client.js`.
Then create a plugin file:
```ts
```ts [plugins/vue-gtag.client.ts]
import VueGtag, { trackRouter } from 'vue-gtag-next'
export default defineNuxtPlugin((nuxtApp) => {
@ -213,9 +238,9 @@ export default defineNuxtPlugin((nuxtApp) => {
## Vue Directives
Similarly, you can register a custom Vue directive in a plugin. For example, in `plugins/directive.ts`:
Similarly, you can register a custom Vue directive in a plugin.
```ts
```ts [plugins/my-directive.ts]
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.directive('focus', {
mounted (el) {
@ -229,8 +254,8 @@ export default defineNuxtPlugin((nuxtApp) => {
})
```
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
If you register a Vue directive, you _must_ register it on both client and server side unless you are only using it when rendering one side. If the directive only makes sense from a client side, you can always move it to `~/plugins/my-directive.client.ts` and provide a 'stub' directive for the server in `~/plugins/my-directive.server.ts`.
::
:ReadMore{link="https://vuejs.org/guide/reusability/custom-directives.html"}
:read-more{icon="i-simple-icons-vuedotjs" title="Custom Directives on Vue Docs" to="https://vuejs.org/guide/reusability/custom-directives.html" target="_blank"}

View File

@ -1,14 +1,27 @@
---
navigation.icon: IconDirectory
title: "public"
description: "The public/ directory is used to serve your website's static assets."
head.title: "public/"
navigation.icon: i-ph-folder-duotone
---
# Public Directory
The `public/` is served at the server root and contains public files that have to keep their names (e.g. `robots.txt`) _or_ likely won't change (e.g. `favicon.ico`).
The [`public/` directory](/docs/guide/directory-structure/public) is directly served at the server root and contains public files that have to keep their names (e.g. `robots.txt`) _or_ likely won't change (e.g. `favicon.ico`).
```bash [Directory structure]
-| public/
---| favicon.ico
---| og-image.png
---| robots.txt
```
::alert{icon=💡}
This is known as the [`static/` directory](https://nuxtjs.org/docs/directory-structure/static) in Nuxt 2.
```vue [app.vue]
<script setup>
useSeoMeta({
ogImage: '/og-image.png'
})
</script>
```
::callout{to="https://v2.nuxt.com/docs/directory-structure/static" target="_blank"}
This is known as the [`static/`] directory in Nuxt 2.
::

View File

@ -1,23 +1,26 @@
---
navigation.icon: IconDirectory
title: server
head.title: 'server/'
description: The server/ directory is used to register API and server handlers to your application.
navigation.icon: i-ph-folder-duotone
---
# Server Directory
Nuxt automatically scans files inside these directories to register API and server handlers with HMR support.
Nuxt automatically scans files inside these directories to register API and server handlers with HMR support:
- `~/server/api`
- `~/server/routes`
- `~/server/middleware`
```bash [Directory structure]
-| server/
---| api/
-----| hello.ts # /api/hello
---| routes/
-----| bonjour.ts # /bonjour
---| middleware/
-----| log.ts # log all requests
```
Each file should export a default function defined with `defineEventHandler()` or `eventHandler()` (alias).
The handler can directly return JSON data, a `Promise`, or use `event.node.res.end()` to send a response.
**Example:** Create the `/api/hello` route with `server/api/hello.ts` file:
```ts [server/api/hello.ts]
export default defineEventHandler((event) => {
return {
@ -38,10 +41,6 @@ const { data } = await useFetch('/api/hello')
</template>
```
Note that [h3 utilities](https://github.com/unjs/h3#utilities) are auto-imported.
:ReadMore{link="https://nitro.unjs.io/guide/routing" title="Nitro Route Handling Docs"}
## Server Routes
Files inside the `~/server/api` are automatically prefixed with `/api` in their route.
@ -56,8 +55,8 @@ export default defineEventHandler(() => 'Hello World!')
Given the example above, the `/hello` route will be accessible at <http://localhost:3000/hello>.
::alert{type=info icon=💡}
Note that currently server routes do not support the full functionality of dynamic routes as [pages](https://nuxt.com/docs/guide/directory-structure/pages#dynamic-routes) do.
::callout
Note that currently server routes do not support the full functionality of dynamic routes as [pages](/docs/guide/directory-structure/pages#dynamic-routes) do.
::
## Server Middleware
@ -66,7 +65,7 @@ Nuxt will automatically read in any file in the `~/server/middleware` to create
Middleware handlers will run on every request before any other server route to add or check headers, log requests, or extend the event's request object.
::alert{type=warning}
::callout
Middleware handlers should not return anything (nor close or respond to the request) and only inspect or extend the request context or throw an error.
::
@ -96,13 +95,13 @@ export default defineNitroPlugin((nitroApp) => {
})
```
:ReadMore{link="https://nitro.unjs.io/guide/plugins" title="Nitro Plugins"}
:read-more{to="https://nitro.unjs.io/guide/plugins" title="Nitro Plugins" target="_blank"}
## Server Utilities
Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers.
:ReadMore{link="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers"}
:read-more{to="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers" target="_blank"}
You can add more helpers yourself inside the `~/server/utils` directory.
@ -131,7 +130,7 @@ export const defineWrappedResponseHandler = <T extends EventHandlerRequest, D> (
## Server Types
::alert{type="info"}
::callout
This feature is available from Nuxt >= 3.5
::
@ -143,24 +142,23 @@ To improve clarity within your IDE between the auto-imports from 'nitro' and 'vu
}
```
Although right now these values won't be respected when type checking (`nuxi typecheck`), you should get better type hints in your IDE.
Although right now these values won't be respected when type checking ([`nuxi typecheck`](/docs/api/commands/typecheck)), you should get better type hints in your IDE.
## Usage Examples
## Recipes
### Matching Route Parameters
### Route Parameters
Server routes can use dynamic parameters within brackets in the file name like `/api/hello/[name].ts` and be accessed via `event.context.params`.
**Example:**
```ts [server/api/hello/[name\\].ts]
export default defineEventHandler((event) => {
const name = getRouterParam(event, 'name')
return `Hello, ${name}!`
})
```
You can now universally call this API using `await $fetch('/api/hello/nuxt')` and get `Hello, nuxt!`.
You can now universally call this API on `/api/hello/nuxt` and get `Hello, nuxt!`.
### Matching HTTP Method
@ -180,53 +178,50 @@ Given the example above, fetching `/test` with:
- **POST** method: Returns `Test post handler`
- Any other method: Returns 405 error
You can also use `index.[method].ts` inside a directory for structuring your code differently.
**Example:**
```ts [server/api/foo/index.ts]
export default defineEventHandler((event) => {
// handle the `api/foo` endpoint
})
```
This is useful to create API namespaces.
**Examples:**
You can also use `index.[method].ts` inside a directory for structuring your code differently, this is useful to create API namespaces.
::code-group
```ts [server/api/foo/index.get.ts]
export default defineEventHandler((event) => {
// handle GET requests for the `api/foo` endpoint
})
```
```ts [server/api/foo/index.post.ts]
export default defineEventHandler((event) => {
// handle POST requests for the `api/foo` endpoint
})
```
```ts [server/api/foo/bar.get.ts]
export default defineEventHandler((event) => {
// handle GET requests for the `api/foo/bar` endpoint
})
```
::
### Catch-all Route
Catch-all routes are helpful for fallback route handling. For example, creating a file named `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`.
Catch-all routes are helpful for fallback route handling.
**Examples:**
For example, creating a file named `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`.
```ts [server/api/foo/[...\\].ts]
export default defineEventHandler(() => `Default foo handler`)
export default defineEventHandler((event) => {
// event.context.path to get the route path: '/api/foo/bar/baz'
// event.context.params._ to get the route segment: 'bar/baz'
return `Default foo handler`
})
```
```ts [server/api/[...\\].ts]
export default defineEventHandler(() => `Default api handler`)
You can set a name for the catch-all route by using `~/server/api/foo/[...slug].ts` and access it via `event.context.params.slug`.
```ts [server/api/foo/[...slug\\].ts]
export default defineEventHandler((event) => {
// event.context.params.slug to get the route segment: 'bar/baz'
return `Default foo handler`
})
```
### Handling Requests with Body
### Body Handling
```ts [server/api/submit.post.ts]
export default defineEventHandler(async (event) => {
@ -235,32 +230,47 @@ export default defineEventHandler(async (event) => {
})
```
You can now universally call this API using `$fetch('/api/submit', { method: 'post', body: { test: 123 } })`.
You can now universally call this API using:
::alert{type=warning title=Attention}
```vue [app.vue]
<script setup>
async function submit() {
const { body } = await $fetch('/api/submit', {
method: 'post',
body: { test: 123 }
})
}
</script>
```
::callout
We are using `submit.post.ts` in the filename only to match requests with `POST` method that can accept the request body. When using `readBody` within a GET request, `readBody` will throw a `405 Method Not Allowed` HTTP error.
::
### Handling Requests With Query Parameters
### Query Parameters
Sample query `/api/query?param1=a&param2=b`
Sample query `/api/query?foo=bar&baz=qux`
```ts [server/api/query.get.ts]
export default defineEventHandler((event) => {
const query = getQuery(event)
return { a: query.param1, b: query.param2 }
return { a: query.foo, b: query.baz }
})
```
### Error handling
### Error Handling
If no errors are thrown, a status code of `200 OK` will be returned. Any uncaught errors will return a `500 Internal Server Error` HTTP Error.
If no errors are thrown, a status code of `200 OK` will be returned.
To return other error codes, throw an exception with `createError`
Any uncaught errors will return a `500 Internal Server Error` HTTP Error.
To return other error codes, throw an exception with [`createError`](/docs/api/utils/create-error):
```ts [server/api/validation/[id\\].ts]
export default defineEventHandler((event) => {
const id = parseInt(event.context.params.id) as number
if (!Number.isInteger(id)) {
throw createError({
statusCode: 400,
@ -271,9 +281,9 @@ export default defineEventHandler((event) => {
})
```
### Returning other status codes
### Status Codes
To return other status codes, you can use the `setResponseStatus` utility.
To return other status codes, use the [`setResponseStatus`](/docs/api/utils/set-response-status) utility.
For example, to return `202 Accepted`
@ -283,32 +293,55 @@ export default defineEventHandler((event) => {
})
```
### Accessing Runtime Config
### Runtime Config
::code-group
```ts [server/api/foo.ts]
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig(event)
export default defineEventHandler((event) => {
const config = useRuntimeConfig()
return { key: config.KEY }
const repo = await $fetch('https://api.github.com/repos/nuxt/nuxt', {
headers: {
Authorization: `token ${config.githubToken}`
}
})
return repo
})
```
```ts [nuxt.config.ts]
export default defineNuxtConfig({
runtimeConfig: {
githubToken: ''
}
})
```
```bash [.env]
NUXT_GITHUB_TOKEN='<my-super-token>'
```
::
### Accessing Request Cookies
::callout
Giving the `event` as argument to `useRuntimeConfig` is optional, but it is recommended to pass it to get the runtime config overwritten by [environment variables](/docs/guide/going-further/runtime-config#environment-variables) at runtime for server routes.
::
```ts
### Request Cookies
```ts [server/api/cookies.ts]
export default defineEventHandler((event) => {
const cookies = parseCookies(event)
return { cookies }
})
```
## Advanced Usage Examples
## Advanced Usage
### Nitro Configuration
### Nitro Config
You can use `nitro` key in `nuxt.config` to directly set [Nitro configuration](https://nitro.unjs.io/config).
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
This is an advanced option. Custom config can affect production deployments, as the configuration interface might change over time when Nitro is upgraded in semver-minor versions of Nuxt.
::
@ -319,7 +352,9 @@ export default defineNuxtConfig({
})
```
### Using a Nested Router
:read-more{to="/docs/guide/concepts/server-engine"}
### Nested Router
```ts [server/api/hello/[...slug\\].ts]
import { createRouter, defineEventHandler, useBase } from 'h3'
@ -331,9 +366,11 @@ router.get('/test', defineEventHandler(() => 'Hello World'))
export default useBase('/api/hello', router.handler)
```
### Sending Streams (Experimental)
### Sending Streams
**Note:** This is an experimental feature and is only available within Node.js environments.
::callout
This is an experimental feature and is only available in all environments.
::
```ts [server/api/foo.get.ts]
import fs from 'node:fs'
@ -352,7 +389,7 @@ export default defineEventHandler(async (event) => {
})
```
### Return a Legacy Handler or Middleware
### Legacy Handler or Middleware
```ts [server/api/legacy.ts]
export default fromNodeMiddleware((req, res) => {
@ -360,7 +397,7 @@ export default fromNodeMiddleware((req, res) => {
})
```
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
Legacy support is possible using [unjs/h3](https://github.com/unjs/h3), but it is advised to avoid legacy handlers as much as you can.
::
@ -371,15 +408,15 @@ export default fromNodeMiddleware((req, res, next) => {
})
```
::alert{type=warning}
Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`!
::callout{color="amber" icon="i-ph-warning-duotone"}
Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`.
::
### Server Storage
Nitro provides a cross-platform [storage layer](https://nitro.unjs.io/guide/storage). In order to configure additional storage mount points, you can use `nitro.storage`, or [server plugins](#server-plugins).
#### Example: Using Redis
**Example of adding a Redis storage:**
Using `nitro.storage`:
@ -387,7 +424,7 @@ Using `nitro.storage`:
export default defineNuxtConfig({
nitro: {
storage: {
'redis': {
redis: {
driver: 'redis',
/* redis connector options */
port: 6379, // Redis port
@ -402,10 +439,30 @@ export default defineNuxtConfig({
})
```
Alternatively, using server plugins:
Then in your API handler:
```ts [server/api/storage/test.ts]
export default defineEventHandler(async (event) => {
// List all keys with
const keys = await useStorage('redis').getKeys()
// Set a key with
await useStorage('redis').setItem('foo', 'bar')
// Remove a key with
await useStorage('redis').removeItem('foo')
return {}
})
```
::read-more{to="https://nitro.unjs.io/guide/storage" target="_blank"}
Read more about Nitro Storage Layer.
::
Alternatively, you can create a storage mount point using a server plugin and runtime config:
::code-group
```ts [server/plugins/storage.ts]
import redisDriver from 'unstorage/drivers/redis'
@ -436,45 +493,4 @@ export default defineNuxtConfig({
}
})
```
::
Create a new file in `server/api/test.post.ts`:
```ts [server/api/test.post.ts]
export default defineEventHandler(async (event) => {
const body = await readBody(event)
await useStorage().setItem('redis:test', body)
return 'Data is set'
})
```
Create a new file in `server/api/test.get.ts`:
```ts [server/api/test.get.ts]
export default defineEventHandler(async (event) => {
const data = await useStorage().getItem('redis:test')
return data
})
```
Create a new file in `app.vue`:
```vue [app.vue]
<script setup lang="ts">
const { data: resDataSuccess } = await useFetch('/api/test', {
method: 'post',
body: { text: 'Nuxt is Awesome!' }
})
const { data: resData } = await useFetch('/api/test')
</script>
<template>
<div>
<div>Post state: {{ resDataSuccess }}</div>
<div>Get Data: {{ resData.text }}</div>
</div>
</template>
```
::ReadMore{link="/docs/guide/directory-structure/server"}

View File

@ -1,20 +1,49 @@
---
navigation.icon: IconDirectory
title: 'utils'
head.title: 'utils/'
description: Use the utils/ directory to auto-import your utility functions throughout your application.
navigation.icon: i-ph-folder-duotone
---
# Utils Directory
Nuxt 3 uses the [`utils/` directory](/docs/guide/directory-structure/utils) to automatically import helper functions and other utilities throughout your application using [auto-imports](/docs/guide/concepts/auto-imports)!
::alert{type=info}
The main purpose of the [`utils/` directory](/docs/guide/directory-structure/utils) is to allow a semantic distinction between your Vue composables and other auto-imported utility functions.
The way `utils/` auto-imports work and are scanned is identical to [the composables/ directory](/docs/guide/directory-structure/composables). You can see examples and more information about how they work in that section of the docs.
## Usage
**Method 1:** Using named export
```js [utils/index.ts]
export const { format: formatNumber } = Intl.NumberFormat('en-GB', {
notation: 'compact',
maximumFractionDigits: 1
})
```
**Method 2:** Using default export
```js [utils/random-entry.ts or utils/randomEntry.ts]
// It will be available as randomEntry() (camelCase of file name without extension)
export default function (arr: Array<any>) {
return arr[Math.floor(Math.random() * arr.length)]
}
```
You can now use auto imported utility functions in `.js`, `.ts` and `.vue` files
```vue [app.vue]
<template>
<p>{{ formatNumber(1234) }}</p>
</template>
```
:read-more{to="/docs/guide/concepts/auto-imports"}
:link-example{to="/docs/examples/features/auto-imports"}
::callout
The way `utils/` auto-imports work and are scanned is identical to the [`composables/`](/docs/guide/directory-structure/composables) directory.
::
::alert{type=info}
These utils are only available within the Vue part of your app. Within the [server directory](/docs/guide/directory-structure/server#server-utilities), we auto import exported functions and variables from `~/server/utils` instead.
::callout{color="amber" icon="i-ph-warning-duotone"}
These utils are only available within the Vue part of your app. :br
Only `server/utils` are auto-imported in the [`server/`](/docs/guide/directory-structure/server#server-utilities) directory.
::

View File

@ -1,50 +1,57 @@
---
navigation.icon: IconFile
title: ".env"
description: "A .env file specifies your build/dev-time environment variables."
head.title: ".env"
navigation.icon: i-ph-file-duotone
---
# .env File
## At Build, Dev, and Generate Time
Nuxt CLI has built-in [dotenv](https://github.com/motdotla/dotenv) support in development mode and when running `nuxi build` and `nuxi generate`.
In addition to any process environment variables, if you have a `.env` file in your project root directory, it will be automatically loaded **at build, dev, and generate time**, and any environment variables set there will be accessible within your `nuxt.config` file and modules.
::alert
If you want to use a different file - for example, to use `.env.local` or `.env.production` - you can do so by passing the `--dotenv` flag when using `nuxi`. For example:
```bash
npx nuxi dev --dotenv .env.local
```
Just as above, this will only apply in development mode and when running `nuxi build` and `nuxi generate`.
::callout{icon="i-ph-warning-duotone" color="amber"}
This file should be added to your [`.gitignore`](/docs/guide/directory-structure/gitignore) file to avoid pushing secrets to your repository.
::
When updating `.env` in development mode, the Nuxt instance is automatically restarted to apply new values to the `process.env`.
## Dev, Build and Generate Time
::alert{type=warning}
Nuxt CLI has built-in [dotenv](https://github.com/motdotla/dotenv) support in development mode and when running [`nuxi build`](/docs/api/commands/build) and [`nuxi generate`](/docs/api/commands/generate).
In addition to any process environment variables, if you have a `.env` file in your project root directory, it will be automatically loaded **at dev, build and generate time**. Any environment variables set there will be accessible within your `nuxt.config` file and modules.
```bash [.env]
MY_ENV_VARIABLE=hello
```
::callout
Note that removing a variable from `.env` or removing the `.env` file entirely will not unset values that have already been set.
::
## Custom File
If you want to use a different file - for example, to use `.env.local` or `.env.production` - you can do so by passing the `--dotenv` flag when using `nuxi`.
```bash [Terminal]
npx nuxi dev --dotenv .env.local
```
When updating `.env` in development mode, the Nuxt instance is automatically restarted to apply new values to the `process.env`.
## Production Preview
**After your server is built**, you are responsible for setting environment variables when you run the server. Your `.env` file will not be read at this point. How you do this is different for every environment.
**After your server is built**, you are responsible for setting environment variables when you run the server.
For local production preview purpose, we recommend using [`nuxi preview`](https://nuxt.com/docs/api/commands/preview) since using this command, the `.env` file will be loaded into `process.env` for convenience. Note that this command requires dependencies to be installed in the package directory.
Your `.env` file will not be read at this point. How you do this is different for every environment.
For local production preview purpose, we recommend using [`nuxi preview`](/docs/api/commands/preview) since using this command, the `.env` file will be loaded into `process.env` for convenience. Note that this command requires dependencies to be installed in the package directory.
Or you could pass the environment variables as arguments using the terminal. For example, on Linux or macOS:
```bash
```bash [Terminal]
DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs
```
Note that for a purely static site, it is not possible to set runtime configuration config after your project is prerendered.
:ReadMore{link="/docs/guide/going-further/runtime-config"}
:read-more{to="/docs/guide/going-further/runtime-config"}
::callout
If you want to use environment variables set at build time but do not care about updating these down the line (or only need to update them reactively _within_ your app) then `appConfig` may be a better choice. You can define `appConfig` both within your `nuxt.config` (using environment variables) and also within an `~/app.config.ts` file in your project.
:ReadMore{link="/docs/guide/directory-structure/app-config"}
:read-more{to="/docs/guide/directory-structure/app-config"}
::

View File

@ -1,13 +1,13 @@
---
navigation.icon: IconFile
title: ".gitignore"
description: "A .gitignore file specifies intentionally untracked files that git should ignore."
head.title: ".gitignore"
navigation.icon: i-ph-file-duotone
---
# Git Ignore File
A `.gitignore` file specifies intentionally untracked files that git should ignore.
A `.gitignore` file specifies intentionally untracked files that git should ignore. Learn more about it in [the git documentation](https://git-scm.com/docs/gitignore).
:read-more{icon="i-simple-icons-git" color="gray" title="the git documentation" to="https://git-scm.com/docs/gitignore" target="_blank"}
We recommend having a `.gitignore` file that has **at least** the following entries present:

View File

@ -1,17 +1,19 @@
---
navigation.icon: IconFile
title: .nuxtignore
head.title: '.nuxtignore'
description: The .nuxtignore file lets Nuxt ignore files in your projects root directory during the build phase.
navigation.icon: i-ph-file-duotone
---
# Nuxt Ignore File
The `.nuxtignore` file tells Nuxt to ignore files in your projects root directory ([`rootDir`](/docs/api/nuxt-config#rootdir)) during the build phase.
The `.nuxtignore` file lets Nuxt ignore `layouts`, `pages`, `components`, `composables` and `middleware` files in your projects root directory (`rootDir`) during the build phase. The `.nuxtignore` file is subject to the same specification as `.gitignore` and `.eslintignore` files, in which each line is a glob pattern indicating which files should be ignored.
It is subject to the same specification as [`.gitignore`](/docs/guide/directory-structure/gitignore) and `.eslintignore` files, in which each line is a glob pattern indicating which files should be ignored.
**Note**: You can also configure [`ignoreOptions`](/docs/api/configuration/nuxt-config#ignoreoptions), [`ignorePrefix`](/docs/api/configuration/nuxt-config#ignoreprefix) and [`ignore`](/docs/api/configuration/nuxt-config#ignore) in your `nuxt.config` file.
::callout
You can also configure [`ignoreOptions`](/docs/api/nuxt-config#ignoreoptions), [`ignorePrefix`](/docs/api/nuxt-config#ignoreprefix) and [`ignore`](/docs/api/nuxt-config#ignore) in your `nuxt.config` file.
::
## Example
## Usage
```bash [.nuxtignore]
# ignore layout foo.vue
@ -29,4 +31,6 @@ middleware/foo/*.js
!middleware/foo/bar.js
```
> More details about the spec are in the [gitignore doc](https://git-scm.com/docs/gitignore).
::read-more{icon="i-simple-icons-git" color="gray" title="the git documentation" to="https://git-scm.com/docs/gitignore" target="_blank"}
More details about the spec are in the **gitignore documentation**.
::

View File

@ -1,12 +1,10 @@
---
navigation.icon: IconFile
title: app.config.ts
head.title: 'app.config.ts'
description: Nuxt 3 provides the app.config file to expose reactive configuration within your application.
description: Expose reactive configuration within your application with the App Config file.
navigation.icon: i-ph-file-duotone
---
# App Config File
Nuxt 3 provides an `app.config` config file to expose reactive configuration within your application with the ability to update it at runtime within lifecycle or using a nuxt plugin and editing it with HMR (hot-module-replacement).
You can easily provide runtime app configuration using `app.config.ts` file. It can have either of `.ts`, `.js`, or `.mjs` extensions.
@ -17,16 +15,14 @@ export default defineAppConfig({
})
```
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
Do not put any secret values inside `app.config` file. It is exposed to the user client bundle.
::
## Defining App Config
## Usage
To expose config and environment variables to the rest of your app, you will need to define configuration in `app.config` file.
**Example:**
```ts [app.config.ts]
export default defineAppConfig({
theme: {
@ -35,21 +31,23 @@ export default defineAppConfig({
})
```
When adding `theme` to the `app.config`, Nuxt uses Vite or webpack to bundle the code. We can universally access `theme` both when server-rendering the page and in the browser using [useAppConfig](/docs/api/composables/use-app-config) composable.
When adding `theme` to the `app.config`, Nuxt uses Vite or webpack to bundle the code. We can universally access `theme` both when server-rendering the page and in the browser using [`useAppConfig`](/docs/api/composables/use-app-config) composable.
```js
```vue [pages/index.vue]
<script setup>
const appConfig = useAppConfig()
console.log(appConfig.theme)
</script>
```
### Manually Typing App Config
## Typing App Config
Nuxt tries to automatically generate a TypeScript interface from provided app config.
Nuxt tries to automatically generate a TypeScript interface from provided app config so you won't have to type it yourself.
It is also possible to type app config manually. There are two possible things you might want to type.
However, there are some cases where you might want to type it yourself. There are two possible things you might want to type.
#### Typing App Config Input
### App Config Input
`AppConfigInput` might be used by module authors who are declaring what valid _input_ options are when setting app config. This will not affect the type of `useAppConfig()`.
@ -68,11 +66,11 @@ declare module 'nuxt/schema' {
export {}
```
#### Typing App Config Output
### App Config Output
If you want to type the result of calling `useAppConfig()`, then you will want to extend `AppConfig`.
If you want to type the result of calling [`useAppConfig()`](/docs/api/composables/use-app-config), then you will want to extend `AppConfig`.
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
Be careful when typing `AppConfig` as you will overwrite the types Nuxt infers from your actually defined app config.
::
@ -92,12 +90,13 @@ declare module 'nuxt/schema' {
export {}
```
### App Config Merging Strategy in Layers
## Merging Strategy
Nuxt uses a custom merging strategy for the `AppConfig` within [the layers](/docs/getting-started/layers) of your application.
Nuxt uses a custom merging strategy for the `AppConfig` within the layers of your application.
This strategy is implemented using a [Function Merger](https://github.com/unjs/defu#function-merger), which allows defining a custom merging strategy for every key in `app.config` that has an array as value.
::alert{type=warning}
::callout
The Function Merger should only be used in the base `app.config` of your application.
::

View File

@ -1,15 +1,11 @@
---
navigation.icon: IconFile
title: "app.vue"
description: "The app.vue file is the main component in your Nuxt 3 applications."
description: "The app.vue file is the main component of your Nuxt application."
head.title: "app.vue"
navigation.icon: i-ph-file-duotone
---
# App file
The `app.vue` file is the main component in your Nuxt 3 applications.
## Minimal usage
## Minimal Usage
With Nuxt 3, the [`pages/`](/docs/guide/directory-structure/pages) directory is optional. If not present, Nuxt won't include [vue-router](https://router.vuejs.org/) dependency. This is useful when working on a landing page or an application that does not need routing.
@ -19,9 +15,11 @@ With Nuxt 3, the [`pages/`](/docs/guide/directory-structure/pages) directory is
</template>
```
## Usage With Pages
:link-example{to="/docs/examples/hello-world"}
If you have a [`pages/`](/docs/guide/directory-structure/pages) directory, to display the current page, use the `<NuxtPage>` component:
## Usage with Pages
If you have a [`pages/`](/docs/guide/directory-structure/pages) directory, to display the current page, use the [`<NuxtPage>`](/docs/api/components/nuxt-page) component:
```vue [app.vue]
<template>
@ -33,12 +31,14 @@ If you have a [`pages/`](/docs/guide/directory-structure/pages) directory, to di
</template>
```
::alert{type=danger}
Since `<NuxtPage>` internally uses the [`<Suspense>`](https://vuejs.org/guide/built-ins/suspense.html#suspense) component, `<NuxtPage>` cannot be set as a root element.
::callout{color="amber" icon="i-ph-warning-duotone"}
Since [`<NuxtPage>`](/docs/api/components/nuxt-page) internally uses Vue's [`<Suspense>`](https://vuejs.org/guide/built-ins/suspense.html#suspense) component, it cannot be set as a root element.
::
::alert{type=warning}
::callout{color="blue" icon="i-ph-info-duotone"}
Remember that `app.vue` acts as the main component of your Nuxt application. Anything you add to it (JS and CSS) will be global and included in every page.
::
If you want to have the possibility to customize the structure around the page between pages, check out the [`layouts/`](/docs/guide/directory-structure/layouts) directory.
::read-more{to="/docs/guide/directory-structure/layouts"}
If you want to have the possibility to customize the structure around the page between pages, check out the `layouts/` directory.
::

View File

@ -1,28 +1,26 @@
---
navigation.icon: IconFile
title: "nuxt.config.ts"
description: "Nuxt can be easily configured with a single nuxt.config file."
head.title: "nuxt.config.ts"
navigation.icon: i-ph-file-duotone
---
# Nuxt Config File
The `nuxt.config` file extension can either be `.js`, `.ts` or `.mjs`.
Nuxt can be easily configured with a single `nuxt.config` file, which can have either a `.js`, `.ts` or `.mjs` extension.
```ts
```ts [nuxt.config.ts]
export default defineNuxtConfig({
// My Nuxt config
})
```
::alert
::callout
`defineNuxtConfig` helper is globally available without import.
::
You can explicitly import `defineNuxtConfig` from `nuxt/config` if you prefer:
```js
```ts [nuxt.config.ts]
import { defineNuxtConfig } from 'nuxt/config'
export default defineNuxtConfig({
@ -30,7 +28,17 @@ export default defineNuxtConfig({
})
```
To ensure your configuration is up to date, Nuxt will make a full restart when detecting changes in the main configuration file, the `.env`, `.nuxtignore` and `.nuxtrc` dotfiles.
::ReadMore{link="/docs/api/configuration/nuxt-config"}
::read-more{to="/docs/api/configuration/nuxt-config"}
Discover all the available options in the **Nuxt configuration** documentation.
::
To ensure your configuration is up to date, Nuxt will make a full restart when detecting changes in the main configuration file, the [`.env`](/docs/guide/directory-structure/env), [`.nuxtignore`](/docs/guide/directory-structure/nuxtignore) and `.nuxtrc` dotfiles.
The `.nuxtrc` file is a file that can be used to configure Nuxt with a fla syntax, it is based on [`unjs/rc9`](https://github.com/unjs/rc9).
``` [.nuxtrc]
ssr=false
```
If prevent the properties in `.nuxtrc` file will overwrite the properties in the `nuxt.config` file.

View File

@ -1,10 +1,33 @@
---
navigation.icon: IconFile
title: package.json
head.title: package.json
description: The package.json file contains all the dependencies and scripts for your application.
navigation.icon: i-ph-file-duotone
---
# Package.json File
The minimal `package.json` of your Nuxt application should looks like:
The `package.json` file contains all the dependencies and scripts for your application ([learn more](https://docs.npmjs.com/cli/configuring-npm/package-json)).
```json [package.json]
{
"name": "nuxt-app",
"private": true,
"type": "module",
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"@nuxt/devtools": "latest",
"nuxt": "latest",
"vue": "latest",
"vue-router": "latest"
}
}
```
::read-more{icon="i-simple-icons-npm" color="gray" to="https://docs.npmjs.com/cli/configuring-npm/package-json" target="_blank"}
Read more about the `package.json` file.
::

View File

@ -1,18 +1,24 @@
---
navigation.icon: IconFile
title: "tsconfig.json"
description: "Nuxt generates a .nuxt/tsconfig.json file with sensible defaults and your aliases."
head.title: "tsconfig.json"
navigation.icon: i-ph-file-duotone
---
# TypeScript Configuration File
Nuxt [automatically generates](/docs/guide/concepts/typescript) a `.nuxt/tsconfig.json` file with the resolved aliases you are using in your Nuxt project, as well as with other sensible defaults.
Nuxt [automatically generates](/docs/guide/concepts/typescript) a `.nuxt/tsconfig.json` file with the resolved aliases you are using in your Nuxt project, as well as with other sensible defaults. You can benefit from this by creating a `tsconfig.json` in the root of your project with the following content:
You can benefit from this by creating a `tsconfig.json` in the root of your project with the following content:
```json
```json [tsconfig.json]
{
"extends": "./.nuxt/tsconfig.json"
}
```
As you need to, you can customize the contents of this file. However, it is recommended that you don't overwrite `target`, `module` and `moduleResolution`. Moreover, note that if you need to customize your `paths`, this will override the auto-generated path aliases. Instead, we recommend that you add any path aliases you need to the `alias` property within your `nuxt.config`, where they will get picked up and added to the auto-generated `tsconfig`.
::callout
As you need to, you can customize the contents of this file. However, it is recommended that you don't overwrite `target`, `module` and `moduleResolution`.
::
::callout
If you need to customize your `paths`, this will override the auto-generated path aliases. Instead, we recommend that you add any path aliases you need to the [`alias`](/docs/api/nuxt-config#alias) property within your `nuxt.config`, where they will get picked up and added to the auto-generated `tsconfig`.
::

View File

@ -1,4 +1,3 @@
title: Directory Structure
titleTemplate: '%s · Nuxt Directory Structure'
navigation.icon: uil:folder-open
image: '/socials/directory-structure.jpg'
icon: i-ph-folders-duotone

View File

@ -1,4 +0,0 @@
---
navigation: false
redirect: /guide/directory-structure/nuxt
---

View File

@ -1,31 +1,42 @@
---
title: "Experimental Features"
description: "Nuxt experimental features needs to be enabled manually."
description: "Enable Nuxt experimental features to unlock new possibilities."
---
# Experimental Features
The Nuxt experimental features can be enabled in the Nuxt configuration file.
Internally, Nuxt uses `@nuxt/schema` to define these experimental features. You can refer to the [API documentation](https://nuxt.com/docs/api/configuration/nuxt-config#experimental) or the [source code](https://github.com/nuxt/nuxt/blob/main/packages/schema/src/config/experimental.ts) for more information.
::alert{type=info icon=💡}
Internally, Nuxt uses `@nuxt/schema` to define these experimental features. You can refer to the [API documentation](/docs/api/configuration/nuxt-config#experimental) or the [source code](https://github.com/nuxt/nuxt/blob/main/packages/schema/src/config/experimental.ts) for more information.
::callout
Note that these features are experimental and could be removed or modified in the future.
::
## asyncContext
Enable native async context to be accessible for nested composables in Nuxt and in Nitro. See [full explanation in #20918](https://github.com/nuxt/nuxt/pull/20918).
Enable native async context to be accessible for nested composables in Nuxt and in Nitro. This opens the possibility to use composables inside async composables and reduce the chance to get the `Nuxt instance is unavailable` error.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { asyncContext: true } })
export defineNuxtConfig({
experimental: {
asyncContext: true
}
})
```
::read-more{icon="i-simple-icons-github" color="gray" to="https://github.com/nuxt/nuxt/pull/20918" target="_blank"}
See full explanation on the GitHub pull-request.
::
## asyncEntry
Enables generation of an async entry point for the Vue bundle, aiding module federation support.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { asyncEntry: true } })
export defineNuxtConfig({
experimental: {
asyncEntry: true
}
})
```
## reactivityTransform
@ -33,65 +44,111 @@ export defineNuxtConfig({ experimental: { asyncEntry: true } })
Enables Vue's reactivity transform. Note that this feature has been marked as deprecated in Vue 3.3 and is planned to be removed from core in Vue 3.4.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { reactivityTransform: true } })
export defineNuxtConfig({
experimental: {
reactivityTransform: true
}
})
```
::ReadMore{link="/docs/getting-started/configuration#enabling-experimental-vue-features"}
::
:read-more{to="/docs/getting-started/configuration#enabling-experimental-vue-features"}
## externalVue
Externalizes `vue`, `@vue/*` and `vue-router` when building.
*Enabled by default.*
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { externalVue: true } })
export defineNuxtConfig({
experimental: {
externalVue: true
}
})
```
::alert{type=warning icon=⚠️}
This feature will likely be removed in Nuxt 3.6.
::callout{color="amber" icon="i-ph-warning-duotone"}
This feature will likely be removed in a near future.
::
## treeshakeClientOnly
Tree shakes contents of client-only components from server bundle.
*Enabled by default.*
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { treeshakeClientOnly: true } })
export defineNuxtConfig({
experimental: {
treeshakeClientOnly: true
}
})
```
## emitRouteChunkError
Emits `app:chunkError` hook when there is an error loading vite/webpack chunks. Default behavior is to perform a hard reload of the new route when a chunk fails to load.
You can disable automatic handling by setting this to `false`, or handle chunk errors manually by setting it to `manual`.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { emitRouteChunkError: 'automatic' } }) // or 'manual' or false
export defineNuxtConfig({
experimental: {
emitRouteChunkError: 'automatic' // or 'manual' or false
}
})
```
## restoreState
Allows Nuxt app state to be restored from `sessionStorage` when reloading the page after a chunk error or manual `reloadNuxtApp()` call.
To avoid hydration errors, it will be applied only after the Vue app has been mounted,
meaning there may be a flicker on initial load.
Allows Nuxt app state to be restored from `sessionStorage` when reloading the page after a chunk error or manual [`reloadNuxtApp()`](/docs/api/utils/reload-nuxt-app) call.
::alert{type=warning icon=⚠️}
To avoid hydration errors, it will be applied only after the Vue app has been mounted, meaning there may be a flicker on initial load.
::callout{color="amber" icon="i-ph-warning-duotone"}
Consider carefully before enabling this as it can cause unexpected behavior,
and consider providing explicit keys to [`useState`](/docs/api/composables/use-state) as auto-generated keys may not match across builds.
::
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { restoreState: true } })
export defineNuxtConfig({
experimental: {
restoreState: true
}
})
```
## inlineRouteRules
Define route rules at the page level using [`defineRouteRules`](/docs/api/utils/define-route-rules).
```ts [nuxt.config.ts]
export defineNuxtConfig({
experimental: {
inlineRouteRules: true
}
})
```
Matching route rules will be created, based on the page's `path`.
::read-more{to="/docs/api/utils/define-route-rules" icon="i-ph-function-duotone"}
Read more in `defineRouteRules` utility.
::
:read-more{to="/docs/guide/concepts/rendering#hybrid-rendering" icon="i-ph-medal-duotone"}
## inlineSSRStyles
Inlines styles when rendering HTML. This is currently available only when using Vite.
You can also pass a function that receives the path of a Vue component and returns a boolean indicating whether to inline the styles for that component.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { inlineSSRStyles: true } }) // or a function to determine inlining
export defineNuxtConfig({
experimental: {
inlineSSRStyles: true // or a function to determine inlining
}
})
```
## noScripts
@ -99,16 +156,25 @@ export defineNuxtConfig({ experimental: { inlineSSRStyles: true } }) // or a fun
Disables rendering of Nuxt scripts and JS resource hints. Can also be configured granularly within `routeRules`.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { noScripts: true } })
export defineNuxtConfig({
experimental: {
noScripts: true
}
})
```
## renderJsonPayloads
Allows rendering of JSON payloads with support for revivifying complex types.
*Enabled by default.*
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { renderJsonPayloads: true } })
export defineNuxtConfig({
experimental: {
renderJsonPayloads: true
}
})
```
## noVueServer
@ -116,7 +182,11 @@ export defineNuxtConfig({ experimental: { renderJsonPayloads: true } })
Disables Vue server renderer endpoint within Nitro.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { noVueServer: true } })
export defineNuxtConfig({
experimental: {
noVueServer: true
}
})
```
## payloadExtraction
@ -124,15 +194,23 @@ export defineNuxtConfig({ experimental: { noVueServer: true } })
Enables extraction of payloads of pages generated with `nuxt generate`.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { payloadExtraction: true } })
export defineNuxtConfig({
experimental: {
payloadExtraction: true
}
})
```
## clientFallback
Enables the experimental `<NuxtClientFallback>` component for rendering content on the client if there's an error in SSR.
Enables the experimental [`<NuxtClientFallback>`](/docs/api/components/nuxt-client-fallback) component for rendering content on the client if there's an error in SSR.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { clientFallback: true } })
export defineNuxtConfig({
experimental: {
clientFallback: true
}
})
```
## crossOriginPrefetch
@ -140,18 +218,33 @@ export defineNuxtConfig({ experimental: { clientFallback: true } })
Enables cross-origin prefetch using the Speculation Rules API.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { crossOriginPrefetch: true } })
export defineNuxtConfig({
experimental: {
crossOriginPrefetch: true
}
})
```
::read-more{icon="i-simple-icons-w3c" color="gray" to="https://wicg.github.io/nav-speculation/prefetch.html" target="_blank"}
Read more about the **Speculation Rules API**.
::
## viewTransition
Enables View Transition API integration with client-side router.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { viewTransition: true } })
export defineNuxtConfig({
experimental: {
viewTransition: true
}
})
```
::ReadMore{link="/docs/getting-started/transitions#view-transitions-api-experimental"}
:link-example{to="https://stackblitz.com/edit/nuxt-view-transitions?file=app.vue" target="_blank"}
::read-more{icon="i-simple-icons-mdnwebdocs" color="gray" to="https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API" target="_blank"}
Read more about the **View Transition API**.
::
## writeEarlyHints
@ -159,29 +252,43 @@ export defineNuxtConfig({ experimental: { viewTransition: true } })
Enables writing of early hints when using node server.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { writeEarlyHints: true } })
export defineNuxtConfig({
experimental: {
writeEarlyHints: true
}
})
```
## componentIslands
Enables experimental component islands support with `<NuxtIsland>` and `.island.vue` files.
Enables experimental component islands support with [`<NuxtIsland>`](/docs/api/components/nuxt-island) and `.island.vue` files.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { componentIslands: true } })
export defineNuxtConfig({
experimental: {
componentIslands: true // false or 'local+remote'
}
})
```
::ReadMore{link="/docs/guide/directory-structure/components#server-components"}
::
:read-more{to="/docs/guide/directory-structure/components#server-components"}
You can follow the server components roadmap on [GitHub](https://github.com/nuxt/nuxt/issues/19772).
::read-more{icon="i-simple-icons-github" color="gray" to="https://github.com/nuxt/nuxt/issues/19772" target="_blank"}
You can follow the server components roadmap on GitHub.
::
## configSchema
Enables config schema support.
*Enabled by default.*
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { configSchema: true } })
export defineNuxtConfig({
experimental: {
configSchema: true
}
})
```
## polyfillVueUseHead
@ -189,7 +296,11 @@ export defineNuxtConfig({ experimental: { configSchema: true } })
Adds a compatibility layer for modules, plugins, or user code relying on the old `@vueuse/head` API.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { polyfillVueUseHead: false } })
export defineNuxtConfig({
experimental: {
polyfillVueUseHead: false
}
})
```
## respectNoSSRHeader
@ -197,36 +308,53 @@ export defineNuxtConfig({ experimental: { polyfillVueUseHead: false } })
Allow disabling Nuxt SSR responses by setting the `x-nuxt-no-ssr` header.
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { respectNoSSRHeader: false } })
export defineNuxtConfig({
experimental: {
respectNoSSRHeader: false
}
})
```
## localLayerAliases
Resolve `~`, `~~`, `@` and `@@` aliases located within layers with respect to their layer source and root directories.
*Enabled by default.*
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { localLayerAliases: true } })
export defineNuxtConfig({
experimental: {
localLayerAliases: true
}
})
```
## typedPages
Enable the new experimental typed router using [unplugin-vue-router](https://github.com/posva/unplugin-vue-router).
Enable the new experimental typed router using [`unplugin-vue-router`](https://github.com/posva/unplugin-vue-router).
```ts [nuxt.config.ts]
export defineNuxtConfig({ experimental: { typedPages: false } })
export defineNuxtConfig({
experimental: {
typedPages: false
}
})
```
Out of the box, this will enable typed usage of `navigateTo`, `<NuxtLink>`, `router.push()` and more.
Out of the box, this will enable typed usage of [`navigateTo`](/docs/api/utils/navigate-to), [`<NuxtLink>`](/docs/api/components/nuxt-link), [`router.push()`](/docs/api/composables/use-router) and more.
You can even get typed params within a page by using `const route = useRoute('route-name')`.
## watcher
Set an alternative watcher that will be used as the watching service for Nuxt.
Nuxt uses `chokidar-granular` by default, which will ignore top-level directories
(like `node_modules` and `.git`) that are excluded from watching.
You can set this instead to `parcel` to use `@parcel/watcher`, which may improve
performance in large projects or on Windows platforms.
You can also set this to `chokidar` to watch all files in your source directory.
```ts [nuxt.config.ts]

View File

@ -3,18 +3,16 @@ title: "How Nuxt Works?"
description: "Nuxt is a minimal but highly customizable framework to build web applications."
---
# How Nuxt Works?
Nuxt is a minimal but highly customizable framework to build web applications. This guide helps you better understand Nuxt internals to develop new solutions and module integrations on top of Nuxt.
This guide helps you better understand Nuxt internals to develop new solutions and module integrations on top of Nuxt.
## The Nuxt Interface
When you start Nuxt in development mode with `nuxi dev` or building a production application with `nuxi build`,
When you start Nuxt in development mode with [`nuxi dev`](/docs/api/commands/dev) or building a production application with [`nuxi build`](/docs/api/commands/build),
a common context will be created, referred to as `nuxt` internally. It holds normalized options merged with `nuxt.config` file,
some internal state, and a powerful [hooking system](/docs/api/advanced/hooks) powered by [unjs/hookable](https://github.com/unjs/hookable)
allowing different components to communicate with each other. You can think of it as **Builder Core**.
This context is globally available to be used with [nuxt/kit](/docs/api/advanced/kit) composables.
This context is globally available to be used with [Nuxt Kit](/docs/guide/going-further/kit) composables.
Therefore only one instance of Nuxt is allowed to run per process.
To extend the Nuxt interface and hook into different stages of the build process, we can use [Nuxt Modules](/docs/guide/going-further/modules).
@ -27,7 +25,7 @@ When rendering a page in the browser or on the server, a shared context will be
This context keeps vue instance, runtime hooks, and internal states like ssrContext and payload for hydration.
You can think of it as **Runtime Core**.
This context can be accessed using `useNuxtApp()` composable within Nuxt plugins and `<script setup>` and vue composables.
This context can be accessed using [`useNuxtApp()`](/docs/api/composables/use-nuxt-app) composable within Nuxt plugins and `<script setup>` and vue composables.
Global usage is possible for the browser but not on the server, to avoid sharing context between users.
To extend the `nuxtApp` interface and hook into different stages or access contexts, we can use [Nuxt Plugins](/docs/guide/directory-structure/plugins).
@ -78,5 +76,4 @@ While both areas can be extended, that runtime context is isolated from build-ti
`nuxt.config` and [Nuxt Modules](/docs/guide/going-further/modules) can be used to extend the build context, and [Nuxt Plugins](/docs/guide/directory-structure/plugins) can be used to extend runtime.
When building an application for production, `nuxi build` will generate a standalone build
in the `.output` directory, independent of `nuxt.config` and [Nuxt modules](/docs/guide/going-further/modules).
When building an application for production, `nuxi build` will generate a standalone build in the `.output` directory, independent of `nuxt.config` and [Nuxt modules](/docs/guide/going-further/modules).

View File

@ -1,17 +1,11 @@
---
title: "Runtime Config"
description: "Nuxt provides a runtime config API to expose configuration within your application."
description: "Nuxt provides a runtime config API to expose configuration and secrets within your application."
---
# Runtime Config
## Exposing
Nuxt provides a runtime config API to expose configuration within your application and server routes, with the ability to update it at runtime by setting environment variables.
## Exposing Runtime Config
To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your `nuxt.config` file, using the [`runtimeConfig` option](/docs/guide/directory-structure/nuxt.config#runtimeconfig).
**Example:**
To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your `nuxt.config` file, using the [`runtimeConfig`](/docs/guide/directory-structure/nuxt.config#runtimeconfig) option.
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@ -28,15 +22,15 @@ export default defineNuxtConfig({
When adding `apiBase` to the `runtimeConfig.public`, Nuxt adds it to each page payload. We can universally access `apiBase` in both server and browser.
```js
```ts
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
```
::alert{type=info}
When using Options API the public runtime config is available via `this.$config.public`.
::callout
Te public runtime config is available in Vue templates with `$config.public`.
::
### Serialization
@ -49,13 +43,14 @@ Instead of passing non-serializable objects or functions into your application f
The most common way to provide configuration is by using [Environment Variables](https://medium.com/chingu/an-introduction-to-environment-variables-and-how-to-use-them-f602f66d15fa).
::alert{type=warning}
::callout
Nuxi CLI has built-in support for reading your `.env` file in development, build and generate. But when you run your built server, **your `.env` file will not be read**.
:ReadMore{link="/docs/guide/directory-structure/env"}
:read-more{to="/docs/guide/directory-structure/env"}
::
Runtime config values are automatically replaced by matching environment variables at runtime. There are two key requirements.
Runtime config values are **automatically replaced by matching environment variables at runtime**.
There are two key requirements:
1. Your desired variables must be defined in your `nuxt.config`. This ensures that arbitrary environment variables are not exposed to your application code.
@ -79,20 +74,24 @@ export default defineNuxtConfig({
})
```
## Accessing Runtime Config
## Reading
### Vue App
Within the Vue part of your Nuxt app, you will need to call `useRuntimeConfig()` to access the runtime config.
Within the Vue part of your Nuxt app, you will need to call [`useRuntimeConfig()`](/docs/api/composables/use-runtime-config) to access the runtime config.
**Note:** Behavior is different between the client-side and server-side:
::callout{color="amber" icon="i-ph-warning-duotone"}
The behavior is different between the client-side and server-side:
- On the client-side, only keys in `public` are available, and the object is both writable and reactive.
The entire runtime config is available on the server-side, but it is read-only to avoid context sharing.
- On client-side, only keys in `runtimeConfig.public` are available, and the object is both writable and reactive.
```vue
- On server-side, the entire runtime config is available on the server-side, but it is read-only to avoid context sharing.
::
```vue [pages/index.vue]
<script setup lang="ts">
const config = useRuntimeConfig()
console.log('Runtime config:', config)
if (process.server) {
console.log('API secret:', config.apiSecret)
@ -106,21 +105,18 @@ if (process.server) {
</template>
```
**🛑 Security note:** Be careful not to expose runtime config keys to the client-side by either rendering them or passing them to `useState`.
::alert{icon=👉}
**`useRuntimeConfig` only works during `setup` or `Lifecycle Hooks`**.
::callout{icon="i-ph-flag-duotone" color="red"}
**Security note:** Be careful not to expose runtime config keys to the client-side by either rendering them or passing them to `useState`.
::
### Plugins
If you want to use the runtime config within any (custom) plugin, you can use `useRuntimeConfig()` inside of your `defineNuxtPlugin` function.
If you want to use the runtime config within any (custom) plugin, you can use [`useRuntimeConfig()`](/docs/api/composables/use-runtime-config) inside of your `defineNuxtPlugin` function.
For Example:
```ts
```ts [plugins/config.ts]
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
console.log('API base URL:', config.public.apiBase)
});
```
@ -129,22 +125,27 @@ export default defineNuxtPlugin((nuxtApp) => {
You can access runtime config within the server routes as well using `useRuntimeConfig`.
```ts
export default async () => {
```ts [server/api/test.ts]
export default defineEventHandler(async (event) => {
const { apiSecret } = useRuntimeConfig(event)
const result = await $fetch('https://my.api.com/test', {
headers: {
Authorization: `Bearer ${useRuntimeConfig().apiSecret}`
Authorization: `Bearer ${apiSecret}`
}
})
return result
}
})
```
### Manually Typing Runtime Config
::callout
Giving the `event` as argument to `useRuntimeConfig` is optional, but it is recommended to pass it to get the runtime config overwritten by [environment variables](/docs/guide/going-further/runtime-config#environment-variables) at runtime for server routes.
::
## Typing Runtime Config
Nuxt tries to automatically generate a typescript interface from provided runtime config using [unjs/untyped](https://github.com/unjs/untyped).
It is also possible to type your runtime config manually:
But it is also possible to type your runtime config manually:
```ts [index.d.ts]
declare module 'nuxt/schema' {

View File

@ -3,8 +3,6 @@ title: "Nightly Release Channel"
description: "The nightly release channel allows using Nuxt built directly from the latest commits to the repository."
---
# Nightly Release Channel
Nuxt lands commits, improvements, and bug fixes every day. You can opt in to test them earlier before the next release.
After a commit is merged into the `main` branch of [nuxt/nuxt](https://github.com/nuxt/nuxt) and **passes all tests**, we trigger an automated npm release, using GitHub Actions.
@ -13,11 +11,11 @@ You can use these 'nightly' releases to beta test new features and changes.
The build and publishing method and quality of these 'nightly' releases are the same as stable ones. The only difference is that you should often check the GitHub repository for updates. There is a slight chance of regressions not being caught during the review process and by the automated tests. Therefore, we internally use this channel to double-check everything before each release.
:::Alert
::callout
Features that are only available on the nightly release channel are marked with an alert in the documentation.
:::
::
## Opting Into the Nightly Release Channel
## Opting In
Update `nuxt` dependency inside `package.json`:
@ -32,7 +30,7 @@ Update `nuxt` dependency inside `package.json`:
Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, or `bun.lockb`) and reinstall dependencies.
## Opting Out From the Nightly Release Channel
## Opting Out
Update `nuxt` dependency inside `package.json`:
@ -47,10 +45,18 @@ Update `nuxt` dependency inside `package.json`:
Remove lockfile (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, or `bun.lockb`) and reinstall dependencies.
## Using Latest `nuxi` CLI From Nightly Release
## Using Nightly `nuxi`
:::Alert
All cli dependencies are bundled because of the building method for reducing `nuxi` package size. You can get dependency updates and CLI improvements using the nightly release channel.
:::
::callout
All cli dependencies are bundled because of the building method for reducing `nuxi` package size. :br You can get dependency updates and CLI improvements using the nightly release channel.
::
You can use `npx nuxi-edge@latest [command]` to try the latest version of the nuxi CLI.
To try the latest version of [nuxt/cli](https://github.com/nuxt/cli):
```bash [Terminal]
npx nuxi-edge@latest [command]
```
::read-more{to="/docs/api/commands"}
Read more about the available commands.
::

View File

@ -3,25 +3,25 @@ title: "Lifecycle Hooks"
description: "Nuxt provides a powerful hooking system to expand almost every aspect using hooks."
---
# Lifecycle Hooks
Nuxt provides a powerful hooking system to expand almost every aspect using hooks. This feature is powered by [unjs/hookable](https://github.com/unjs/hookable).
::callout
The hooking system is powered by [unjs/hookable](https://github.com/unjs/hookable).
::
## Nuxt Hooks (Build Time)
These hooks are available for [Nuxt Modules](/docs/guide/going-further/modules) and build context.
### Usage with `nuxt.config`
### Within `nuxt.config`
```js [nuxt.config]
export default defineNuxtConfig({
hooks: {
'close': () => { }
close: () => { }
}
})
```
### Usage with Nuxt Modules
### Within Nuxt Modules
```js
import { defineNuxtModule } from '@nuxt/kit'
@ -33,12 +33,14 @@ export default defineNuxtModule({
})
```
::read-more{to="/docs/api/advanced/hooks#nuxt-hooks-build-time"}
Explore all available Nuxt hooks.
::
## App Hooks (Runtime)
App hooks can be mainly used by [Nuxt Plugins](/docs/guide/directory-structure/plugins) to hook into rendering lifecycle but could also be used in Vue composables.
### Usage with Plugins
```js [plugins/test.ts]
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:start', () => {
@ -47,15 +49,13 @@ export default defineNuxtPlugin((nuxtApp) => {
})
```
::alert{icon=👉}
Learn more about [available lifecycle hooks](/docs/api/advanced/hooks)
::read-more{to="/docs/api/advanced/hooks#app-hooks-runtime"}
Explore all available App hooks.
::
## Nitro App Hooks (Runtime)
## Server Hooks (Runtime)
These hooks are available for [Nitro plugins](https://nitro.unjs.io/guide/plugins) to hook into Nitro's runtime behavior.
### Usage within a Nitro Plugin
These hooks are available for [server plugins](/docs/guide/directory-structure/server#server-plugins) to hook into Nitro's runtime behavior.
```js [~/server/plugins/test.ts]
export default defineNitroPlugin((nitroApp) => {
@ -70,11 +70,11 @@ export default defineNitroPlugin((nitroApp) => {
})
```
::alert{icon=👉}
Learn more about available [Nitro lifecycle hooks](/docs/api/advanced/hooks#nitro-app-hooks-runtime-server-side).
::read-more{to="/docs/api/advanced/hooks#nitro-app-hooks-runtime-server-side"}
Learn more about available Nitro lifecycle hooks.
::
## Add additional hooks
## Additional Hooks
You can add additional hooks by augmenting the types provided by Nuxt. This can be useful for modules.

View File

@ -4,11 +4,7 @@ description: "Learn how to create a Nuxt Module to integrate, enhance or extend
image: '/socials/module-author-guide.jpg'
---
# Module Author Guide
Learn how to create a Nuxt Module to integrate, enhance or extend any Nuxt applications.
Nuxt's [configuration](/docs/api/configuration/nuxt-config) and [hooks](/docs/guide/going-further/hooks) systems make it possible to customize every aspect of Nuxt and add any integration you might need (Vue plugins, CMS, server routes, components, logging, etc.).
Nuxt's [configuration](/docs/api/nuxt-config) and [hooks](/docs/guide/going-further/hooks) systems make it possible to customize every aspect of Nuxt and add any integration you might need (Vue plugins, CMS, server routes, components, logging, etc.).
**Nuxt Modules** are functions that sequentially run when starting Nuxt in development mode using `nuxi dev` or building a project for production with `nuxi build`.
With modules, you can encapsulate, properly test, and share custom solutions as npm packages without adding unnecessary boilerplate to your project, or requiring changes to Nuxt itself.
@ -17,7 +13,7 @@ With modules, you can encapsulate, properly test, and share custom solutions as
We recommend you get started with Nuxt Modules using our [starter template](https://github.com/nuxt/starter/tree/module):
```bash
```bash [Terminal]
npx nuxi init -t module my-module
```
@ -43,7 +39,7 @@ You can interact with the playground like with any Nuxt application.
- Launch its development server with `npm run dev`, it should reload itself as you make changes to your module in the `src` directory
- Build it with `npm run dev:build`
::alert{type=info}
::callout{color="blue" icon="i-ph-info-duotone"}
All other `nuxi` commands can be used against the `playground` directory (e.g. `nuxi <COMMAND> playground`). Feel free to declare additional `dev:*` scripts within your `package.json` referencing them for convenience.
::
@ -54,7 +50,7 @@ The module starter comes with a basic test suite:
- A linter powered by [ESLint](https://eslint.org), run it with `npm run lint`
- A test runner powered by [Vitest](https://vitest.dev), run it with `npm run test` or `npm run test:watch`
::alert{type=info}
::callout
Feel free to augment this default test strategy to better suit your needs.
::
@ -64,13 +60,13 @@ Nuxt Modules come with their own builder provided by [`@nuxt/module-builder`](ht
You can build your module by running `npm run prepack`.
::alert{type=info}
::callout
While building your module can be useful in some cases, most of the time you won't need to build it on your own: the `playground` takes care of it while developing, and the release script also has you covered when publishing.
::
#### How to Publish
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
Before publishing your module to npm, makes sure you have an [npmjs.com](https://www.npmjs.com) account and that you're authenticated to it locally with `npm login`.
::
@ -89,7 +85,7 @@ When running the release script, the following will happen:
- Publishing the module to npm (for that purpose, the module will be built again to ensure its updated version number is taken into account in the published artifact)
- Pushing a git tag representing the newly published version to your git remote origin
::alert{type=info}
::callout
As with other scripts, feel free to fine-tune the default `release` script in your `package.json` to better suit your need.
::
@ -102,13 +98,13 @@ Nuxt Modules come with a variety of powerful APIs and patterns allowing them to
We can consider two kinds of Nuxt Modules:
- published modules are distributed on npm - you can see a list of some community modules on [the Nuxt website](/modules).
- "local" modules, they exist within a Nuxt project itself, either [inlined in Nuxt config](/docs/api/configuration/nuxt-config#modules) or as part of [the `modules` directory](/docs/guide/directory-structure/modules).
- "local" modules, they exist within a Nuxt project itself, either [inlined in Nuxt config](/docs/api/nuxt-config#modules) or as part of [the `modules` directory](/docs/guide/directory-structure/modules).
In either case, their anatomy is similar.
#### Module Definition
::alert{type=info}
::callout
When using the starter, your module definition is available at `src/module.ts`.
::
@ -116,7 +112,7 @@ The module definition is the entry point of your module. It's what gets loaded b
At a low level, a Nuxt Module definition is a simple, potentially asynchronous, function accepting inline user options and a `nuxt` object to interact with Nuxt.
```js
```ts
export default function (inlineOptions, nuxt) {
// You can do whatever you like here..
console.log(inlineOptions.token) // `123`
@ -127,9 +123,9 @@ export default function (inlineOptions, nuxt) {
}
```
You can get type-hint support for this function using the higher-level `defineNuxtModule` helper provided by [Nuxt Kit](/docs/api/advanced/kit).
You can get type-hint support for this function using the higher-level `defineNuxtModule` helper provided by [Nuxt Kit](/docs/guide/going-further/kit).
```js
```ts
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule((options, nuxt) => {
@ -143,7 +139,7 @@ However, **we do not recommend** using this low-level function definition. Inste
This helper makes writing Nuxt Module more straightforward by implementing many common patterns seen in modules, guaranteeing future compatibility, and improving your module author developer experience and the one of your module users.
```js
```ts
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
@ -171,7 +167,6 @@ export default defineNuxtModule({
Ultimately `defineNuxtModule` returns a wrapper function with the lower level `(inlineOptions, nuxt)` module signature. This wrapper function applies defaults and other necessary steps before calling your `setup` function:
::list
- Support `defaults` and `meta.configKey` for automatically merging module options
- Type hints and automated type inference
- Add shims for basic Nuxt 2 compatibility
@ -181,11 +176,10 @@ Ultimately `defineNuxtModule` returns a wrapper function with the lower level `(
- Expose `getOptions` and `getMeta` for internal usage of Nuxt
- Ensuring backward and upward compatibility as long as the module is using `defineNuxtModule` from the latest version of `@nuxt/kit`
- Integration with module builder tooling
::
#### Runtime Directory
::alert{type=info}
::callout
When using the starter, the runtime directory is available at `src/runtime`.
::
@ -209,11 +203,11 @@ Or any other kind of asset you want to inject in users' Nuxt applications:
You'll then be able to inject all those assets inside the application from your [module definition](#module-definition).
::alert{type=info}
::callout
Learn more about asset injection in [the recipes section](#recipes).
::
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
Published modules cannot leverage auto-imports for assets within their runtime directory. Instead, they have to import them explicitly from `#imports` or alike.
Indeed, auto-imports are not enabled for files within `node_modules` (the location where a published module will eventually live) for performance reasons. That's why the module starter [deliberately disables them](https://github.com/nuxt/starter/blob/module/.nuxtrc#L1) while developing a module.
@ -233,7 +227,7 @@ Modules come with a set of first-party tools to help you with their development.
[Nuxt Kit](/docs/guide/going-further/kit) provides composable utilities to help your module interact with Nuxt applications. It's recommended to use Nuxt Kit utilities over manual alternatives whenever possible to ensure better compatibility and code readability of your module.
:ReadMore{link="/docs/api/advanced/kit" title="API > Advanced > Kit"}
:read-more{to="/docs/guide/going-further/kit"}
#### `@nuxt/test-utils`
@ -263,7 +257,7 @@ When you need to handle more complex configuration alterations, you should consi
#### Exposing Options to Runtime
Because modules aren't part of the application runtime, their options aren't either. However, in many cases, you might need access to some of these module options within your runtime code. We recommend exposing the needed config using Nuxt's [`runtimeConfig`](/docs/api/configuration/nuxt-config#runtimeconfig).
Because modules aren't part of the application runtime, their options aren't either. However, in many cases, you might need access to some of these module options within your runtime code. We recommend exposing the needed config using Nuxt's [`runtimeConfig`](/docs/api/nuxt-config#runtimeconfig).
<!-- TODO: Update after #18466 (or equivalent) -->
@ -288,11 +282,11 @@ You can then access your module options in a plugin, component, the application
const options = useRuntimeConfig().public.myModule
```
::alert{type=warning}
::callout{color="amber" icon="i-ph-warning-duotone"}
Be careful not to expose any sensitive module configuration on the public runtime config, such as private API keys, as they will end up in the public bundle.
::
:ReadMore{link="/docs/guide/going-further/runtime-config" title="Guide > Going Further > Runtime Config"}
:read-more{to="/docs/guide/going-further/runtime-config"}
#### Injecting Plugins With `addPlugin`
@ -311,7 +305,7 @@ export default defineNuxtModule({
})
```
:ReadMore{link="/docs/api/advanced/kit" title="API > Advanced > Kit"}
:read-more{to="/docs/guide/going-further/kit"}
#### Injecting Vue Components With `addComponent`
@ -499,9 +493,9 @@ export default defineNuxtModule({
})
```
:ReadMore{link="/docs/api/advanced/hooks" title="API > Advanced > Hooks"}
:read-more{to="/docs/api/advanced/hooks"}
::alert{type=info}
::callout
**Module cleanup**
If your module opens, handles, or starts a watcher, you should close it when the Nuxt lifecycle is done. The `close` hook is available for this.
@ -595,7 +589,7 @@ Testing helps ensuring your module works as expected given various setup. Find i
#### Unit and Integration
::alert{type=info}
::callout
We're still discussing and exploring how to ease unit and integration testing on Nuxt Modules.
[Check out this RFC to join the conversation](https://github.com/nuxt/nuxt/discussions/18399).
@ -651,7 +645,7 @@ describe('ssr', async () => {
describe('csr', async () => { /* ... */ })
```
::alert{type=info}
::callout
An example of such a workflow is available on [the module starter](https://github.com/nuxt/starter/blob/module/test/basic.test.ts).
::
@ -673,7 +667,7 @@ As we've seen, Nuxt Modules can be asynchronous. For example, you may want to de
However, be careful with asynchronous behaviors as Nuxt will wait for your module to setup before going to the next module and starting the development server, build process, etc. Prefer deferring time-consuming logic to Nuxt hooks.
::alert{type="warning"}
::callout{color="amber" icon="i-ph-warning-duotone"}
If your module takes more than **1 second** to setup, Nuxt will emit a warning about it.
::

View File

@ -3,9 +3,11 @@ title: "Nuxt Kit"
description: "@nuxt/kit provides features for module authors."
---
# Nuxt Kit
Nuxt Kit provides composable utilities to make interacting with [Nuxt Hooks](/docs/api/advanced/hooks), the [Nuxt Interface](/docs/guide/going-further/internals#the-nuxt-interface) and developing [Nuxt Modules](/docs/guide/going-further/modules) super easy.
> Nuxt Kit provides composable utilities to make interacting with [Nuxt Hooks](/docs/api/advanced/hooks) and [Nuxt Builder Core](/docs/guide/going-further/internals#the-nuxt-interface) and developing [Nuxt Modules](/docs/guide/going-further/modules) super easy!
::read-more{to="/docs/api/kit"}
Discover all Nuxt Kit utilities.
::
## Usage
@ -27,10 +29,9 @@ You can install the latest Nuxt Kit by adding it to the `dependencies` section o
import { useNuxt } from '@nuxt/kit'
```
::ReadMore{link="/docs/api/advanced/kit" title="API > Advanced > Kit"}
::
:read-more{to="/docs/api/kit"}
::alert{type="warning"}
::callout
Nuxt Kit utilities are only available for modules and not meant to be imported in runtime (components, Vue composables, pages, plugins, or server routes).
::

View File

@ -1,42 +1,54 @@
---
title: "NuxtApp"
description: "In Nuxt 3, you can access runtime app context within composables, components and plugins."
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/nuxt.ts
---
# NuxtApp
In Nuxt 3, you can access runtime app context within composables, components and plugins.
In Nuxt 3, you can access runtime app context within composables, components and plugins. In Nuxt 2, this was referred to as [Nuxt context](https://nuxtjs.org/docs/internals-glossary/context#the-context).
::read-more{to="https://v2.nuxt.com/docs/internals-glossary/context#the-context" target="_blank"}
In Nuxt 2, this was referred to as **Nuxt context**.
::
## Nuxt App Interface
::read-more{to="/docs/guide/going-further/internals#the-nuxtapp-interface"}
Jump over the `NuxtApp` interface documentation.
::
## Accessing NuxtApp
Within composables, plugins and components you can access `nuxtApp` with `useNuxtApp`:
Within composables, plugins and components you can access `nuxtApp` with [`useNuxtApp()`](/docs/api/composables/use-nuxt-app):
```js
function useMyComposable () {
```ts [composables/useMyComposable.ts]
export function useMyComposable () {
const nuxtApp = useNuxtApp()
// access runtime nuxt app instance
}
```
Plugins also receive `nuxtApp` as the first argument for convenience. [Read more about plugins.](/docs/guide/directory-structure/plugins)
Plugins also receive `nuxtApp` as the first argument for convenience.
::alert{icon=👉}
**`useNuxtApp` (on the server) only works during `setup`, inside Nuxt plugins or `Lifecycle Hooks`**.
::
:read-more{to="/docs/guide/directory-structure/plugins"}
## Providing Helpers
You can provide helpers to be usable across all composables and application. This usually happens within a Nuxt plugin.
```js
```ts
const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', (name) => `Hello ${name}!`)
console.log(nuxtApp.$hello('name')) // Prints "Hello name!"
```
In Nuxt 2 plugins, this was referred to as [inject function](https://nuxtjs.org/docs/directory-structure/plugins#inject-in-root--context).
::alert{icon=👉}
It is possible to inject helpers by returning an object with a `provide` key. See the [plugins documentation](/docs/guide/directory-structure/plugins) for more information.
::read-more{to="/docs/guide/directory-structure/plugins#providing-helpers"}
It is possible to inject helpers by returning an object with a `provide` key in plugins.
::
::read-more{to="https://v2.nuxt.com/docs/directory-structure/plugins#inject-in-root--context" target="_blank"}
In Nuxt 2 plugins, this was referred to as **inject function**.
::

View File

@ -1,31 +1,33 @@
---
title: Authoring Nuxt Layers
description: Nuxt provides a powerful system that allows you to extend the default files, configs, and much more.
---
# Authoring Nuxt Layers
Nuxt layers are a powerful feature that you can use to share and reuse partial Nuxt applications within a monorepo, or from a git repository or npm package. The layers structure is almost identical to a standard Nuxt application, which makes them easy to author and maintain.
Nuxt layers are a powerful feature that you can use to share and reuse partial Nuxt applications within a monorepo, or from a git repository or npm package. The layers structure is almost identical to a standard Nuxt application, which makes them easy to author and maintain. ([Read More](/docs/getting-started/layers))
:read-more{to="/docs/getting-started/layers"}
A minimal Nuxt layer directory should contain a [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file to indicate it is a layer.
```ts{}[base/nuxt.config.ts]
```ts [base/nuxt.config.ts]
export default defineNuxtConfig({})
```
Additionally, certain other files in the layer directory will be auto-scanned and used by Nuxt for the project extending this layer.
- `components/*` - Extend the default components
- `composables/*` - Extend the default composables
- `pages/*` - Extend the default pages
- `server/*` - Extend the default server endpoints & middleware
- [`components/*`](/docs/guide/directory-structure/components) - Extend the default components
- [`composables/*`](/docs/guide/directory-structure/composables) - Extend the default composables
- [`pages/*`](/docs/guide/directory-structure/pages) - Extend the default pages
- [`server/*`](/docs/guide/directory-structure/server) - Extend the default server endpoints & middleware
- [`utils/*`](/docs/guide/directory-structure/utils) - Extend the default utils
- [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config)- Extend the default nuxt config
- `app.config.ts` - Extend the default app config
- [`app.config.ts`](/docs/guide/directory-structure/app-config) - Extend the default app config
## Basic Example
::code-group
```ts{}[nuxt.config.ts]
```ts [nuxt.config.ts]
export default defineNuxtConfig({
extends: [
'./base'
@ -33,13 +35,13 @@ Additionally, certain other files in the layer directory will be auto-scanned an
})
```
```vue{}[app.vue]
```vue [app.vue]
<template>
<BaseComponent/>
</template>
```
```ts{}[base/nuxt.config.ts]
```ts [base/nuxt.config.ts]
export default defineNuxtConfig({
// Extending from base nuxt.config.ts!
app: {
@ -53,7 +55,7 @@ Additionally, certain other files in the layer directory will be auto-scanned an
})
```
```vue{}[base/components/BaseComponent.vue]
```vue [base/components/BaseComponent.vue]
<template>
<h1>Extending Components is Fun!</h1>
</template>
@ -61,24 +63,24 @@ Additionally, certain other files in the layer directory will be auto-scanned an
::
::alert{type="info"}
If you're interested in deepening your understanding about layers, consider examining [a fully fleshed out [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file on the Docus platform](https://github.com/nuxt-themes/docus/blob/main/nuxt.config.ts).
::callout
If you're interested in deepening your understanding about layers, consider examining [a fully fleshed out [`nuxt.config.ts`](/docs/guide/directory-structure/nuxt.config) file on the [Docus theme](https://github.com/nuxt-themes/docus/blob/main/nuxt.config.ts).
::
## Starter Template
To get started you can initialize a layer with the [nuxt/starter/layer template](https://github.com/nuxt/starter/tree/layer). This will create a basic structure you can build upon. Execute this command within the terminal to get started:
```bash
```bash [Terminal]
npx nuxi init --template layer nuxt-layer
```
Follow up on the README instructions for the next steps.
::alert
::callout
Check [nuxt-themes/starter](https://github.com/nuxt-themes/starter) for a more opinionated starter for authoring Nuxt themes. It can be initialized with:
```bash
```bash [Terminal]
npx nuxi init --template gh:nuxt-themes/starter my-theme
```
@ -105,11 +107,11 @@ export default defineNuxtConfig({
})
```
::alert{type="info"}
::callout
If you want to extend a private remote source, you need to add the environment variable `GIGET_AUTH=<token>` to provide a token.
::
::alert{type="warning"}
::callout{color="amber" icon="i-ph-warning-duotone"}
Currently, with git remote sources, if a layer has npm dependencies, you will need to manually install them in the target project. We are working on this to auto-install layer dependencies with git sources.
::
@ -145,13 +147,13 @@ To publish a layer directory as an npm package, you want to make sure that the `
}
```
::alert{type="info"}
::callout
Make sure any dependency imported in the layer is **explicitly added** to the `dependencies`. The `nuxt` dependency, and anything only used for testing the layer before publishing, should remain in the `devDependencies` field.
::
Now you can proceed to publish the module to npm, either publicly or privately.
::alert{type="warning"}
::callout{color="amber" icon="i-ph-warning-duotone"}
When publishing the layer as a private npm package, you need to make sure you log in, to authenticate with npm to download the node module.
::
@ -180,9 +182,7 @@ export default defineNuxtConfig({
You can use the internal array `nuxt.options._layers` to support custom multi-layer handling for your modules.
Example:
```js [modules/my-module.ts]
```ts [modules/my-module.ts]
export default defineNuxtModule({
setup(_options, nuxt) {
for (const layer of nuxt.options._layers) {
@ -201,4 +201,6 @@ export default defineNuxtModule({
Configuration loading and extends support is handled by [unjs/c12](https://github.com/unjs/c12), merged using [unjs/defu](https://github.com/unjs/defu) and remote git sources are supported using [unjs/giget](https://github.com/unjs/giget). Check the docs and source code to learn more.
We are working to bring more improvements for layers support. Please refer to [nuxt/nuxt#13367](https://github.com/nuxt/nuxt/issues/13367).
::read-more{icon="i-simple-icons-github" color="gray" to="https://github.com/nuxt/nuxt/issues/13367" target="_blank"}
Checkout our ongoing development to bring more improvements for layers support on GitHub.
::

View File

@ -1,5 +1,5 @@
---
title: "Custom routing"
title: "Custom Routing"
description: "In Nuxt 3, your routing is defined by the structure of your files inside the pages directory. However, since it uses vue-router under the hood, Nuxt offers you several ways to add custom routes in your project."
---
@ -7,13 +7,13 @@ description: "In Nuxt 3, your routing is defined by the structure of your files
In Nuxt 3, your routing is defined by the structure of your files inside the [pages directory](/docs/guide/directory-structure/pages). However, since it uses [vue-router](https://router.vuejs.org/) under the hood, Nuxt offers you several ways to add custom routes in your project.
### Using router config
### Router Config
Using [router options](/docs/guide/going-further/custom-routing#router-options), you can optionally override or extend your routes using a function that accepts the scanned routes and returns customized routes.
If it returns `null` or `undefined`, Nuxt will fall back to the default routes (useful to modify input array).
```js [app/router.options.ts]
```ts [app/router.options.ts]
import type { RouterConfig } from '@nuxt/schema'
// https://router.vuejs.org/api/interfaces/routeroptions.html
@ -28,13 +28,15 @@ export default <RouterConfig> {
}
```
::alert
::callout
Nuxt will not augment any new routes you return from the `routes` function with metadata defined in `definePageMeta` of the component you provide. If you want that to happen, you should use the `pages:extend` hook which is [called at build-time](/docs/api/advanced/hooks#nuxt-hooks-build-time).
::
### Using the `pages:extend` hook
### Pages Hook
You can add, change or remove pages from the scanned routes with the `pages:extend` nuxt hook. For example, to prevent creating routes for any `.ts` files:
You can add, change or remove pages from the scanned routes with the `pages:extend` nuxt hook.
For example, to prevent creating routes for any `.ts` files:
```ts [nuxt.config.ts]
export default defineNuxtConfig({
@ -67,13 +69,13 @@ export default defineNuxtConfig({
})
```
### Using a module
### Nuxt Module
If you plan to add a whole set of pages related with a specific functionality, you might want to use a [Nuxt module](/modules).
The [Nuxt kit](/docs/guide/going-further/kit) provides a few ways [to add routes](/docs/api/advanced/kit#pages):
- extendPages (callback: pages => void)
- extendRouteRules (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)
The [Nuxt kit](/docs/guide/going-further/kit) provides a few ways [to add routes](/docs/api/kit/pages):
- [`extendPages`](/docs/api/kit/pages#extendpages) (callback: pages => void)
- [`extendRouteRules`](/docs/api/kit/pages#extendrouterules) (route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)
## Router Options

View File

@ -64,7 +64,7 @@ You may need to update the config below with a path to your web browser. For mor
If you prefer your usual browser extensions, add this to the _chrome_ configuration above:
```json5
"userDataDir": false,
"userDataDir": false,
```
### Example JetBrains IDEs Debug Configuration

View File

@ -1,4 +1,3 @@
title: Going further
title: Going Further
titleTemplate: '%s · Nuxt Advanced'
navigation.icon: uil:star
image: '/socials/going-further.jpg'
icon: i-ph-star-duotone

View File

@ -1 +1,2 @@
image: '/socials/guide.jpg'
title: 'Guide'
icon: i-ph-book-open-duotone

View File

@ -1,4 +0,0 @@
---
navigation: false
redirect: /guide/concepts/auto-imports
---

View File

@ -1,14 +1,19 @@
---
description: The <ClientOnly> component renders its slot only in client-side.
title: '<ClientOnly>'
description: Render components only in client-side with the <ClientOnly> component.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/client-only.ts
size: xs
---
# `<ClientOnly>`
The `<ClientOnly>` component renders its slot only in client-side. To import a component only on the client, register the component in a client-side only plugin.
## Props
- **placeholderTag** | **fallbackTag**: specify a tag to be rendered server-side.
- **placeholder** | **fallback**: specify a content to be rendered server-side.
- `placeholderTag` | `fallbackTag`: specify a tag to be rendered server-side.
- `placeholder` | `fallback`: specify a content to be rendered server-side.
```vue
<template>
@ -23,7 +28,7 @@ The `<ClientOnly>` component renders its slot only in client-side. To import a c
## Slots
- **#fallback**: specify a content to be displayed server-side.
- `#fallback`: specify a content to be displayed server-side.
```vue
<template>

View File

@ -1,19 +1,24 @@
---
title: "<NuxtClientFallback>"
description: "Nuxt provides `<NuxtClientFallback>` component to render its content on the client if any of its children trigger an error in SSR"
links:
- label: Source (client)
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/client-fallback.client.ts
size: xs
- label: Source (server)
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/client-fallback.server.ts
size: xs
---
# `<NuxtClientFallback>`
Nuxt provides a `<NuxtClientFallback>` component to render its content on the client if any of its children trigger an error in SSR.
::alert{type=warning}
::callout{to="/docs/guide/going-further/experimental-features#clientfallback"}
This component is experimental and in order to use it you must enable the `experimental.clientFallback` option in your `nuxt.config`.
::
## Events
- **`@ssr-error`**: Event emitted when a child triggers an error in SSR. Note that this will only be triggered on the server.
- `@ssr-error`: Event emitted when a child triggers an error in SSR. Note that this will only be triggered on the server.
```vue
<template>
@ -25,12 +30,12 @@ This component is experimental and in order to use it you must enable the `exper
## Props
- **placeholderTag** | **fallbackTag**: Specify a fallback tag to be rendered if the slot fails to render.
- `placeholderTag` | `fallbackTag`: Specify a fallback tag to be rendered if the slot fails to render.
- **type**: `string`
- **default**: `div`
- **placeholder** | **fallback**: Specify fallback content to be rendered if the slot fails to render.
- `placeholder` | `fallback`: Specify fallback content to be rendered if the slot fails to render.
- **type**: `string`
- **keepFallback**: Keep the fallback content if it failed to render server-side.
- `keepFallback`: Keep the fallback content if it failed to render server-side.
- **type**: `boolean`
- **default**: `false`
@ -45,7 +50,7 @@ This component is experimental and in order to use it you must enable the `exper
## Slots
- **#fallback**: specify content to be displayed server-side if the slot fails to render.
- `#fallback`: specify content to be displayed server-side if the slot fails to render.
```vue
<template>

View File

@ -1,11 +1,16 @@
---
title: "<NuxtPicture>"
description: "Nuxt provides a <NuxtPicture> component to handle automatic image optimization."
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/image/blob/main/src/runtime/components/nuxt-picture.ts
size: xs
---
`<NuxtPicture>` is a drop-in replacement for the native `<picture>` tag.
Usage of `<NuxtPicture>` is almost identical to [`<NuxtImg>`](./nuxt-img) but it also allows serving modern formats like `webp` when possible.
Usage of `<NuxtPicture>` is almost identical to [`<NuxtImg>`](/docs/api/components/nuxt-img) but it also allows serving modern formats like `webp` when possible.
Learn more about the [`<picture>` tag on MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture).
@ -17,6 +22,6 @@ In order to use `<NuxtPicture>` you should install and enable the Nuxt Image mod
npx nuxi@latest module add image
```
::read-more{to="https://image.nuxt.com/usage/nuxt-picture"}
::read-more{to="https://image.nuxt.com/usage/nuxt-picture" target="_blank"}
Read more about the `<NuxtPicture>` component.
::

View File

@ -1,13 +1,13 @@
---
title: '<Teleport>'
description: The <Teleport> component teleports a component to a different location in the DOM.
---
# `<Teleport>`
The `<Teleport>` component teleports a component to a different location in the DOM.
::callout{color="amber" icon="i-ph-warning-duotone"}
The `to` target of [`<Teleport>`](https://vuejs.org/guide/built-ins/teleport.html) expects a CSS selector string or an actual DOM node. Nuxt currently has SSR support for teleports to `body` only, with client-side support for other targets using a `<ClientOnly>` wrapper.
::
## Example: `body` Teleport
## Body Teleport
```vue
<template>
@ -25,7 +25,7 @@ The `to` target of [`<Teleport>`](https://vuejs.org/guide/built-ins/teleport.htm
</template>
```
## Example: Client-side Teleport
## Client-side Teleport
```vue
<template>
@ -37,5 +37,4 @@ The `to` target of [`<Teleport>`](https://vuejs.org/guide/built-ins/teleport.htm
</template>
```
::LinkExample{link="/docs/examples/advanced/teleport"}
::
:link-example{to="/docs/examples/advanced/teleport"}

View File

@ -0,0 +1,93 @@
---
title: "<NuxtPage>"
description: The <NuxtPage> component is required to display pages located in the pages/ directory.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/pages/runtime/page.ts
size: xs
---
`<NuxtPage>` is a built-in component that comes with Nuxt. It lets you display top-level or nested pages located in the [`pages/`](/docs/guide/directory-structure/pages) directory.
::callout
`<NuxtPage>` is a wrapper around [`<RouterView>`](https://router.vuejs.org/api/interfaces/RouterViewProps.html#interface-routerviewprops) component from Vue Router. :br
It accepts same `name` and `route` props.
::
## Props
- `name`: tells `RouterView` to render the component with the corresponding name in the matched route record's components option.
- type: `string`
- `route`: route location that has all of its components resolved.
- type: `RouteLocationNormalized`
- `pageKey:` control when the `NuxtPage` component is re-rendered.
- type: `string` or `function`
::callout
Nuxt automatically resolves the `name` and `route` by scanning and rendering all Vue component files found in the `/pages` directory.
::
## Example
For example, passing `static` key, `NuxtPage` component is rendered only once when it is mounted.
```vue [app.vue]
<template>
<NuxtPage page-key="static" />
</template>
```
You can also use a dynamic key based on the current route:
```html
<NuxtPage :page-key="route => route.fullPath" />
```
::callout{color="amber" icon="i-ph-warning-duotone"}
Don't use `$route` object here as it can cause problems with how `<NuxtPage>` renders pages with `<Suspense>`.
::
Alternatively, `pageKey` can be passed as a `key` value via [`definePageMeta`](/docs/api/utils/define-page-meta) from the `<script>` section of your Vue component in the `/pages` directory.
```vue [pages/my-page.vue]
<script setup lang="ts">
definePageMeta({
key: route => route.fullPath
})
</script>
```
:link-example{to="/docs/examples/routing/pages"}
## Page's Ref
To get the `ref` of a page component, access it through `ref.value.pageRef`
````vue [app.vue]
<script setup lang="ts">
const page = ref()
function logFoo () {
page.value.pageRef.foo()
}
</script>
<template>
<NuxtPage ref="page" />
</template>
````
## Custom Props
In addition, `<NuxtPage>` also accepts custom props that you may need to pass further down the hierarchy.
These custom props are accessible via `attrs` in the Nuxt app.
```html
<NuxtPage :foobar="123" />
```
For example, in the above example, the value of `foobar` will be available using `$attrs.foobar` in the template or `useAttrs().foobar` in `<script setup>`.
:read-more{to="/docs/guide/directory-structure/pages"}

View File

@ -1,12 +1,16 @@
---
title: "<NuxtLayout>"
description: "Nuxt provides the <NuxtLayout> component to show layouts on pages and error pages."
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-layout.ts
size: xs
---
# `<NuxtLayout>`
You can use `<NuxtLayout />` component to activate the `default` layout on `app.vue` or `error.vue`.
You can use `<NuxtLayout />` component to activate `default` layout on `app.vue` or `error.vue`.
```vue [/app.vue]
```vue [app.vue]
<template>
<NuxtLayout>
some page content
@ -14,13 +18,13 @@ You can use `<NuxtLayout />` component to activate `default` layout on `app.vue`
</template>
```
`<NuxtLayout />` can be used to override `default` layout on `app.vue`, `error.vue` or even page components found in the `/pages` directory.
:read-more{to="/docs/guide/directory-structure/layouts"}
## `name` prop
## Props
`<NuxtLayout />` component accepts the `name` prop, which you can pass to use a non-default layout, where `name` can be a static string, reactive reference or a computed property. It **must** match the name of the corresponding layout file in the `/layouts` directory.
### Examples
- `name`: Specify a layout name to be rendered, can be a string, reactive reference or a computed property. It **must** match the name of the corresponding layout file in the [`layouts/`](/docs/guide/directory-structure/layouts) directory.
- **type**: `string`
- **default**: `default`
```vue [pages/index.vue]
<script setup lang="ts">
@ -35,11 +39,11 @@ const layout = 'custom'
</template>
```
::alert{icon=👉}
::callout
Please note the layout name is normalized to kebab-case, so if your layout file is named `errorLayout.vue`, it will become `error-layout` when passed as a `name` property to `<NuxtLayout />`.
::
```vue [/error.vue]
```vue [error.vue]
<template>
<NuxtLayout name="error-layout">
<NuxtPage />
@ -47,27 +51,35 @@ Please note the layout name is normalized to kebab-case, so if your layout file
</template>
```
## Passing Additional Props
::read-more{to="/docs/guide/directory-structure/layouts"}
Read more about dynamic layouts.
::
## Additional Props
`NuxtLayout` also accepts any additional props that you may need to pass to the layout. These custom props are then made accessible as attributes.
```vue[pages/some-page.vue]
<div>
```vue [pages/some-page.vue]
<template>
<div>
<NuxtLayout name="custom" title="I am a custom layout">
<-- ... -->
</NuxtLayout>
</div>
</div>
</template>
```
In the above example, the value of `title` will be available using `$attrs.title` in the template or `useAttrs().title` in `<script setup>` at custom.vue.
```vue[layouts/custom.vue]
```vue [layouts/custom.vue]
<script setup lang="ts">
const layoutCustomProps = useAttrs()
console.log(layoutCustomProps.title) // I am a custom layout
const layoutCustomProps = useAttrs()
console.log(layoutCustomProps.title) // I am a custom layout
</script>
```
## Layout and Transition
## Transitions
`<NuxtLayout />` renders incoming content via `<slot />`, which is then wrapped around Vues `<Transition />` component to activate layout transition. For this to work as expected, it is recommended that `<NuxtLayout />` is **not** the root element of the page component.
@ -81,13 +93,16 @@ In the above example, the value of `title` will be available using `$attrs.title
</template>
```
## Accessing a layout's component ref
:read-more{to="/docs/getting-started/transitions"}
## Layout's Ref
To get the ref of a layout component, access it through `ref.value.layoutRef`
````html
````vue [app.vue]
<script setup lang="ts">
const layout = ref()
function logFoo () {
layout.value.layoutRef.foo()
}
@ -98,5 +113,4 @@ function logFoo () {
</template>
````
::ReadMore{link="/docs/guide/directory-structure/layouts"}
::
:read-more{to="/docs/guide/directory-structure/layouts"}

View File

@ -0,0 +1,122 @@
---
title: "<NuxtLink>"
description: "Nuxt provides <NuxtLink> component to handle any kind of links within your application."
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-link.ts
size: xs
---
::callout
`<NuxtLink>` is a drop-in replacement for both Vue Router's `<RouterLink>` component and HTML's `<a>` tag. It intelligently determines whether the link is _internal_ or _external_ and renders it accordingly with available optimizations (prefetching, default attributes, etc.)
::
## Internal Routing
In this example, we use `<NuxtLink>` component to link to another page of the application.
```vue [pages/index.vue]
<template>
<NuxtLink to="/about">
About page
</NuxtLink>
<!-- <a href="/about">...</a> (+Vue Router & prefetching) -->
</template>
```
## External Routing
In this example, we use `<NuxtLink>` component to link to a website.
```vue [app.vue]
<template>
<NuxtLink to="https://nuxtjs.org">
Nuxt website
</NuxtLink>
<!-- <a href="https://nuxtjs.org" rel="noopener noreferrer">...</a> -->
</template>
```
## `target` and `rel` Attributes
In this example, we use `<NuxtLink>` with `target`, `rel`, and `noRel` props.
```vue [app.vue]
<template>
<NuxtLink to="https://twitter.com/nuxt_js" target="_blank">
Nuxt Twitter
</NuxtLink>
<!-- <a href="https://twitter.com/nuxt_js" target="_blank" rel="noopener noreferrer">...</a> -->
<NuxtLink to="https://discord.nuxtjs.org" target="_blank" rel="noopener">
Nuxt Discord
</NuxtLink>
<!-- <a href="https://discord.nuxtjs.org" target="_blank" rel="noopener">...</a> -->
<NuxtLink to="https://github.com/nuxt" no-rel>
Nuxt GitHub
</NuxtLink>
<!-- <a href="https://github.com/nuxt">...</a> -->
<NuxtLink to="/contact" target="_blank">
Contact page opens in another tab
</NuxtLink>
<!-- <a href="/contact" target="_blank" rel="noopener noreferrer">...</a> -->
</template>
```
## Props
- `to`: Any URL or a [route location object](https://router.vuejs.org/api/interfaces/RouteLocation.html) from Vue Router
- `href`: An alias for `to`. If used with `to`, `href` will be ignored
- `target`: A `target` attribute value to apply on the link
- `rel`: A `rel` attribute value to apply on the link. Defaults to `"noopener noreferrer"` for external links.
- `noRel`: If set to `true`, no `rel` attribute will be added to the link
- `activeClass`: A class to apply on active links. Works the same as [Vue Router's `active-class` prop](https://router.vuejs.org/api/interfaces/RouterLinkProps.html#Properties-activeClass) on internal links. Defaults to Vue Router's default (`"router-link-active"`)
- `exactActiveClass`: A class to apply on exact active links. Works the same as [Vue Router's `exact-active-class` prop](https://router.vuejs.org/api/interfaces/RouterLinkProps.html#Properties-exactActiveClass) on internal links. Defaults to Vue Router's default `"router-link-exact-active"`)
- `replace`: Works the same as [Vue Router's `replace` prop](https://router.vuejs.org/api/interfaces/RouteLocationOptions.html#Properties-replace) on internal links
- `ariaCurrentValue`: An `aria-current` attribute value to apply on exact active links. Works the same as [Vue Router's `aria-current-value` prop](https://router.vuejs.org/api/interfaces/RouterLinkProps.html#Properties-ariaCurrentValue) on internal links
- `external`: Forces the link to be considered as external (`true`) or internal (`false`). This is helpful to handle edge-cases
- `prefetch` and **noPrefetch**: Whether to enable prefetching assets for links that enter the view port.
- `prefetchedClass`: A class to apply to links that have been prefetched.
- `custom`: Whether `<NuxtLink>` should wrap its content in an `<a>` element. It allows taking full control of how a link is rendered and how navigation works when it is clicked. Works the same as [Vue Router's `custom` prop](https://router.vuejs.org/api/interfaces/RouterLinkProps.html#Properties-custom)
::callout
Defaults can be overwritten, see [overwriting defaults](#overwriting-defaults) if you want to change them.
::
## Overwriting Defaults
You can overwrite `<NuxtLink>` defaults by creating your own link component using `defineNuxtLink`.
```js [components/MyNuxtLink.ts]
export default defineNuxtLink({
componentName: 'MyNuxtLink',
/* see signature below for more */
})
```
You can then use `<MyNuxtLink />` component as usual with your new defaults.
### `defineNuxtLink` Signature
```ts
defineNuxtLink({
componentName?: string;
externalRelAttribute?: string;
activeClass?: string;
exactActiveClass?: string;
prefetchedClass?: string;
trailingSlash?: 'append' | 'remove'
}) => Component
```
- `componentName`: A name for the defined `<NuxtLink>` component.
- `externalRelAttribute`: A default `rel` attribute value applied on external links. Defaults to `"noopener noreferrer"`. Set it to `""` to disable
- `activeClass`: A default class to apply on active links. Works the same as [Vue Router's `linkActiveClass` option](https://router.vuejs.org/api/interfaces/RouterOptions.html#Properties-linkActiveClass). Defaults to Vue Router's default (`"router-link-active"`)
- `exactActiveClass`: A default class to apply on exact active links. Works the same as [Vue Router's `linkExactActiveClass` option](https://router.vuejs.org/api/interfaces/RouterOptions.html#Properties-linkExactActiveClass). Defaults to Vue Router's default (`"router-link-exact-active"`)
- `prefetchedClass`: A default class to apply to links that have been prefetched.
- `trailingSlash`: An option to either add or remove trailing slashes in the `href`. If unset or not matching the valid values `append` or `remove`, it will be ignored.
:link-example{to="/docs/examples/routing/pages"}

View File

@ -0,0 +1,42 @@
---
title: '<NuxtLoadingIndicator>'
description: 'Display a progress bar between page navigations.'
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-loading-indicator.ts
size: xs
---
## Usage
Add `<NuxtLoadingIndicator/>` in your [`app.vue`](/docs/guide/directory-structure/app) or [`layouts/`](/docs/guide/directory-structure/layouts).
```vue [app.vue]
<template>
<NuxtLayout>
<div>
<NuxtLoadingIndicator /> <!-- here -->
<NuxtPage />
</div>
</NuxtLayout>
</template>
```
:link-example{to="/docs/examples/routing/pages"}
## Slots
You can pass custom HTML or components through the loading indicator's default slot.
## Props
- `color`: The color of the loading bar. It can be set to `false` to turn off explicit color styling.
- `height`: Height of the loading bar, in pixels (default `3`).
- `duration`: Duration of the loading bar, in milliseconds (default `2000`).
- `throttle`: Throttle the appearing and hiding, in milliseconds (default `200`).
::callout
This component is optional. :br
To achieve full customization, you can implement your own one based on [its source code](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-loading-indicator.ts).
::

View File

@ -0,0 +1,42 @@
---
title: "<NuxtErrorBoundary>"
description: The <NuxtErrorBoundary> component handles client-side errors happening in its default slot.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-error-boundary.ts
size: xs
---
::callout
The `<NuxtErrorBoundary>` uses Vue's [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle.html#onerrorcaptured) hook under the hood.
::
## Events
- `@error`: Event emitted when the default slot of the component throws an error.
```vue
<template>
<NuxtErrorBoundary @error="logSomeError">
<!-- ... -->
</NuxtErrorBoundary>
</template>
```
## Slots
- `#error`: Specify a fallback content to display in case of error.
```vue
<template>
<NuxtErrorBoundary>
<!-- ... -->
<template #error="{ error }">
<p>An error occurred: {{ error }}</p>
</template>
</NuxtErrorBoundary>
</template>
```
:read-more{to="/docs/getting-started/error-handling"}

View File

@ -0,0 +1,25 @@
---
title: '<NuxtWelcome>'
description: The `<NuxtWelcome>` component greets users in new projects made from the starter template.
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/assets/blob/main/packages/templates/templates/welcome/index.html
size: xs
---
It includes links to the Nuxt documentation, source code, and social media accounts.
```vue [app.vue]
<template>
<NuxtWelcome />
</template>
```
::read-more{to="https://templates.ui.nuxtjs.org/templates/welcome" target="_blank"}
Preview the `<NuxtWelcome />` component.
::
::callout
This component is part of [nuxt/assets](https://github.com/nuxt/assets).
::

View File

@ -1,45 +1,47 @@
---
title: "<NuxtIsland>"
description: "Nuxt provides `<NuxtIsland>` component to render a non-interactive component without any client JS"
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/components/nuxt-island.ts
size: xs
---
# `<NuxtIsland>`
Nuxt provide `<NuxtIsland>` to render components only server side.
When rendering an island component, the content of the island component is static, thus no JS is downloaded client-side.
Changing the island component props triggers a refetch of the island component to re-render it again.
::alert{type=warning}
::read-more{to="/docs/guide/going-further/experimental-features#componentislands" icon="i-ph-star-duotone"}
This component is experimental and in order to use it you must enable the `experimental.componentIslands` option in your `nuxt.config`.
::
::alert{type=info}
Global styles of your application are sent with the response
::callout
Global styles of your application are sent with the response.
::
::alert{type=info}
::callout
Server only components use `<NuxtIsland>` under the hood
::
## Props
- **name** : Name of the component to render.
- `name` : Name of the component to render.
- **type**: `string`
- **required**
- **lazy**: Make the component non-blocking.
- `lazy`: Make the component non-blocking.
- **type**: `boolean`
- **default**: `false`
- **props**: Props to send to the component to render.
- `props`: Props to send to the component to render.
- **type**: `Record<string, any>`
- **source**: Remote source to call the island to render.
- `source`: Remote source to call the island to render.
- **type**: `string`
::alert{type=warning}
::callout{color="blue" icon="i-ph-info-duotone"}
Remote islands need `experimental.componentIslands` to be `'local+remote'` in your `nuxt.config`.
::
## `Slots`
## Slots
Slots can be passed to an island component if declared.
@ -47,4 +49,4 @@ Every slot is interactive since the parent component is the one providing it.
Some slots are reserved to `NuxtIsland` for special cases.
- **fallback**: Specify the content to be rendered before the island loads (if the component is lazy) or if `NuxtIsland` fails to fetch the component.
- `#fallback`: Specify the content to be rendered before the island loads (if the component is lazy) or if `NuxtIsland` fails to fetch the component.

View File

@ -1,6 +1,11 @@
---
title: "<NuxtImg>"
description: "Nuxt provides a <NuxtImg> component to handle automatic image optimization."
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/image/blob/main/src/runtime/components/nuxt-img.ts
size: xs
---
`<NuxtImg>` is a drop-in replacement for the native `<img>` tag.
@ -33,6 +38,6 @@ Will result in:
<img src="/nuxt-icon.png" />
```
::read-more{to="https://image.nuxt.com/usage/nuxt-img"}
::read-more{to="https://image.nuxt.com/usage/nuxt-img" target="_blank"}
Read more about the `<NuxtImg>` component.
::

View File

@ -0,0 +1,3 @@
title: 'Components'
titleTemplate: '%s · Nuxt Components'
icon: i-ph-cube-duotone

View File

@ -1,3 +0,0 @@
navigation.icon: heroicons-outline:switch-horizontal
titleTemplate: '%s · Nuxt Composables'
image: '/socials/composables.jpg'

View File

@ -1,13 +0,0 @@
# `useAppConfig`
Access the reactive [app config](/docs/guide/directory-structure/app-config) defined in the project.
**Usage:**
```js
const appConfig = useAppConfig()
console.log(appConfig)
```
::ReadMore{link="/docs/guide/directory-structure/app-config"}

View File

@ -1,37 +0,0 @@
---
title: "useError"
description: useError composable returns the global Nuxt error that is being handled.
---
# `useError`
`useError` composable returns the global Nuxt error that is being handled and it is available on both client and server.
```ts
const error = useError()
```
`useError` sets an error in the state and creates a reactive as well as SSR-friendly global Nuxt error across components. Nuxt errors have the following properties:
## Properties
- **statusCode**
Type: `Number`
HTTP response status code
- **statusMessage**
Type: `String`
HTTP response status message
- **message**
Type: `String`
Error message
::ReadMore{link="/docs/getting-started/error-handling"}
::

View File

@ -1,100 +0,0 @@
---
description: useHead customizes the head properties of individual pages of your Nuxt app.
---
# useHead
The [`useHead`](/docs/api/composables/use-head) composable function allows you to manage your head tags in a programmatic and reactive way, powered by [Unhead](https://unhead.unjs.io/). If the data comes from a user or other untrusted source, we recommend you check out [`useHeadSafe`](/docs/api/composables/use-head-safe)
:ReadMore{link="/docs/getting-started/seo-meta"}
## Type
```ts
useHead(meta: MaybeComputedRef<MetaObject>): void
```
Below are the non-reactive types for [`useHead`](/docs/api/composables/use-head) .
```ts
interface MetaObject {
title?: string
titleTemplate?: string | ((title?: string) => string)
base?: Base
link?: Link[]
meta?: Meta[]
style?: Style[]
script?: Script[]
noscript?: Noscript[]
htmlAttrs?: HtmlAttributes
bodyAttrs?: BodyAttributes
}
```
See [@unhead/schema](https://github.com/unjs/unhead/blob/main/packages/schema/src/schema.ts) for more detailed types.
::alert{type=info}
The properties of [`useHead`](/docs/api/composables/use-head) can be dynamic, accepting `ref`, `computed` and `reactive` properties. `meta` parameter can also accept a function returning an object to make the entire object reactive.
::
## Parameters
### `meta`
**Type**: `MetaObject`
An object accepting the following head metadata:
- `meta`
**Type**: `Array<Record<string, any>>`
Each element in the array is mapped to a newly-created `<meta>` tag, where object properties are mapped to the corresponding attributes.
- `link`
**Type**: `Array<Record<string, any>>`
Each element in the array is mapped to a newly-created `<link>` tag, where object properties are mapped to the corresponding attributes.
- `style`
**Type**: `Array<Record<string, any>>`
Each element in the array is mapped to a newly-created `<style>` tag, where object properties are mapped to the corresponding attributes.
- `script`
**Type**: `Array<Record<string, any>>`
Each element in the array is mapped to a newly-created `<script>` tag, where object properties are mapped to the corresponding attributes.
- `noscript`
**Type**: `Array<Record<string, any>>`
Each element in the array is mapped to a newly-created `<noscript>` tag, where object properties are mapped to the corresponding attributes.
- `titleTemplate`
**Type**: `string` | `((title: string) => string)`
Configures dynamic template to customize the page title on an individual page.
- `title`
**Type**: `string`
Sets static page title on an individual page.
- `bodyAttrs`
**Type**: `Record<string, any>`
Sets attributes of the `<body>` tag. Each object property is mapped to the corresponding attribute.
- `htmlAttrs`
**Type**: `Record<string, any>`
Sets attributes of the `<html>` tag. Each object property is mapped to the corresponding attribute.

View File

@ -1,38 +0,0 @@
# `useHydration`
Allows full control of the hydration cycle to set and receive data from the server.
`useHydration` is a built-in composable that provides a way to set data on the server side every time a new HTTP request is made and receive that data on the client side. This way `useHydration` allows you to take full control of the hydration cycle.
## Type
```ts [signature]
useHydration <T> (key: string, get: () => T, set: (value: T) => void) => {}
```
You can use `useHydration()` within composables, plugins and components.
`useHydration` accepts three parameters:
- `key`
**Type**: `String`
`key` is a unique key that identifies the data in your Nuxt application
- `get`
**Type**: `Function`
`get` is a function that returns the value to set the initial data
- `set`
**Type**: `Function`
`set` a function that receives the data on the client-side
Once the initial data is returned using the `get` function on the server side, you can access that data within `nuxtApp.payload` using the unique key that is passed as the first parameter in `useHydration` composable.
::ReadMore{link="/docs/getting-started/data-fetching"}
::

View File

@ -1,43 +0,0 @@
---
description: This wrapper around useAsyncData triggers navigation immediately.
---
# `useLazyAsyncData`
`useLazyAsyncData` provides a wrapper around [`useAsyncData`](/docs/api/composables/use-async-data) that triggers navigation before the handler is resolved by setting the `lazy` option to `true`.
## Description
By default, [useAsyncData](/docs/api/composables/use-async-data) blocks navigation until its async handler is resolved.
> `useLazyAsyncData` has the same signature as [`useAsyncData`](/docs/api/composables/use-async-data) .
:ReadMore{link="/docs/api/composables/use-async-data"}
## Example
```vue
<script setup lang="ts">
/* Navigation will occur before fetching is complete.
Handle pending and error states directly within your component's template
*/
const { pending, data: count } = await useLazyAsyncData('count', () => $fetch('/api/count'))
watch(count, (newCount) => {
// Because count might start out null, you won't have access
// to its contents immediately, but you can watch it.
})
</script>
<template>
<div>
{{ pending ? 'Loading' : count }}
</div>
</template>
```
::alert{type=warning}
`useLazyAsyncData` is a reserved function name transformed by the compiler, so you should not name your own function `useLazyAsyncData`.
::
:ReadMore{link="/docs/getting-started/data-fetching#uselazyasyncdata"}

View File

@ -1,25 +0,0 @@
# useRequestURL
`useRequestURL` is a helper function that returns an [URL object](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) working on both server-side and client-side.
::code-group
```vue [pages/about.vue]
<script setup lang="ts">
const url = useRequestURL()
</script>
<template>
<p>URL is: {{ url }}</p>
<p>Path is: {{ url.pathname }}</p>
</template>
```
```html [Result in development]
<p>URL is: http://localhost:3000/about</p>
<p>Path is: /about</p>
```
::
You can find the list of the [URL instance properties](https://developer.mozilla.org/en-US/docs/Web/API/URL#instance_properties) on the MDN documentation.

View File

@ -1,66 +0,0 @@
---
title: "useRouter"
description: "The useRouter composable returns the router instance."
---
# `useRouter`
The [`useRouter`](/docs/api/composables/use-router) composable returns the router instance and must be called in a setup function, plugin, or route middleware.
Within the template of a Vue component, you can access the router using `$router` instead.
If you have a `pages/` folder, [`useRouter`](/docs/api/composables/use-router) is identical in behavior to the one provided by `vue-router`. Feel free to read the router documentation for more information on what each method does.
::ReadMore{link="https://router.vuejs.org/api/interfaces/Router.html#Properties-currentRoute"}
::
## Basic Manipulation
- **addRoute:** Add a new route to the router instance. `parentName` can be provided to add new route as the child of an existing route.
- **removeRoute:** Remove an existing route by its name.
- **getRoutes:** Get a full list of all the route records.
- **hasRoute:** Checks if a route with a given name exists.
## Based on History API
- **back:** Go back in history if possible, same as `router.go(-1)`.
- **forward:** Go forward in history if possible, same as `router.go(1)`.
- **go:** Move forward or backward through the history without the hierarchical restrictions enforced in `router.back()` and `router.forward()`.
- **push:** Programmatically navigate to a new URL by pushing an entry in the history stack. **It is recommended to use [`navigateTo`](/docs/api/utils/navigate-to) instead.**
- **replace:** Programmatically navigate to a new URL by replacing the current entry in the routes history stack. **It is recommended to use [`navigateTo`](/docs/api/utils/navigate-to) instead.**
> TIP: `router.addRoute()` adds route details into an array of routes and it is useful while building Nuxt plugins while `router.push()` on the other hand, triggers a new navigation immediately and it is useful in Nuxt Page components, Vue components and composable.
```js [js]
const router = useRouter();
router.back();
router.forward();
router.go();
router.push({ path: "/home" });
router.replace({ hash: "#bio" });
````
::ReadMore{link="https://developer.mozilla.org/en-US/docs/Web/API/History"}
::
## Navigation Guards
`useRouter` composable provides `afterEach`, `beforeEach` and `beforeResolve` helper methods that acts as navigation guards.
However, Nuxt has a concept of **route middleware** that simplifies the implementation of navigation guards and provides a better developer experience.
::ReadMore{link="/docs/guide/directory-structure/middleware"}
::
## Promise and Error Handling
- **isReady:** Returns a Promise that resolves when the router has completed the initial navigation.
- **onError:** Adds an error handler that is called every time a non caught error happens during navigation.
- **resolve:** Returns the normalized version of a route location. Also includes an `href` property that includes any existing base.
::ReadMore{link="https://router.vuejs.org/api/interfaces/Router.html#Methods"}
::
## Universal Router Instance
If you do not have a `pages/` folder, then [`useRouter`](/docs/api/composables/use-router) will return a universal router instance with similar helper methods, but be aware that not all features may be supported or behave in exactly the same way as with `vue-router`.

Some files were not shown because too many files have changed in this diff Show More