matijao/webdev huggingface dataset:
Getting Help · Nuxt Community

Community
Getting Help

We're a friendly community of developers and we'd love to help.

At some point, you may find that there's an issue you need some help with.

But don't worry! We're a friendly community of developers and we'd love to help.

"I can't figure out how to (...)."

You've read through these docs and you think it should be possible, but it's not clear how. The best thing is to open a GitHub Discussion.

Please don't feel embarrassed about asking a question that you think is easy - we've all been there! ❤️

Everyone you'll encounter is helping out because they care, not because they are paid to do so. The kindest thing to do is make it easy for them to help you. Here are some ideas:

Explain what your objective is, not just the problem you're facing. "I need to ensure my form inputs are accessible, so I'm trying to get the ids to match between server and client."
Make sure you've first read the docs and used your favorite search engine. Let people know by saying something like "I've Googled for 'nuxt script setup' but I couldn't find code examples anywhere."
Explain what you've tried. Tell people the kind of solutions you've experimented with, and why. Often this can make people's advice more relevant to your situation.
Share your code. People probably won't be able to help if they just see an error message or a screenshot - but that all changes if you share your code in a copy/pasteable format - preferably in the form of a minimal reproduction like a CodeSandbox.

And finally, just ask the question! There's no need to ask permission to ask a question or wait for someone to reply to your 'hello'. If you do, you might not get a response because people are waiting for the whole question before engaging.

"Could there be a bug?"

Something isn't working the way that the docs say that it should. You're not sure if it's a bug. You've searched through the open issues and discussions but you can't find anything. (if there is a closed issue, please create a new one)

We recommend taking a look at how to report bugs. Nuxt 3 is still in active development, and every issue helps make it better.

Nuxt Configuration

Discover all the options you can use in your nuxt.config.ts file.

Reporting Bugs

One of the most valuable roles in open source is taking the time to report bugs helpfully.
Import meta · Nuxt API

Advanced
Import meta

Understand where your code is running using `import.meta`.

The import.meta object

With ES modules you can obtain some metadata from the code that imports or compiles your ES-module. This is done through import.meta, which is an object that provides your code with this information. Throughout the Nuxt documentation you may see snippets that use this already to figure out whether the code is currently running on the client or server side.

 Read more in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta.
Runtime (App) Properties

These values are statically injected and can be used for tree-shaking your runtime code.

Property	Type	Description
import.meta.client	boolean	True when evaluated on the client side.
import.meta.browser	boolean	True when evaluated on the client side.
import.meta.server	boolean	True when evaluated on the server side.
import.meta.nitro	boolean	True when evaluated on the server side.
import.meta.dev	boolean	True when running the Nuxt dev server.
import.meta.test	boolean	True when running in a test context.
import.meta.prerender	boolean	True when rendering HTML on the server in the prerender stage of your build.
Builder Properties

These values are available both in modules and in your nuxt.config.

Property	Type	Description
import.meta.env	object	Equals process.env
import.meta.url	string	Resolvable path for the current file.
Examples
Using import.meta.url to resolve files within modules
modules/my-module/index.ts
import { createResolver } from 'nuxt/kit'



// Resolve relative from the current file

const resolver = createResolver(import.meta.url)



export default defineNuxtModule({

  meta: { name: 'myModule' },

  setup() {

    addComponent({

      name: 'MyModuleComponent',

      // Resolves to '/modules/my-module/components/MyModuleComponent.vue'

      filePath: resolver.resolve('./components/MyModuleComponent.vue')

    })

  }

})


Lifecycle Hooks

Nuxt provides a powerful hooking system to expand almost every aspect using hooks.

Nuxt Configuration

Discover all the options you can use in your nuxt.config.ts file.
Layout · Nuxt Kit

Nuxt Kit
Layout
Source

Nuxt Kit provides a set of utilities to help you work with layouts.

Layouts is used to be a wrapper around your pages. It can be used to wrap your pages with common components, for example, a header and a footer. Layouts can be registered using addLayout utility.

addLayout

Register template as layout and add it to the layouts.

In Nuxt 2 error layout can also be registered using this utility. In Nuxt 3 error layout replaced with error.vue page in project root.
Type
function addLayout (layout: NuxtTemplate | string, name: string): void



interface NuxtTemplate {

  src?: string

  filename?: string

  dst?: string

  options?: Record<string, any>

  getContents?: (data: Record<string, any>) => string | Promise<string>

  write?: boolean

}

Parameters
layout

Type: NuxtTemplate | string

Required: true

A template object or a string with the path to the template. If a string is provided, it will be converted to a template object with src set to the string value. If a template object is provided, it must have the following properties:

src (optional)
Type: string
Path to the template. If src is not provided, getContents must be provided instead.
filename (optional)
Type: string
Filename of the template. If filename is not provided, it will be generated from the src path. In this case, the src option is required.
dst (optional)
Type: string
Path to the destination file. If dst is not provided, it will be generated from the filename path and nuxt buildDir option.
options (optional)
Type: Options
Options to pass to the template.
getContents (optional)
Type: (data: Options) => string | Promise<string>
A function that will be called with the options object. It should return a string or a promise that resolves to a string. If src is provided, this function will be ignored.
write (optional)
Type: boolean
If set to true, the template will be written to the destination file. Otherwise, the template will be used only in virtual filesystem.

