matijao/webdev huggingface dataset:
How Nuxt Works? · Nuxt Advanced

Guide
Going Further
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.

The Nuxt Interface

When you start Nuxt in development mode with nuxi dev or building a production application with nuxi 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 powered by 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 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.

For more details, check out the source code.

The NuxtApp Interface

When rendering a page in the browser or on the server, a shared context will be created, referred to as nuxtApp. 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. 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.

Check Nuxt App for more information about this interface.

nuxtApp has the following properties:

const nuxtApp = {

  vueApp, // the global Vue application: https://vuejs.org/api/application.html#application-api



  versions, // an object containing Nuxt and Vue versions



  // These let you call and add runtime NuxtApp hooks

  // https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/nuxt.ts#L18

  hooks,

  hook,

  callHook,



  // Only accessible on server-side

  ssrContext: {

    url,

    req,

    res,

    runtimeConfig,

    noSSR,

  },



  // This will be stringified and passed from server to client

  payload: {

    serverRendered: true,

    data: {},

    state: {}

  }



  provide: (name: string, value: any) => void

}


For more details, check out the source code.

Runtime Context vs. Build Context

Nuxt builds and bundles project using Node.js but also has a runtime side.

While both areas can be extended, that runtime context is isolated from build-time. Therefore, they are not supposed to share state, code, or context other than runtime configuration!

nuxt.config and Nuxt Modules can be used to extend the build context, and Nuxt 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.

Experimental Features

Enable Nuxt experimental features to unlock new possibilities.

Lifecycle Hooks

Nuxt provides a powerful hooking system to expand almost every aspect using hooks.
tsconfig.json · Nuxt Directory Structure

Guide
Directory Structure
tsconfig.json

Nuxt generates a .nuxt/tsconfig.json file with sensible defaults and your aliases.

Nuxt automatically generates 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:

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.
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.

package.json

The package.json file contains all the dependencies and scripts for your application.

Experimental Features

Enable Nuxt experimental features to unlock new possibilities.
package.json · Nuxt Directory Structure

Guide
Directory Structure
package.json

The package.json file contains all the dependencies and scripts for your application.

The minimal package.json of your Nuxt application should looks like:

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 about the package.json file.

nuxt.config.ts

Nuxt can be easily configured with a single nuxt.config file.

tsconfig.json

Nuxt generates a .nuxt/tsconfig.json file with sensible defaults and your aliases.
.nuxtignore · Nuxt Directory Structure

Guide
Directory Structure
.nuxtignore

The .nuxtignore file lets Nuxt ignore files in your project’s root directory during the build phase.

The .nuxtignore file tells Nuxt to ignore files in your project’s root directory (rootDir) during the build phase.

It 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.

You can also configure ignoreOptions, ignorePrefix and ignore in your nuxt.config file.
Usage
.nuxtignore
# ignore layout foo.vue

layouts/foo.vue

# ignore layout files whose name ends with -ignore.vue