Pages

Nuxt Kit provides a set of utilities to help you create and use pages. You can use these utilities to manipulate the pages configuration or to define route rules.

Plugins

Nuxt Kit provides a set of utilities to help you create and use plugins. You can add plugins or plugin templates to your module using these functions.
Logging · Nuxt Kit

Nuxt Kit
Logging
Source

Nuxt Kit provides a set of utilities to help you work with logging. These functions allow you to log messages with extra features.

Nuxt provides a logger instance that you can use to log messages with extra features. useLogger allows you to get a logger instance.

useLogger

Returns a logger instance. It uses consola under the hood.

Type
function useLogger (tag?: string, options?: Partial<ConsolaOptions>): ConsolaInstance

Parameters
tag

Type: string

*Optional: true

A tag to prefix all log messages with.

options

Type: Partial<ConsolaOptions>

*Optional: true

Consola configuration options

Examples
import { defineNuxtModule, useLogger } from '@nuxt/kit'



export default defineNuxtModule({

  setup(options, nuxt) {

    const logger = useLogger('my-module')



    logger.info('Hello from my module!')

  }

})

import { defineNuxtModule, useLogger } from '@nuxt/kit'



export default defineNuxtModule({

  setup(options, nuxt) {

    const logger = useLogger('my-module', { level: options.quiet ? 0 : 3 })



    logger.info('Hello from my module!')

  }

})


Resolving

Nuxt Kit provides a set of utilities to help you resolve paths. These functions allow you to resolve paths relative to the current module, with unknown name or extension.

Builder

Nuxt Kit provides a set of utilities to help you work with the builder. These functions allow you to extend the webpack and vite configurations.
Examples · Nuxt Kit

Nuxt Kit
Examples

Examples of Nuxt Kit utilities in use.

Accessing Nuxt Vite Config

If you are building an integration that needs access to the runtime Vite or webpack config that Nuxt uses, it is possible to extract this using Kit utilities.

Some examples of projects doing this already:

histoire
nuxt-vitest
@storybook-vue/nuxt

Here is a brief example of how you might access the Vite config from a project; you could implement a similar approach to get the webpack configuration.

import { loadNuxt, buildNuxt } from '@nuxt/kit'



// https://github.com/nuxt/nuxt/issues/14534

async function getViteConfig() {

  const nuxt = await loadNuxt({ cwd: process.cwd(), dev: false, overrides: { ssr: false } })

  return new Promise((resolve, reject) => {

    nuxt.hook('vite:extendConfig', (config, { isClient }) => {

      if (isClient) {

        resolve(config)

        throw new Error('_stop_')

      }

    })

    buildNuxt(nuxt).catch((err) => {

      if (!err.toString().includes('_stop_')) {

        reject(err)

      }

    })

  }).finally(() => nuxt.close())

}



const viteConfig = await getViteConfig()

console.log(viteConfig)


Builder

Nuxt Kit provides a set of utilities to help you work with the builder. These functions allow you to extend the webpack and vite configurations.

Lifecycle Hooks

Nuxt provides a powerful hooking system to expand almost every aspect using hooks.
Context · Nuxt Kit

Nuxt Kit
Context
Source

Nuxt Kit provides a set of utilities to help you work with context.

Nuxt modules allow you to enhance Nuxt's capabilities. They offer a structured way to keep your code organized and modular. If you're looking to break down your module into smaller components, Nuxt offers the useNuxt and tryUseNuxt functions. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as argument.

When you're working with the setup function in Nuxt modules, Nuxt is already provided as the second argument. This means you can directly utilize it without needing to call useNuxt(). You can look at Nuxt Site Config as an example of usage.
useNuxt

Get the Nuxt instance from the context. It will throw an error if Nuxt is not available.

Type
function useNuxt(): Nuxt



interface Nuxt {

  options: NuxtOptions

  hooks: Hookable<NuxtHooks>

  hook: Nuxt['hooks']['hook']

  callHook: Nuxt['hooks']['callHook']

  addHooks: Nuxt['hooks']['addHooks']

  ready: () => Promise<void>

  close: () => Promise<void>

  server?: any

  vfs: Record<string, string>

  apps: Record<string, NuxtApp>

}

Examples
setupTranspilation.ts
module.ts
// https://github.com/Lexpeartha/nuxt-xstate/blob/main/src/parts/transpile.ts

import { useNuxt } from '@nuxt/kit'



export const setupTranspilation = () => {

  const nuxt = useNuxt()



  nuxt.options.build.transpile = nuxt.options.build.transpile || []



  if (nuxt.options.builder === '@nuxt/webpack-builder') {

    nuxt.options.build.transpile.push(

      'xstate',

    )

  }

}

tryUseNuxt

Get the Nuxt instance from the context. It will return null if Nuxt is not available.

Type
function tryUseNuxt(): Nuxt | null



interface Nuxt {

  options: NuxtOptions

  hooks: Hookable<NuxtHooks>

  hook: Nuxt['hooks']['hook']

  callHook: Nuxt['hooks']['callHook']

  addHooks: Nuxt['hooks']['addHooks']

  ready: () => Promise<void>

  close: () => Promise<void>

  server?: any

  vfs: Record<string, string>

  apps: Record<string, NuxtApp>

}