layouts/*-ignore.vue



# ignore page bar.vue

pages/bar.vue

# ignore page inside ignore folder

pages/ignore/*.vue



# ignore route middleware files under foo folder except foo/bar.js

middleware/foo/*.js

!middleware/foo/bar.js

More details about the spec are in the gitignore documentation.

.gitignore

A .gitignore file specifies intentionally untracked files that git should ignore.

app.config.ts

Expose reactive configuration within your application with the App Config file.
.gitignore · Nuxt Directory Structure

Guide
Directory Structure
.gitignore

A .gitignore file specifies intentionally untracked files that git should ignore.

A .gitignore file specifies intentionally untracked files that git should ignore.

 Read more in the git documentation.

We recommend having a .gitignore file that has at least the following entries present:

.gitignore
# Nuxt dev/build outputs

.output

.data

.nuxt

.nitro

.cache

dist



# Node dependencies

node_modules



# Logs

logs

*.log



# Misc

.DS_Store



# Local env files

.env

.env.*

!.env.example


.env

A .env file specifies your build/dev-time environment variables.

.nuxtignore

The .nuxtignore file lets Nuxt ignore files in your project’s root directory during the build phase.
.env · Nuxt Directory Structure

Guide
Directory Structure
.env

A .env file specifies your build/dev-time environment variables.

This file should be added to your .gitignore file to avoid pushing secrets to your repository.
Dev, Build and Generate Time

Nuxt CLI has built-in 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 dev, build and generate time. Any environment variables set there will be accessible within your nuxt.config file and modules.

.env
MY_ENV_VARIABLE=hello

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.

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.

For local production preview purpose, we recommend using nuxi 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:

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.

 Read more in Docs > Guide > Going Further > Runtime Config.
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.
 Read more in Docs > Guide > Directory Structure > App Config.

utils

Use the utils/ directory to auto-import your utility functions throughout your application.

.gitignore

A .gitignore file specifies intentionally untracked files that git should ignore.
utils/ · Nuxt Directory Structure

Guide
Directory Structure
utils

Use the utils/ directory to auto-import your utility functions throughout your application.

The main purpose of the utils/ directory is to allow a semantic distinction between your Vue composables and other auto-imported utility functions.

Usage

Method 1: Using named export

utils/index.ts
export const { format: formatNumber } = Intl.NumberFormat('en-GB', {

  notation: 'compact',

  maximumFractionDigits: 1

})


Method 2: Using default export

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

app.vue
<template>

  <p>{{ formatNumber(1234) }}</p>

</template>

 Read more in Docs > Guide > Concepts > Auto Imports.
 Read and edit a live example in Docs > Examples > Features > Auto Imports.
The way utils/ auto-imports work and are scanned is identical to the composables/ directory.
These utils are only available within the Vue part of your app.
Only server/utils are auto-imported in the server/ directory.

server

The server/ directory is used to register API and server handlers to your application.

.env

A .env file specifies your build/dev-time environment variables.
node_modules/ · Nuxt Directory Structure

Guide
Directory Structure
node_modules

The package manager stores the dependencies of your project in the node_modules/ directory.

The package manager (npm or yarn or pnpm or bun) creates this directory to store the dependencies of your project.

This directory should be added to your .gitignore file to avoid pushing the dependencies to your repository.

modules

Use the modules/ directory to automatically register local modules within your application.

pages

Nuxt provides file-based routing to create routes within your web application.
public/ · Nuxt Directory Structure

Guide
Directory Structure
public

The public/ directory is used to serve your website's static assets.

Files contained within the public/ directory are served at the root and are not modified by the build process. This is suitable for files that have to keep their names (e.g. robots.txt) or likely won't change (e.g. favicon.ico).

Directory structure
-| public/

---| favicon.ico

---| og-image.png

---| robots.txt

app.vue
<script setup>

useSeoMeta({

  ogImage: '/og-image.png'

})

</script>

This is known as the static/ directory in Nuxt 2.

plugins

Nuxt has a plugins system to use Vue plugins and more at the creation of your Vue application.

server

The server/ directory is used to register API and server handlers to your application.
modules/ · Nuxt Directory Structure

Guide
Directory Structure
modules

Use the modules/ directory to automatically register local modules within 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
modules/*.ts

You don't need to add those local modules to your nuxt.config.ts separately.

modules/hello/index.ts
modules/hello/runtime/api-route.ts
// `nuxt/kit` is a helper subpath import you can use when defining local modules

// that means you do not need to add `@nuxt/kit` to your project's dependencies

import { createResolver, defineNuxtModule, addServerHandler } from 'nuxt/kit'



export default defineNuxtModule({

  meta: {

    name: 'hello'

  },

  setup () {

    const { resolve } = createResolver(import.meta.url)



    // Add an API route

    addServerHandler({

      route: '/api/hello',

      handler: resolve('./runtime/api-route')

    })

  }

})


When starting Nuxt, the hello module will be registered and the /api/hello route will be available.

Local modules are registered in alphabetical order. You can change the order by adding a number to the front of each directory name:

Directory structure
modules/

  1.first-module/

    index.ts

  2.second-module.ts

 Read more in Docs > Guide > Going Further > Modules.

middleware

Nuxt provides middleware to run code before navigating to a particular route.

node_modules

The package manager stores the dependencies of your project in the node_modules/ directory.
composables/ · Nuxt Directory Structure

Guide
Directory Structure
composables

Use the composables/ directory to auto-import your Vue composables into your application.

Usage

Method 1: Using named export

composables/useFoo.ts
export const useFoo = () => {

  return useState('foo', () => 'bar')

}


Method 2: Using default export

composables/use-foo.ts or composables/useFoo.ts
// It will be available as useFoo() (camelCase of file name without extension)

export default function () {

  return useState('foo', () => 'bar')

}


Usage: You can now use auto imported composable in .js, .ts and .vue files

app.vue
<script setup lang="ts">

const foo = useFoo()

</script>



<template>

  <div>

    {{ foo }}

  </div>

</template>

 Read more in Docs > Guide > Concepts > Auto Imports.
 Read and edit a live example in 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, 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'.
Examples
Nested Composables

You can use a composable within another composable using auto imports:

composables/test.ts
export const useFoo = () => {

  const nuxtApp = useNuxtApp()

  const bar = useBar()

}

Access plugin injections

You can access plugin injections from composables:

composables/test.ts
export const useHello = () => {

  const nuxtApp = useNuxtApp()

  return nuxtApp.$hello

}

How Files Are Scanned

Nuxt only scans files at the top level of the composables/ directory, e.g.:

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.

To get auto imports working for nested modules, you could either re-export them (recommended) or configure the scanner to include nested directories:

Example: Re-export the composables you need from the composables/index.ts file:

composables/index.ts
// Enables auto import for this export

export { utils } from './nested/utils.ts'


Example: Scan nested directories inside the composables/ folder:

nuxt.config.ts
export default defineNuxtConfig({

  imports: {

    dirs: [

      // Scan top-level modules

      'composables',

      // ... or scan modules nested one level deep with a specific name and file extension

      'composables/*/index.{ts,js,mjs,mts}',

      // ... or scan all modules within given directory

      'composables/**'

    ]

  }

})