Examples
requireSiteConfig.ts
module.ts
// https://github.com/harlan-zw/nuxt-site-config/blob/main/test/assertions.test.ts

import { tryUseNuxt } from '@nuxt/kit'



interface SiteConfig {

  title: string

}



export const requireSiteConfig = (): SiteConfig => {

  const nuxt = tryUseNuxt()

  if (!nuxt) {

    return { title: null }

  }

  return nuxt.options.siteConfig

}


Components

Nuxt Kit provides a set of utilities to help you work with components. You can register components globally or locally, and also add directories to be scanned for components.

Pages

Nuxt Kit provides a set of utilities to help you create and use pages. You can use these utilities to manipulate the pages configuration or to define route rules.
Programmatic Usage · Nuxt Kit

Nuxt Kit
Programmatic Usage
Source

Nuxt Kit provides a set of utilities to help you work with Nuxt programmatically. These functions allow you to load Nuxt, build Nuxt, and load Nuxt configuration.

Programmatic usage can be helpful when you want to use Nuxt programmatically, for example, when building a CLI tool or test utils.

loadNuxt

Load Nuxt programmatically. It will load the Nuxt configuration, instantiate and return the promise with Nuxt instance.

Type
async function loadNuxt (loadOptions?: LoadNuxtOptions): Promise<Nuxt>



interface LoadNuxtOptions extends LoadNuxtConfigOptions {

  dev?: boolean

  ready?: boolean

  rootDir?: string

  config?: LoadNuxtConfigOptions['overrides']

}

Parameters
loadOptions

Type: LoadNuxtOptions

Default: {}

Loading conditions for Nuxt. loadNuxt uses c12 under the hood, so it accepts the same options as c12.loadConfig with some additional options:

dev (optional)
Type: boolean
Default: false
If set to true, Nuxt will be loaded in development mode.
ready (optional)
Type: boolean
Default: true
If set to true, Nuxt will be ready to use after the loadNuxt call. If set to false, you will need to call nuxt.ready() to make sure Nuxt is ready to use.
rootDir (optional)
Type: string
Default: null
Deprecated: Use cwd option instead.
The root directory of the Nuxt project.
config (optional)
Type: LoadNuxtConfigOptions['overrides']
Default: {}
Deprecated: Use overrides option instead.
Overrides for the Nuxt configuration.
buildNuxt

Build Nuxt programmatically. It will invoke the builder (currently @nuxt/vite-builder or @nuxt/webpack-builder) to bundle the application.

Type
async function buildNuxt (nuxt: Nuxt): Promise<any>

Parameters
nuxt

Type: Nuxt

Required: true

Nuxt instance to build. It can be retrieved from the context via useNuxt() call.

loadNuxtConfig

Load Nuxt configuration. It will return the promise with the configuration object.

Type
async function loadNuxtConfig (options: LoadNuxtConfigOptions): Promise<NuxtOptions>

Parameters
options

Type: LoadNuxtConfigOptions

Required: true

Options to pass in c12 loadConfig call.

writeTypes

Generates tsconfig.json and writes it to the project buildDir.

Type
function writeTypes (nuxt?: Nuxt): void



interface Nuxt {

  options: NuxtOptions

  hooks: Hookable<NuxtHooks>

  hook: Nuxt['hooks']['hook']

  callHook: Nuxt['hooks']['callHook']

  addHooks: Nuxt['hooks']['addHooks']

  ready: () => Promise<void>

  close: () => Promise<void>

  server?: any

  vfs: Record<string, string>

  apps: Record<string, NuxtApp>

}

Parameters
nuxt

Type: Nuxt

Required: true

Nuxt instance to build. It can be retrieved from the context via useNuxt() call.

Modules

Nuxt Kit provides a set of utilities to help you create and use modules. You can use these utilities to create your own modules or to reuse existing modules.

Compatibility

Nuxt Kit provides a set of utilities to help you check the compatibility of your modules with different Nuxt versions.
nuxi typecheck · Nuxt Commands

Commands
nuxi typecheck
Source

The typecheck command runs vue-tsc to check types throughout your app.

Terminal
npx nuxi typecheck [--log-level] [rootDir]


The typecheck command runs vue-tsc to check types throughout your app.

Option	Default	Description
rootDir	.	The directory of the target application.
This command sets process.env.NODE_ENV to production. To override, define NODE_ENV in a .env file or as a command-line argument.
Read more on how to enable type-checking at build or development time.

nuxi preview

The preview command starts a server to preview your application after the build command.

nuxi upgrade

The upgrade command upgrades Nuxt 3 to the latest version.
nuxi upgrade · Nuxt Commands

Commands
nuxi upgrade
Source

The upgrade command upgrades Nuxt 3 to the latest version.

Terminal
npx nuxi upgrade [--force|-f]


The upgrade command upgrades Nuxt 3 to the latest version.

Option	Default	Description
--force, -f	false	Removes node_modules and lock files before upgrade.

nuxi typecheck

The typecheck command runs vue-tsc to check types throughout your app.

Modules

Nuxt Kit provides a set of utilities to help you create and use modules. You can use these utilities to create your own modules or to reuse existing modules.
nuxi preview · Nuxt Commands

Commands
nuxi preview
Source

The preview command starts a server to preview your application after the build command.

Terminal
npx nuxi preview [rootDir] [--dotenv]