components

The components/ directory is where you put all your Vue components.

content

Use the content/ directory to create a file-based CMS for your application.
content/ · Nuxt Directory Structure

Guide
Directory Structure
content

Use the content/ directory to create a file-based CMS for your application.

Nuxt Content reads the content/ directory 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.
Learn more in Nuxt Content documentation.
Enable Nuxt Content

Install the @nuxt/content module in your project as well as adding it to your nuxt.config.ts with one command:

Terminal
npx nuxi module add content

Create Content

Place your markdown files inside the content/ directory:

content/index.md
# Hello Content


The module automatically loads and parses them.

Render Content

To render content pages, add a catch-all route using the <ContentDoc> component:

pages/[...slug].vue
<template>

  <main>

    <!-- ContentDoc returns content for `$route.path` by default or you can pass a `path` prop -->

    <ContentDoc />

  </main>

</template>

Documentation
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.

composables

Use the composables/ directory to auto-import your Vue composables into your application.

layouts

Nuxt provides a layouts framework to extract common UI patterns into reusable layouts.
TypeScript · Nuxt Concepts

Guide
Key Concepts
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.

To enable type-checking at build or development time, install vue-tsc and typescript as development dependency:

yarn
npm
pnpm
bun
yarn add --dev vue-tsc typescript


Then, run nuxi typecheck command to check your types:

Terminal
npx nuxi typecheck


To enable type-checking at build time, you can also use the typescript.typeCheck option in your nuxt.config file:

nuxt.config.ts
export default defineNuxtConfig({

  typescript: {

    typeCheck: true

  }

})

Auto-generated Types

When you run nuxi dev or nuxi build, Nuxt generates the following files for IDE type support (and type checking):

.nuxt/nuxt.d.ts

This file contains the types of any modules you are using, as well as the key types that Nuxt 3 requires. Your IDE should recognize these types automatically.

Some of the references in the file are to files that are only generated within your buildDir (.nuxt) and therefore for full typings, you will need to run nuxi dev or nuxi build.

.nuxt/tsconfig.json

This file contains the recommended basic TypeScript configuration for your project, including resolved aliases injected by Nuxt or modules you are using, so you can get full type support and path auto-complete for aliases like ~/file or #build/file.

Read more about how to extend this configuration.

Nitro also auto-generates types for API routes. Plus, Nuxt also generates types for globally available components and auto-imports from your composables, plus other core functionality.
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 within your nuxt.config. nuxi will pick them up and extend ./.nuxt/tsconfig.json accordingly.
Stricter Checks

TypeScript comes with certain checks to give you more safety and analysis of your program.

Once you’ve converted your codebase to TypeScript and felt familiar with it, you can start enabling these checks for greater safety (read more).

In order to enable strict type checking, you have to update nuxt.config:

nuxt.config.ts
export default defineNuxtConfig({

  typescript: {

    strict: true

  }

})


ES Modules

Nuxt 3 (and Bridge) uses Native ES Modules.

.nuxt

Nuxt uses the .nuxt/ directory in development to generate your Vue application.
assets/ · Nuxt Directory Structure

Guide
Directory Structure
assets

The assets/ directory is used to add all the website's assets that the build tool will process.

The directory usually contains the following types of files:

Stylesheets (CSS, SASS, etc.)
Fonts
Images that won't be served from the public/ directory.

If you want to serve assets from the server, we recommend taking a look at the public/ directory.

 Read more in Docs > Getting Started > Assets.

.output

Nuxt creates the .output/ directory when building your application for production.

components

The components/ directory is where you put all your Vue components.
.output/ · Nuxt Directory Structure

Guide
Directory Structure
.output

Nuxt creates the .output/ directory when building your application for production.

This directory should be added to your .gitignore file to avoid pushing the build output to your repository.

Use this directory to deploy your Nuxt application to production.

 Read more in Docs > Getting Started > Deployment.
You should not touch any files inside since the whole directory will be re-created when running nuxt build.

.nuxt

Nuxt uses the .nuxt/ directory in development to generate your Vue application.

assets

The assets/ directory is used to add all the website's assets that the build tool will process.
.nuxt/ · Nuxt Directory Structure

Guide
Directory Structure
.nuxt

Nuxt uses the .nuxt/ directory in development to generate your Vue application.

This directory should be added to your .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.

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 opening the Nuxt DevTools in development mode and navigating to the Virtual Files tab.

You should not touch any files inside since the whole directory will be re-created when running nuxt dev.

TypeScript

Nuxt 3 is fully typed and provides helpful shortcuts to ensure you have access to accurate type information when you are coding.

.output

Nuxt creates the .output/ directory when building your application for production.
Modules · Nuxt Concepts

Guide
Key Concepts
Modules

Nuxt provides a module system to extend the framework core and simplify integrations.

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.

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.

Explore Nuxt Modules
Add Nuxt Modules

Once you have installed the modules you can add them to your nuxt.config.ts file under the modules property. Module developers usually provide additional steps and details for usage.

nuxt.config.ts
export default defineNuxtConfig({

  modules: [

    // Using package name (recommended usage)

    '@nuxtjs/example',



    // Load a local module

    './modules/example',



    // Add module with inline-options

    ['./modules/example', { token: '123' }]



    // Inline module definition

    async (inlineOptions, nuxt) => { }

  ]

})

Nuxt modules are now build-time-only, and the buildModules property used in Nuxt 2 is deprecated in favor of modules.
Create a Nuxt Module

Everyone has the opportunity to develop modules and we cannot wait to see what you will build.

 Read more in Module Author Guide.

Server Engine

Nuxt 3 is powered by a new server engine: Nitro.

ES Modules

Nuxt 3 (and Bridge) uses Native ES Modules.
Server Engine · Nuxt Concepts

Guide
Key Concepts
Server Engine

Nuxt 3 is powered by a new server engine: Nitro.

While building Nuxt 3, we created a new server engine: Nitro.

It is shipped with many features:

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

Server API endpoints and Middleware are added by Nitro that internally uses h3.

Key features include:

Handlers can directly return objects/arrays for an automatically-handled JSON response
Handlers can return promises, which will be awaited (res.end() and next() are also supported)
Helper functions for body parsing, cookie handling, redirects, headers and more

Check out the h3 docs for more information.

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.

$fetch API is using 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

For more information on $fetch features, check out ofetch.

Typed API Routes

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().

Standalone Server

Nitro produces a standalone server dist that is independent of node_modules.

The server in Nuxt 2 is not standalone and requires part of Nuxt core to be involved by running nuxt start (with the nuxt-start or nuxt distributions) or custom programmatic usage, which is fragile and prone to breakage and not suitable for serverless and service-worker environments.

Nuxt 3 generates this dist when running nuxt build into a .output directory.

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.

Read more about Nitro engine on GitHub.

Rendering Modes

Learn about the different rendering modes available in Nuxt.

Modules

Nuxt provides a module system to extend the framework core and simplify integrations.
Testing · Get Started with Nuxt

Get Started
Testing

How to test your Nuxt application.

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

In Nuxt 3, we have a rewritten version of @nuxt/test-utils. We support Vitest and Jest as test runners.

Installation
yarn
npm
pnpm
bun
yarn 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.

test/my-test.spec.ts
import { describe, test } from 'vitest'

import { setup, $fetch } from '@nuxt/test-utils'



describe('My test', async () => {

  await setup({

    // test context options

  })



  test('my test', () => {

    // ...

  })

})


Behind the scenes, setup performs a number of tasks in beforeAll, beforeEach, afterEach and afterAll to set up the Nuxt test environment correctly.

Please use the options below for the setup method.