The preview command starts a server to preview your Nuxt application after running the build command. The start command is an alias for preview. When running your application in production refer to the Deployment section.

Option	Default	Description
rootDir	.	The root directory of the application to preview.
--dotenv	.	Point to another .env file to load, relative to the root directory.

This command sets process.env.NODE_ENV to production. To override, define NODE_ENV in a .env file or as command-line argument.

For convenience, in preview mode, your .env file will be loaded into process.env. (However, in production you will need to ensure your environment variables are set yourself.)

nuxi prepare

The prepare command creates a .nuxt directory in your application and generates types.

nuxi typecheck

The typecheck command runs vue-tsc to check types throughout your app.
nuxi prepare · Nuxt Commands

Commands
nuxi prepare
Source

The prepare command creates a .nuxt directory in your application and generates types.

Terminal
npx nuxi prepare [--log-level] [rootDir]


The prepare command creates a .nuxt directory in your application and generates types. This can be useful in a CI environment or as a postinstall command in your package.json.

Option	Default	Description
rootDir	.	The root directory of the application to prepare.

nuxi init

The init command initializes a fresh Nuxt project.

nuxi preview

The preview command starts a server to preview your application after the build command.
nuxi info · Nuxt Commands

Commands
nuxi info
Source

The info command logs information about the current or specified Nuxt project.

Terminal
npx nuxi info [rootDir]


The info command logs information about the current or specified Nuxt project.

Option	Default	Description
rootDir	.	The directory of the target application.

nuxi generate

Pre-renders every route of the application and stores the result in plain HTML files.

nuxi init

The init command initializes a fresh Nuxt project.
nuxi devtools · Nuxt Commands

Commands
nuxi devtools
Source

The devtools command allows you to enable or disable Nuxt DevTools on a per-project basis.

Terminal
npx nuxi devtools enable|disable [rootDir]


Running nuxi devtools enable will install the Nuxt DevTools globally, and also enable it within the particular project you are using. It is saved as a preference in your user-level .nuxtrc. If you want to remove devtools support for a particular project, you can run nuxi devtools disable.

Option	Default	Description
rootDir	.	The root directory of the app you want to enable devtools for.
Read more about the Nuxt DevTools.

nuxi dev

The dev command starts a development server with hot module replacement at http://localhost:3000

nuxi generate

Pre-renders every route of the application and stores the result in plain HTML files.
nuxi generate · Nuxt Commands

Commands
nuxi generate
Source

Pre-renders every route of the application and stores the result in plain HTML files.

Terminal
npx nuxi generate [rootDir] [--dotenv]


The generate command pre-renders every route of your application and stores the result in plain HTML files that you can deploy on any static hosting services. The command triggers the nuxi build command with the prerender argument set to true

Option	Default	Description
rootDir	.	The root directory of the application to generate
--dotenv	.	Point to another .env file to load, relative to the root directory.
Read more about pre-rendering and static hosting.

nuxi devtools

The devtools command allows you to enable or disable Nuxt DevTools on a per-project basis.

nuxi info

The info command logs information about the current or specified Nuxt project.
nuxi init · Nuxt Commands

Commands
nuxi init
Source

The init command initializes a fresh Nuxt project.

Terminal
npx nuxi init|create [--verbose|-v] [--template,-t] [dir]


The init command initializes a fresh Nuxt project using unjs/giget.

Options
Option	Default	Description
--template, -t	v3	Specify template name or git repository to use as a template. Format is gh:org/name to use a custom github template.
--force	false	Force clone to any existing directory.
--offline	false	Do not attempt to download from github and only use local cache.
--prefer-offline	false	Try local cache first to download templates.
--shell	false	Open shell in cloned directory (experimental).
Environment variables
NUXI_INIT_REGISTRY: Set to a custom template registry. (learn more).
Default registry is loaded from nuxt/starter/templates

nuxi info

The info command logs information about the current or specified Nuxt project.

nuxi prepare

The prepare command creates a .nuxt directory in your application and generates types.
updateAppConfig · Nuxt Utils

Utils
updateAppConfig
Source

Update the App Config at runtime.

Updates the app.config using deep assignment. Existing (nested) properties will be preserved.
Usage
const appConfig = useAppConfig() // { foo: 'bar' }



const newAppConfig = { foo: 'baz' }



updateAppConfig(newAppConfig)



console.log(appConfig) // { foo: 'baz' }

 Read more in Docs > Guide > Directory Structure > App Config.

showError

Nuxt provides a quick and simple way to show a full screen error page if needed.

nuxi add

Scaffold an entity into your Nuxt application.
nuxi build-module · Nuxt Commands

Commands
nuxi build-module
Source

Nuxt command to build your Nuxt module before publishing.

Terminal
npx nuxi build-module [--stub] [rootDir]


The build-module command runs @nuxt/module-builder to generate dist directory within your rootDir that contains the full build for your nuxt-module.

Option	Default	Description
rootDir	.	The root directory of the module to bundle.
--stub	false	Stub out your module for development using jiti. (note: This is mainly for development purposes.)
Read more about @nuxt/module-builder.

nuxi analyze

Analyze the production bundle or your Nuxt application.

nuxi build

Build your Nuxt application.
nuxi build · Nuxt Commands

Commands
nuxi build
Source

Build your Nuxt application.

Terminal
npx nuxi build [--prerender] [--dotenv] [--log-level] [rootDir]


The build command creates a .output directory with all your application, server and dependencies ready for production.

Option	Default	Description
rootDir	.	The root directory of the application to bundle.
--prerender	false	Pre-render every route of your application. (note: This is an experimental flag. The behavior might be changed.)
--dotenv	.	Point to another .env file to load, relative to the root directory.
This command sets process.env.NODE_ENV to production.

nuxi build-module

Nuxt command to build your Nuxt module before publishing.

nuxi cleanup

Remove common generated Nuxt files and caches.
setResponseStatus · Nuxt Utils

Utils
setResponseStatus
Source

setResponseStatus sets the statusCode (and optionally the statusMessage) of the response.

Nuxt provides composables and utilities for first-class server-side-rendering support.

setResponseStatus sets the statusCode (and optionally the statusMessage) of the response.

const event = useRequestEvent()



// Set the status code to 404 for a custom 404 page

setResponseStatus(event, 404)



// Set the status message as well

setResponseStatus(event, 404, 'Page Not Found')

In the browser, setResponseStatus will have no effect.
 Read more in Docs > Getting Started > Error Handling.

setPageLayout

setPageLayout allows you to dynamically change the layout of a page.

showError

Nuxt provides a quick and simple way to show a full screen error page if needed.
nuxi cleanup · Nuxt Commands

Commands
nuxi cleanup
Source

Remove common generated Nuxt files and caches.

Terminal
npx nuxi clean|cleanup [rootDir]


The cleanup command removes common generated Nuxt files and caches, including:

.nuxt
.output
node_modules/.vite
node_modules/.cache
Option	Default	Description
rootDir	.	The root directory of the project.

nuxi build

Build your Nuxt application.

nuxi dev

The dev command starts a development server with hot module replacement at http://localhost:3000
nuxi analyze · Nuxt Commands

Commands
nuxi analyze
Source

Analyze the production bundle or your Nuxt application.

Terminal
npx nuxi analyze [--log-level] [rootDir]


The analyze command builds Nuxt and analyzes the production bundle (experimental).

Option	Default	Description
rootDir	.	The directory of the target application.
This command sets process.env.NODE_ENV to production.

nuxi add

Scaffold an entity into your Nuxt application.

nuxi build-module

Nuxt command to build your Nuxt module before publishing.
nuxi add · Nuxt Commands

Commands
nuxi add
Source

Scaffold an entity into your Nuxt application.

Terminal
npx nuxi add [--cwd] [--force] <TEMPLATE> <NAME>

Option	Default	Description
TEMPLATE	-	Specify a template of the file to be generated.
NAME	-	Specify a name of the file that will be created.
--cwd	.	The directory of the target application.
--force	false	Force override file if it already exists.

Modifiers:

Some templates support additional modifier flags to add a suffix (like .client or .get) to their name.

Terminal
# Generates `/plugins/sockets.client.ts`

npx nuxi add plugin sockets --client

nuxi add component
Modifier flags: --mode client|server or --client or --server
Terminal
# Generates `components/TheHeader.vue`

npx nuxi add component TheHeader

nuxi add composable
Terminal
# Generates `composables/foo.ts`

npx nuxi add composable foo

nuxi add layout
Terminal
# Generates `layouts/custom.vue`

npx nuxi add layout custom

nuxi add plugin
Modifier flags: --mode client|server or --clientor --server
Terminal
# Generates `plugins/analytics.ts`

npx nuxi add plugin analytics

nuxi add page
Terminal
# Generates `pages/about.vue`

npx nuxi add page about

Terminal
# Generates `pages/category/[id].vue`

npx nuxi add page "category/[id]"

nuxi add middleware
Modifier flags: --global
Terminal
# Generates `middleware/auth.ts`

npx nuxi add middleware auth

nuxi add api
Modifier flags: --method (can accept connect, delete, get, head, options, patch, post, put or trace) or alternatively you can directly use --get, --post, etc.
Terminal
# Generates `server/api/hello.ts`

npx nuxi add api hello


updateAppConfig

Update the App Config at runtime.

nuxi analyze

Analyze the production bundle or your Nuxt application.
showError · Nuxt Utils

Utils
showError
Source

Nuxt provides a quick and simple way to show a full screen error page if needed.

Within your pages, components and plugins you can use showError to show an error.

Parameters:

error: string | Error | Partial<{ cause, data, message, name, stack, statusCode, statusMessage }>
showError("😱 Oh no, an error has been thrown.")

showError({

  statusCode: 404,

  statusMessage: "Page Not Found"

})


The error is set in the state using useError() to create a reactive and SSR-friendly shared error state across components.

showError calls the app:error hook.
 Read more in Docs > Getting Started > Error Handling.

setResponseStatus

setResponseStatus sets the statusCode (and optionally the statusMessage) of the response.

updateAppConfig

Update the App Config at runtime.
setPageLayout · Nuxt Utils

Utils
setPageLayout
Source

setPageLayout allows you to dynamically change the layout of a page.

setPageLayout relies on access to the Nuxt context and can only be called within components' setup functions, plugins, and route middleware.
middleware/custom-layout.ts
export default defineNuxtRouteMiddleware((to) => {

  // Set the layout on the route you are navigating _to_

  setPageLayout('other')

})