Nuxt Config
rootDir: Path to a directory with a Nuxt app to be put under test.
Type: string
Default: '.'
configFile: Name of the configuration file.
Type: string
Default: 'nuxt.config'
Timings
setupTimeout: The amount of time (in milliseconds) to allow for setupTest to complete its work (which could include building or generating files for a Nuxt application, depending on the options that are passed).
Type: number
Default: 60000
Features
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 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.
runner: Specify the runner for the test suite. Currently, Vitest is recommended.
Type: 'vitest' | 'jest'
Default: 'vitest'
APIs
$fetch(url)

Get the HTML of a server-rendered page.

import { $fetch } from '@nuxt/test-utils'



const html = await $fetch('/')

fetch(url)

Get the response of a server-rendered page.

import { fetch } from '@nuxt/test-utils'



const res = await fetch('/')

const { body, headers } = res

url(path)

Get the full URL for a given page (including the port the test server is running on.)

import { url } from '@nuxt/test-utils'



const pageUrl = url('/page')

// 'http://localhost:6840/page'

Testing in a Browser
We are working on it, stay tuned!

Deployment

Learn how to deploy your Nuxt application to any hosting provider.

Upgrade Guide

Learn how to upgrade to the latest Nuxt version.
Upgrade Guide · Get Started with Nuxt

Get Started
Upgrade Guide

Learn how to upgrade to the latest Nuxt version.

Upgrading Nuxt 3
Latest release

To upgrade Nuxt 3 to the latest release, use the nuxi upgrade command.

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 guide.

Nuxt 2 vs Nuxt 3

In the table below, there is a quick comparison between 3 versions of Nuxt:

Feature / Version	Nuxt 2	Nuxt Bridge	Nuxt 3
Vue	2	2	3
Stability	😊 Stable	😌 Semi-stable	😊 Stable
Performance	🏎 Fast	✈️ Faster	🚀 Fastest
Nitro Engine	❌	✅	✅
ESM support	🌙 Partial	👍 Better	✅
TypeScript	☑️ Opt-in	🚧 Partial	✅
Composition API	❌	🚧 Partial	✅
Options API	✅	✅	✅
Components Auto Import	✅	✅	✅
<script setup> syntax	❌	🚧 Partial	✅
Auto Imports	❌	✅	✅
webpack	4	4	5
Vite	⚠️ Partial	🚧 Partial	✅
Nuxi CLI	❌ Old	✅ nuxi	✅ nuxi
Static sites	✅	✅	✅
Nuxt 2 to Nuxt 3

The migration guide provides a step-by-step comparison of Nuxt 2 features to Nuxt 3 features and guidance to adapt your current application.

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.

Migrate from Nuxt 2 to Nuxt Bridge

Testing

How to test your Nuxt application.

Auto-imports

Nuxt auto-imports components, composables, helper functions and Vue APIs.
Server · Get Started with Nuxt

Get Started
Server

Build full-stack applications with Nuxt's server framework. You can fetch data from your database or another server, create APIs, or even generate static server-side content like a sitemap or a RSS feed - all from a single codebase.

 Read more in Docs > Guide > Directory Structure > Server.
Powered by Nitro

Nuxt's server is Nitro. It was originally created for Nuxt but is now part of UnJS and open for other frameworks - and can even be used on its own.

Using Nitro gives Nuxt superpowers:

Full control of the server-side part of your app
Universal deployment on any provider (many zero-config)
Hybrid rendering

Nitro is internally using h3, a minimal H(TTP) framework built for high performance and portability.

Server Endpoints & Middleware

You can easily manage the server-only part of your Nuxt app, from API endpoints to middleware.

Both endpoints and middleware can be defined like this:

server/api/test.ts
export default defineEventHandler(async (event) => {

  // ... Do whatever you want here

})


And you can directly return text, json, html or even a stream.

Out-of-the-box, it supports hot module replacement and auto-import like the other parts of your Nuxt application.

 Read more in 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 in Blog > Nuxt On The Edge.

There are more than 15 presets to build your Nuxt app for different cloud providers and servers, including:

Cloudflare Workers
Netlify Functions
Vercel Edge Network
Lagon

Or for other runtimes:

Deno

Bun

 Read more in Docs > Getting Started > Deployment.
Hybrid Rendering

Nitro has a powerful feature called routeRules which allows you to define a set of rules to customize how each route of your Nuxt app is rendered (and more).