If you choose to set the layout dynamically on the server side, you must do so before the layout is rendered by Vue (that is, within a plugin or route middleware) to avoid a hydration mismatch.

reloadNuxtApp

reloadNuxtApp will perform a hard reload of the page.

setResponseStatus

setResponseStatus sets the statusCode (and optionally the statusMessage) of the response.
reloadNuxtApp · Nuxt Utils

Utils
reloadNuxtApp
Source

reloadNuxtApp will perform a hard reload of the page.

reloadNuxtApp will perform a hard reload of your app, re-requesting a page and its dependencies from the server.

By default, it will also save the current state of your app (that is, any state you could access with useState).

You can enable experimental restoration of this state by enabling the experimental.restoreState option in your nuxt.config file.
Type
reloadNuxtApp(options?: ReloadNuxtAppOptions)



interface ReloadNuxtAppOptions {

  ttl?: number

  force?: boolean

  path?: string

  persistState?: boolean

}

options (optional)

Type: ReloadNuxtAppOptions

An object accepting the following properties:

path (optional)
Type: string
Default: window.location.pathname
The path to reload (defaulting to the current path). If this is different from the current window location it will trigger a navigation and add an entry in the browser history.
ttl (optional)
Type: number
Default: 10000
The number of milliseconds in which to ignore future reload requests. If called again within this time period, reloadNuxtApp will not reload your app to avoid reload loops.
force (optional)
Type: boolean
Default: false
This option allows bypassing reload loop protection entirely, forcing a reload even if one has occurred within the previously specified TTL.
persistState (optional)
Type: boolean
Default: false
Whether to dump the current Nuxt state to sessionStorage (as nuxt:reload:state). By default this will have no effect on reload unless experimental.restoreState is also set, or unless you handle restoring the state yourself.

refreshNuxtData

refreshNuxtData refetches all data from the server and updates the page.

setPageLayout

setPageLayout allows you to dynamically change the layout of a page.
prefetchComponents · Nuxt Utils

Utils
prefetchComponents
Source

Nuxt provides utilities to give you control over prefetching components.

Prefetching component downloads the code in the background, this is based on the assumption that the component will likely be used for rendering, enabling the component to load instantly if and when the user requests it. The component is downloaded and cached for anticipated future use without the user making an explicit request for it.

Use prefetchComponents to manually prefetch individual components that have been registered globally in your Nuxt app. By default Nuxt registers these as async components. You must use the Pascal-cased version of the component name.

await prefetchComponents('MyGlobalComponent')



await prefetchComponents(['MyGlobalComponent1', 'MyGlobalComponent2'])

Current implementation behaves exactly the same as preloadComponents by preloading components instead of just prefetching we are working to improve this behavior.
On server, prefetchComponents will have no effect.

onNuxtReady

The onNuxtReady composable allows running a callback after your app has finished initializing.

preloadComponents

Nuxt provides utilities to give you control over preloading components.
refreshNuxtData · Nuxt Utils

Utils
refreshNuxtData
Source

refreshNuxtData refetches all data from the server and updates the page.

refreshNuxtData re-fetches all data from the server and updates the page as well as invalidates the cache of useAsyncData , useLazyAsyncData, useFetch and useLazyFetch.
Type
refreshNuxtData(keys?: string | string[])


Parameters:

keys:
Type: String | String[]
refreshNuxtData accepts a single or an array of strings as keys that are used to fetch the data. This parameter is optional. All useAsyncData and useFetch are re-fetched when no keys are specified.
Refresh All Data

This example below refreshes all data being fetched using useAsyncData and useFetch on the current page.

pages/some-page.vue
<script setup lang="ts">

const refreshing = ref(false)

const refreshAll = async () => {

  refreshing.value = true

  try {

    await refreshNuxtData()

  } finally {

    refreshing.value = false

  }

}

</script>



<template>

  <div>

    <button :disabled="refreshing" @click="refreshAll">

      Refetch All Data

    </button>

  </div>

</template>

Refresh Specific Data

This example below refreshes only data where the key matches to count.

pages/some-page.vue
<script setup lang="ts">

const { pending, data: count } = await useLazyAsyncData('count', () => $fetch('/api/count'))

const refresh = () => refreshNuxtData('count')

</script>



<template>

  <div>

    {{ pending ? 'Loading' : count }}

  </div>

  <button @click="refresh">Refresh</button>

</template>

 Read more in Docs > Getting Started > Data Fetching.

prerenderRoutes

prerenderRoutes hints to Nitro to prerender an additional route.

reloadNuxtApp

reloadNuxtApp will perform a hard reload of the page.
prerenderRoutes · Nuxt Utils

Utils
prerenderRoutes
Source

prerenderRoutes hints to Nitro to prerender an additional route.

When prerendering, you can hint to Nitro to prerender additional paths, even if their URLs do not show up in the HTML of the generated page.

const route = useRoute()



prerenderRoutes('/')

prerenderRoutes(['/', '/about'])

In the browser, or if called outside prerendering, prerenderRoutes will have no effect.

preloadRouteComponents

preloadRouteComponents allows you to manually preload individual pages in your Nuxt app.

refreshNuxtData

refreshNuxtData refetches all data from the server and updates the page.
preloadRouteComponents · Nuxt Utils

Utils
preloadRouteComponents
Source

preloadRouteComponents allows you to manually preload individual pages in your Nuxt app.