nuxt.config.ts
export default defineNuxtConfig({

  routeRules: {

    // Generated at build time for SEO purpose

    '/': { prerender: true },

    // Cached for 1 hour

    '/api/*': { cache: { maxAge: 60 * 60 } },

    // Redirection to avoid 404

    '/old-page': {

      redirect: { to: { '/new-page', statusCode: 302 }

    }

    // ...

  }

})

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 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.

 Read more in Docs > Guide > Concepts > Rendering.

Error Handling

Learn how to catch and handle errors in Nuxt.

Layers

Nuxt provides a powerful system that allows you to extend the default files, configs, and much more.
Layers · Get Started with Nuxt

Get Started
Layers

Nuxt provides a powerful system that allows you to extend the default files, configs, and much more.

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.

Use Cases
Share reusable configuration presets across projects using nuxt.config and app.config
Create a component library using components/ directory
Create utility and composable library using composables/ and utils/ directories
Create Nuxt module presets
Share standard setup across projects
Create Nuxt themes
Usage

You can extend a layer by adding the extends property to the nuxt.config.ts file.

nuxt.config.ts
export default defineNuxtConfig({

  extends: [

    '../base',                     // Extend from a local layer

    '@my-themes/awesome',          // Extend from an installed npm package

    'github:my-themes/awesome#v1', // Extend from a git repository

  ]

})

Read more about layers in the Layer Author Guide.
Watch Learn Vue video about Nuxt Layers.
Examples
Nuxt Docus Theme
Nuxt Content Wind Theme

Server

Build full-stack applications with Nuxt's server framework. You can fetch data from your database or another server, create APIs, or even generate static server-side content like a sitemap or a RSS feed - all from a single codebase.

Deployment

Learn how to deploy your Nuxt application to any hosting provider.
Assets · Get Started with Nuxt

Get Started
Assets

Nuxt offers two options for your assets.

Nuxt uses two directories to handle assets like stylesheets, fonts or images.

The public/ directory content is served at the server root as-is.
The assets/ directory contains by convention every asset that you want the build tool (Vite or webpack) to process.
Public Directory

The 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 from your application's code or from a browser by the root URL /.

Example

For example, referencing an image file in the public/img/ directory, available at the static URL /img/nuxt.png:

app.vue
<template>

  <img src="/img/nuxt.png" alt="Discover Nuxt 3" />

</template>

Assets Directory

Nuxt uses Vite (default) or webpack 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 (for Vite) or 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 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 by using the ~/assets/ path.

Example

For example, referencing an image file that will be processed if a build tool is configured to handle this file extension:

app.vue
<template>

  <img src="~/assets/img/nuxt.png" alt="Discover Nuxt 3" />

</template>

Nuxt won't serve files in the assets/ directory at a static URL like /assets/my-file.png. If you need a static URL, use the public/ directory.
Global Styles Imports

To globally insert statements in your Nuxt components styles, you can use the Vite option at your nuxt.config file.

Example

In this example, there is a sass partial file containing color variables to be used by your Nuxt pages and components

assets/_colors.scss
assets/_colors.sass
$primary: #49240F;

$secondary: #E4A79D;


In your nuxt.config

SCSS
SASS
export default defineNuxtConfig({

  vite: {

    css: {

      preprocessorOptions: {

        scss: {

          additionalData: '@use "@/assets/_colors.scss" as *;'

        }

      }

    }

  }

})


Views

Nuxt provides several component layers to implement the user interface of your application.

Styling

Learn how to style your Nuxt application.
Installation · Get Started with Nuxt

Get Started
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:

Open on StackBlitz

Open on CodeSandbox

Start with one of our starters and themes directly by opening nuxt.new.

New Project
Prerequisites
Node.js - v18.0.0 or newer
Text editor - We recommend Visual Studio Code with the Volar Extension
Terminal - In order to run Nuxt commands
Additional notes for an optimal setup:

Open a terminal (if you're using Visual Studio Code, you can open an integrated terminal) and use the following command to create a new starter project:

npx
pnpm
bun
npx nuxi@latest init <project-name>


Open your project folder in Visual Studio Code:

Terminal
code <project-name>


Or change directory into your new project from your terminal:

cd <project-name>


Install the dependencies:

yarn
npm
pnpm
bun
yarn install

Development Server

Now you'll be able to start your Nuxt app in development mode:

yarn
npm
pnpm
bun
yarn dev -o

Well done! A browser window should automatically open for http://localhost:3000.
Next Steps

Now that you've created your Nuxt 3 project, you are ready to start building your application.

 Read more in Nuxt Concepts.

Introduction

Nuxt's goal is to make web development intuitive and performant with a great Developer Experience in mind.

Configuration

Nuxt is configured with sensible defaults to make you productive.