Preloading routes loads the components of a given route that the user might navigate to in future. This ensures that the components are available earlier and less likely to block the navigation, improving performance.

Nuxt already automatically preloads the necessary routes if you're using the NuxtLink component.
 Read more in Docs > API > Components > Nuxt Link.
Example

Preload a route when using navigateTo.

// we don't await this async function, to avoid blocking rendering

// this component's setup function

preloadRouteComponents('/dashboard')



const submit = async () => {

  const results = await $fetch('/api/authentication')



  if (results.token) {

    await navigateTo('/dashboard')

  }

}

 Read more in Docs > API > Utils > Navigate To.
On server, preloadRouteComponents will have no effect.

preloadComponents

Nuxt provides utilities to give you control over preloading components.

prerenderRoutes

prerenderRoutes hints to Nitro to prerender an additional route.
onNuxtReady · Nuxt Utils

Utils
onNuxtReady
Source

The onNuxtReady composable allows running a callback after your app has finished initializing.

onNuxtReady only runs on the client-side.
It is ideal for running code that should not block the initial rendering of your app.
plugins/ready.client.ts
export default defineNuxtPlugin(() => {

  onNuxtReady(async () => {

    const myAnalyticsLibrary = await import('my-big-analytics-library')

    // do something with myAnalyticsLibrary

  })

})


It is 'safe' to run even after your app has initialized. In this case, then the code will be registered to run in the next idle callback.

onBeforeRouteUpdate

The onBeforeRouteUpdate composable allows registering a route guard within a component.

prefetchComponents

Nuxt provides utilities to give you control over prefetching components.
preloadComponents · Nuxt Utils

Utils
preloadComponents
Source

Nuxt provides utilities to give you control over preloading components.

Preloading components loads components that your page will need very soon, which you want to start loading early in rendering lifecycle. This ensures they are available earlier and are less likely to block the page's render, improving performance.

Use preloadComponents to manually preload individual components that have been registered globally in your Nuxt app. By default Nuxt registers these as async components. You must use the Pascal-cased version of the component name.

await preloadComponents('MyGlobalComponent')



await preloadComponents(['MyGlobalComponent1', 'MyGlobalComponent2'])

On server, preloadComponents will have no effect.

prefetchComponents

Nuxt provides utilities to give you control over prefetching components.

preloadRouteComponents

preloadRouteComponents allows you to manually preload individual pages in your Nuxt app.
onBeforeRouteLeave · Nuxt Utils

Utils
onBeforeRouteLeave
Source

The onBeforeRouteLeave composable allows registering a route guard within a component.

 Read more in Vue Router Docs.

navigateTo

navigateTo is a helper function that programmatically navigates users.

onBeforeRouteUpdate

The onBeforeRouteUpdate composable allows registering a route guard within a component.
onBeforeRouteUpdate · Nuxt Utils

Utils
onBeforeRouteUpdate
Source

The onBeforeRouteUpdate composable allows registering a route guard within a component.

 Read more in Vue Router Docs.

onBeforeRouteLeave

The onBeforeRouteLeave composable allows registering a route guard within a component.

onNuxtReady

The onNuxtReady composable allows running a callback after your app has finished initializing.
defineRouteRules · Nuxt Utils

Utils
defineRouteRules
Source

Define route rules for hybrid rendering at the page level.

This feature is experimental and in order to use it you must enable the experimental.inlineRouteRules option in your nuxt.config.
Usage
pages/index.vue
<script setup>

defineRouteRules({

  prerender: true

})

</script>



<template>

  <h1>Hello world!</h1>

</template>


Will be translated to:

nuxt.config.ts
export default defineNuxtConfig({

  routeRules: {

    '/': { prerender: true }

  }

})

When running nuxt build, the home page will be pre-rendered in .output/public/index.html and statically served.
Notes
A rule defined in ~/pages/foo/bar.vue will be applied to /foo/bar requests.
A rule in ~/pages/foo/[id].vue will be applied to /foo/** requests.

For more control, such as if you are using a custom path or alias set in the page's definePageMeta, you should set routeRules directly within your nuxt.config.

Read more about the routeRules.

definePageMeta

Define metadata for your page components.

navigateTo

navigateTo is a helper function that programmatically navigates users.
addRouteMiddleware · Nuxt Utils

Utils
addRouteMiddleware
Source

addRouteMiddleware() is a helper function to dynamically add middleware in your application.

Route middleware are navigation guards stored in the middleware/ directory of your Nuxt application (unless set otherwise).
Type
addRouteMiddleware (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {})

Parameters
name
Type: string | RouteMiddleware

Can be either a string or a function of type RouteMiddleware. Function takes the next route to as the first argument and the current route from as the second argument, both of which are Vue route objects.

Learn more about available properties of route objects.

middleware
Type: RouteMiddleware

The second argument is a function of type RouteMiddleware. Same as above, it provides to and from route objects. It becomes optional if the first argument in addRouteMiddleware() is already passed as a function.

options
Type: AddRouteMiddlewareOptions

An optional options argument lets you set the value of global to true to indicate whether the router middleware is global or not (set to false by default).

Examples
Anonymous Route Middleware

Anonymous route middleware does not have a name. It takes a function as the first argument, making the second middleware argument redundant:

plugins/my-plugin.ts
export default defineNuxtPlugin(() => {

  addRouteMiddleware((to, from) => {

    if (to.path === '/forbidden') {

      return false

    }

  })

})

Named Route Middleware

Named route middleware takes a string as the first argument and a function as the second.

When defined in a plugin, it overrides any existing middleware of the same name located in the middleware/ directory:

plugins/my-plugin.ts
export default defineNuxtPlugin(() => {

  addRouteMiddleware('named-middleware', () => {

    console.log('named middleware added in Nuxt plugin')

  })

})

Global Route Middleware

Set an optional, third argument { global: true } to indicate whether the route middleware is global:

plugins/my-plugin.ts
export default defineNuxtPlugin(() => {

  addRouteMiddleware('global-middleware', (to, from) => {

      console.log('global middleware that runs on every route change')

    },

    { global: true }

  )

})


abortNavigation

abortNavigation is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.

clearError

The clearError composable clears all handled errors.
abortNavigation · Nuxt Utils

Utils
abortNavigation
Source

abortNavigation is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.

abortNavigation is only usable inside a route middleware handler.
Type
abortNavigation(err?: Error | string): false

Parameters
err
Type: Error | string
Optional error to be thrown by abortNavigation.
Examples

The example below shows how you can use abortNavigation in a route middleware to prevent unauthorized route access:

middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {

  const user = useState('user')



  if (!user.value.isAuthorized) {

    return abortNavigation()

  }

 

  if (to.path !== '/edit-post') {

    return navigateTo('/edit-post')

  }

})

err as a String

You can pass the error as a string:

middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {

  const user = useState('user')



  if (!user.value.isAuthorized) {

    return abortNavigation('Insufficient permissions.')

  }

})

err as an Error Object

You can pass the error as an Error object, e.g. caught by the catch-block:

middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {

  try {

    /* code that might throw an error */

  } catch (err) {

    return abortNavigation(err)

  }

})


$fetch

Nuxt uses ofetch to expose globally the $fetch helper for making HTTP requests.

addRouteMiddleware

addRouteMiddleware() is a helper function to dynamically add middleware in your application.
useState · Nuxt Composables

Composables
useState
Source

The useState composable creates a reactive and SSR-friendly shared state.

Usage
// Create a reactive state and set default value

const count = useState('counter', () => Math.round(Math.random() * 100))

 Read more in Docs > Getting Started > State Management.
Because the data inside useState will be serialized to JSON, it is important that it does not contain anything that cannot be serialized, such as classes, functions or symbols.
useState is a reserved function name transformed by the compiler, so you should not name your own function useState.
Using shallowRef

If you don't need your state to be deeply reactive, you can combine useState with shallowRef. This can improve performance when your state contains large objects and arrays.

const state = useState('my-shallow-state', () => shallowRef({ deep: 'not reactive' }))

// isShallow(state) === true

Type
useState<T>(init?: () => T | Ref<T>): Ref<T>

useState<T>(key: string, init?: () => T | Ref<T>): Ref<T>

key: A unique key ensuring that data fetching is properly de-duplicated across requests. If you do not provide a key, then a key that is unique to the file and line number of the instance of useState will be generated for you.
init: A function that provides initial value for the state when not initiated. This function can also return a Ref.
T: (typescript only) Specify the type of state

useServerSeoMeta

The useServerSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support.

$fetch

Nuxt uses ofetch to expose globally the $fetch helper for making HTTP requests.
useRequestURL · Nuxt Composables

Composables
useRequestURL
Source

Access the incoming request URL with the useRequestURL composable.

useRequestURL is a helper function that returns an URL object working on both server-side and client-side.

pages/about.vue
Result in development
<script setup lang="ts">

const url = useRequestURL()

</script>



<template>

  <p>URL is: {{ url }}</p>

  <p>Path is: {{ url.pathname }}</p>

</template>

Read about the URL instance properties on the MDN documentation.

useRequestHeaders

Use useRequestHeaders to access the incoming request headers.

useRoute

The useRoute composable returns the current route.
useRoute · Nuxt Composables

Composables
useRoute
Source

The useRoute composable returns the current route.

Within the template of a Vue component, you can access the route using $route.
Example

In the following example, we call an API via useFetch using a dynamic page parameter - slug - as part of the URL.

~/pages/[slug].vue
<script setup lang="ts">

const route = useRoute()

const { data: mountain } = await useFetch(`/api/mountains/${route.params.slug}`)

</script>



<template>

  <div>

    <h1>{{ mountain.title }}</h1>

    <p>{{ mountain.description }}</p>

  </div>

</template>


If you need to access the route query parameters (for example example in the path /test?example=true), then you can use useRoute().query instead of useRoute().params.

API

Apart from dynamic parameters and query parameters, useRoute() also provides the following computed references related to the current route:

fullPath: encoded URL associated with the current route that contains path, query and hash
hash: decoded hash section of the URL that starts with a #
matched: array of normalized matched routes with current route location
meta: custom data attached to the record
name: unique name for the route record
path: encoded pathname section of the URL
redirectedFrom: route location that was attempted to access before ending up on the current route location
 Read more in https://router.vuejs.org/api/interfaces/RouteLocationNormalizedLoaded.html.

useRequestURL

Access the incoming request URL with the useRequestURL composable.

useRouter

The useRouter composable returns the router instance.