matijao/webdev huggingface dataset:
$fetch · Nuxt Utils

Utils
$fetch
Source

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

Nuxt uses ofetch to expose globally the $fetch helper for making HTTP requests within your Vue app or API routes.

During server-side rendering, calling $fetch to fetch your internal API routes will directly call the relevant function (emulating the request), saving an additional API call.
Using $fetch in components without wrapping it with useAsyncData causes fetching the data twice: initially on the server, then again on the client-side during hydration, because $fetch does not transfer state from the server to the client. Thus, the fetch will be executed on both sides because the client has to get the data again.

We recommend to use useFetch or useAsyncData + $fetch to prevent double data fetching when fetching the component data.

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

// During SSR data is fetched twice, once on the server and once on the client.

const dataTwice = await $fetch('/api/item')



// During SSR data is fetched only on the server side and transferred to the client.

const { data } = await useAsyncData('item', () => $fetch('/api/item'))



// You can also useFetch as shortcut of useAsyncData + $fetch

const { data } = await useFetch('/api/item')

</script>

 Read more in Docs > Getting Started > Data Fetching.

You can use $fetch for any method that are executed only on client-side.

pages/contact.vue
<script setup lang="ts">

function contactForm() {

  $fetch('/api/contact', {

    method: 'POST',

    body: { hello: 'world '}

  })

}

</script>



<template>

  <button @click="contactForm">Contact</button>

</template>

$fetch is the preferred way to make HTTP calls in Nuxt instead of @nuxt/http and @nuxtjs/axios that are made for Nuxt 2.

useState

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

abortNavigation

abortNavigation is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.
Migrate to Nuxt Bridge: Overview

Upgrade Guide
Migrate to Nuxt Bridge
Overview

Reduce the differences with Nuxt 3 and reduce the burden of migration to Nuxt 3.

If you're starting a fresh Nuxt 3 project, please skip this section and go to Nuxt 3 Installation.
Nuxt Bridge provides identical features to Nuxt 3 (docs) but there are some limitations, notably that useAsyncData and useFetch composables are not available. Please read the rest of this page for details.

Bridge is a forward-compatibility layer that allows you to experience many of the new Nuxt 3 features by simply installing and enabling a Nuxt module.

Using Nuxt Bridge, you can make sure your project is (almost) ready for Nuxt 3 and you can gradually proceed with the transition to Nuxt 3.

First Step
Upgrade Nuxt 2

Make sure your dev server (nuxt dev) isn't running, remove any package lock files (package-lock.json and yarn.lock), and install the latest Nuxt 2 version:

package.json
- "nuxt": "^2.16.3"

+ "nuxt": "^2.17.0"


Then, reinstall your dependencies:

yarn
npm
yarn install

Once the installation is complete, make sure both development and production builds are working as expected before proceeding.
Install Nuxt Bridge

Install @nuxt/bridge-edge as a development dependency:

Yarn
npm
yarn add --dev @nuxt/bridge@npm:@nuxt/bridge-edge

Update nuxt.config

Please make sure to avoid any CommonJS syntax such as module.exports, require or require.resolve in your config file. It will soon be deprecated and unsupported.

You can use static import, dynamic import() and export default instead. Using TypeScript by renaming to nuxt.config.ts is also possible and recommended.

nuxt.config.ts
import { defineNuxtConfig } from '@nuxt/bridge'



export default defineNuxtConfig({

  bridge: false

})

Update Commands

The nuxt command should now be changed to the nuxt2 command.

{

  "scripts": {

-   "dev": "nuxt",

+   "dev": "nuxt2",

-   "build": "nuxt build",

+   "build": "nuxt2 build",

-   "start": "nuxt start",

+   "start": "nuxt2 start"

  }

}


Try running nuxt2 once here. You will see that the application works as before.

(If 'bridge' is set to false, your application will operate without any changes as before.)

Upgrade Steps

With Nuxt Bridge, the migration to Nuxt 3 can proceed in steps. The below Upgrade Steps does not need to be done all at once.

TypeScript
Migrate Legacy Composition API
Plugins and Middleware
Migrate New Composition API
Meta Tags
Runtime Config
Nitro
Vite
Migrate from CommonJS to ESM

Nuxt 3 natively supports TypeScript and ECMAScript Modules. Please check Native ES Modules for more info and upgrading.

Releases

Discover the latest releases of Nuxt & Nuxt official modules.

TypeScript

Learn how to use TypeScript with Nuxt Bridge.
useServerSeoMeta · Nuxt Composables

Composables
useServerSeoMeta
Source

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

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

 Read more in Docs > API > Composables > Use Seo Meta.

In most instances, the meta doesn't need to be reactive as robots will only scan the initial load. So we recommend using useServerSeoMeta as a performance-focused utility that will not do anything (or return a head object) on the client.

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

useServerSeoMeta({

  robots: 'index, follow'

})

</script>


Parameters are exactly the same as with useSeoMeta

 Read more in Docs > Getting Started > Seo Meta.

useSeoMeta

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

useState

The useState composable creates a reactive and SSR-friendly shared state.
Migrate to Nuxt Bridge: Configuration

Upgrade Guide
Migrate to Nuxt Bridge
Configuration

Learn how to configure Nuxt Bridge to your own needs.

Feature Flags

You can optionally disable some features from bridge or opt-in to less stable ones. In normal circumstances, it is always best to stick with defaults!

You can check bridge/src/module.ts for latest defaults.

nuxt.config.ts
import { defineNuxtConfig } from '@nuxt/bridge'

export default defineNuxtConfig({

  bridge: {



    // -- Opt-in features --



    // Use Vite as the bundler instead of webpack 4

    // vite: true,



    // Enable Nuxt 3 compatible useHead

    // meta: true,



    // -- Default features --



    // Use legacy server instead of Nitro

    // nitro: false,



    // Disable Nuxt 3 compatible `nuxtApp` interface

    // app: false,



    // Disable Composition API support

    // capi: false,



    // ... or just disable legacy Composition API support

    // capi: {

    //   legacy: false

    // },



    // Do not transpile modules

    // transpile: false,



    // Disable <script setup> support

    // scriptSetup: false,



    // Disable composables auto importing

    // imports: false,



    // Do not warn about module incompatibilities

    // constraints: false

  },



  vite: {

    // Config for Vite

  }

})

Migration of each option
router.base
export default defineNuxtConfig({

- router: {

-   base: '/my-app/'

- }

+ app: {

+   baseURL: '/my-app/'

+ }

})

build.publicPath
export default defineNuxtConfig({

- build: {

-   publicPath: 'https://my-cdn.net'

- }

+ app: {

+   cdnURL: 'https://my-cdn.net'

+ }

})


Vite

Activate Vite to your Nuxt 2 application with Nuxt Bridge.

Overview

Nuxt 3 is a complete rewrite of Nuxt 2, and also based on a new set of underlying technologies.
Migrate to Nuxt Bridge: Vite

Upgrade Guide
Migrate to Nuxt Bridge
Vite

Activate Vite to your Nuxt 2 application with Nuxt Bridge.

When using vite, nitro must have been configured.
Remove Modules
Remove nuxt-vite: Bridge enables same functionality
Update Config
nuxt.config.ts
import { defineNuxtConfig } from '@nuxt/bridge'



export default defineNuxtConfig({

  bridge: {

    vite: true,

    nitro: true

  }

})

Configuration
nuxt.config.ts
import { defineNuxtConfig } from '@nuxt/bridge'



export default defineNuxtConfig({

  vite: {

    // Config for Vite

  }

})


Nitro

Activate Nitro to your Nuxt 2 application with Nuxt Bridge.

Configuration

Learn how to configure Nuxt Bridge to your own needs.
Migrate to Nuxt Bridge: Runtime Config

Upgrade Guide
Migrate to Nuxt Bridge
Runtime Config

Nuxt provides a runtime config API to expose configuration and secrets within your application.

When using runtimeConfig option, nitro must have been configured.
Update Runtime Config

Nuxt 3 approaches runtime config differently than Nuxt 2, using a new combined runtimeConfig option.

First, you'll need to combine your publicRuntimeConfig and privateRuntimeConfig properties into a new one called runtimeConfig, with the public config within a key called public.

// nuxt.config.js

- privateRuntimeConfig: {

-   apiKey: process.env.NUXT_API_KEY || 'super-secret-key'

- },

- publicRuntimeConfig: {

-   websiteURL: 'https://public-data.com'

- }

+ runtimeConfig: {

+   apiKey: process.env.NUXT_API_KEY || 'super-secret-key',

+   public: {

+     websiteURL: 'https://public-data.com'

+   }

+ }


This also means that when you need to access public runtime config, it's behind a property called public. If you use public runtime config, you'll need to update your code.

// MyWidget.vue

- <div>Website: {{ $config.websiteURL }}</div>

+ <div>Website: {{ $config.public.websiteURL }}</div>


Meta Tags

Learn how to migrate from Nuxt 2 to Nuxt Bridge new meta tags.

Nitro

Activate Nitro to your Nuxt 2 application with Nuxt Bridge.
Migrate to Nuxt Bridge: Meta Tags

Upgrade Guide
Migrate to Nuxt Bridge
Meta Tags

Learn how to migrate from Nuxt 2 to Nuxt Bridge new meta tags.

If you need to access the component state with head, you should migrate to using useHead .

If you need to use the Options API, there is a head() method you can use when you use defineNuxtComponent.

Migration
Set bridge.meta
import { defineNuxtConfig } from '@nuxt/bridge'

export default defineNuxtConfig({

  bridge: {

    meta: true,

    nitro: false // If migration to Nitro is complete, set to true

  }

})

Update head properties

In your nuxt.config, rename head to meta. (Note that objects no longer have a hid key for deduplication.)

Nuxt 2
Nuxt 3
export default {

  head: {

    titleTemplate: '%s - Nuxt',

    meta: [

      { charset: 'utf-8' },

      { name: 'viewport', content: 'width=device-width, initial-scale=1' },

      { hid: 'description', name: 'description', content: 'Meta description' }

    ]

  }

}

useHead Composables

Nuxt Bridge provides a new Nuxt 3 meta API that can be accessed with a new useHead composable.

<script setup lang="ts">

useHead({

  title: 'My Nuxt App',

})

</script>

This useHead composable uses @unhead/vue under the hood (rather than vue-meta) to manipulate your <head>.
We recommend not using the native Nuxt 2 head() properties in addition to useHead , as they may conflict.

For more information on how to use this composable, see the docs.

Options API
<script>

// if using options API `head` method you must use `defineNuxtComponent`

export default defineNuxtComponent({

  head (nuxtApp) {

    // `head` receives the nuxt app but cannot access the component instance

    return {

      meta: [{

        name: 'description',

        content: 'This is my page description.'

      }]

    }

  }

})

</script>

Title Template

If you want to use a function (for full control), then this cannot be set in your nuxt.config, and it is recommended instead to set it within your /layouts directory.

layouts/default.vue
<script setup lang="ts">

useHead({

  titleTemplate: (titleChunk) => {

    return titleChunk ? `${titleChunk} - Site Title` : 'Site Title';

  }

})

</script>


New Composition API

Nuxt Bridge implements composables compatible with Nuxt 3.

Runtime Config

Nuxt provides a runtime config API to expose configuration and secrets within your application.
Migrate to Nuxt Bridge: Nitro

Upgrade Guide
Migrate to Nuxt Bridge
Nitro

Activate Nitro to your Nuxt 2 application with Nuxt Bridge.

Remove Modules
Remove @nuxt/nitro: Bridge injects same functionality
Update Config
nuxt.config.ts
import { defineNuxtConfig } from '@nuxt/bridge'



export default defineNuxtConfig({

  bridge: {

    nitro: true

  }

})

Update Your Scripts

You will also need to update your scripts within your package.json to reflect the fact that Nuxt will now produce a Nitro server as build output.

Install Nuxi

Install nuxi as a development dependency:

yarn
npm
yarn add --dev nuxi

Nuxi

Nuxt 3 introduced the new Nuxt CLI command nuxi. Update your scripts as follows to leverage the better support from Nuxt Bridge:

{

  "scripts": {

-   "dev": "nuxt",

+   "dev": "nuxi dev",

-   "build": "nuxt build",

+   "build": "nuxi build",

-   "start": "nuxt start",

+   "start": "nuxi preview"

  }

}

If nitro: false, use the nuxt2 command.
Static Target

If you have set target: 'static' in your nuxt.config then you need to ensure that you update your build script to be nuxi generate.

package.json
{

  "scripts": {

    "build": "nuxi generate"

  }

}

Server Target

For all other situations, you can use the nuxi build command.

package.json
{

  "scripts": {

    "build": "nuxi build",

    "start": "nuxi preview"

  }

}

Exclude Built Nitro Folder From Git

Add the folder .output to the .gitignore file.

Ensure Everything Goes Well

✔️ Try with nuxi dev and nuxi build (or nuxi generate) to see if everything goes well.

Runtime Config

Nuxt provides a runtime config API to expose configuration and secrets within your application.

Vite

Activate Vite to your Nuxt 2 application with Nuxt Bridge.
defineNuxtComponent · Nuxt Utils

Utils
defineNuxtComponent
Source

defineNuxtComponent() is a helper function for defining type safe components with Options API.

defineNuxtComponent() is a helper function for defining type safe Vue components using options API similar to defineComponent(). defineNuxtComponent() wrapper also adds support for asyncData and head component options.
Using <script setup lang="ts"> is the recommended way of declaring Vue components in Nuxt 3.
 Read more in Docs > Getting Started > Data Fetching.
asyncData()

If you choose not to use setup() in your app, you can use the asyncData() method within your component definition:

pages/index.vue
<script lang="ts">

export default defineNuxtComponent({

  async asyncData() {

    return {

      data: {

        greetings: 'hello world!'

      }

    }

  },

})

</script>

head()

If you choose not to use setup() in your app, you can use the head() method within your component definition:

pages/index.vue
<script lang="ts">

export default defineNuxtComponent({

  head(nuxtApp) {

    return {

      title: 'My site'

    }

  },

})

</script>


createError

Create an error object with additional metadata.

defineNuxtRouteMiddleware

Create named route middleware using defineNuxtRouteMiddleware helper function.
Migrate to Nuxt Bridge: Plugins and Middleware

Upgrade Guide
Migrate to Nuxt Bridge
Plugins and Middleware

Learn how to migrate from Nuxt 2 to Nuxt Bridge new plugins and middleware.

New Plugins Format

You can now migrate to the Nuxt 3 plugins API, which is slightly different in format from Nuxt 2.

Plugins now take only one argument (nuxtApp). You can find out more in the docs.

plugins/hello.ts
export default defineNuxtPlugin(nuxtApp => {

  nuxtApp.provide('injected', () => 'my injected function')

  // now available on `nuxtApp.$injected`

})

If you want to use the new Nuxt composables (such as useNuxtApp or useRuntimeConfig) within your plugins, you will need to use the defineNuxtPlugin helper for those plugins.
Although a compatibility interface is provided via nuxtApp.vueApp you should avoid registering plugins, directives, mixins or components this way without adding your own logic to ensure they are not installed more than once, or this may cause a memory leak.
New Middleware Format

You can now migrate to the Nuxt 3 middleware API, which is slightly different in format from Nuxt 2.

Middleware now take only two argument (to, from). You can find out more in the docs.

export default defineNuxtRouteMiddleware((to) => {

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

    return navigateTo('/')

  }

})

Use of defineNuxtRouteMiddleware is not supported outside of the middleware directory.
You can also use definePageMeta in Nuxt Bridge. But only for middleware and layout.

Legacy Composition API

Learn how to migrate to Composition API with Nuxt Bridge.

New Composition API

Nuxt Bridge implements composables compatible with Nuxt 3.
Migrate to Nuxt Bridge: TypeScript

Upgrade Guide
Migrate to Nuxt Bridge
TypeScript

Learn how to use TypeScript with Nuxt Bridge.

Remove Modules
Remove @nuxt/typescript-build: Bridge enables same functionality
Remove @nuxt/typescript-runtime and nuxt-ts: Nuxt 2 has built-in runtime support
Set bridge.typescript
import { defineNuxtConfig } from '@nuxt/bridge'



export default defineNuxtConfig({

  bridge: {

    typescript: true,

    nitro: false // If migration to Nitro is complete, set to true

  }

})

Update tsconfig.json

If you are using TypeScript, you can edit your tsconfig.json to benefit from auto-generated Nuxt types:

tsconfig.json
{

+ "extends": "./.nuxt/tsconfig.json",

  "compilerOptions": {

    ...

  }

}

As .nuxt/tsconfig.json is generated and not checked into version control, you'll need to generate that file before running your tests. Add nuxi prepare as a step before your tests, otherwise you'll see TS5083: Cannot read file '~/.nuxt/tsconfig.json'
You may also need to add @vue/runtime-dom as a devDependency if you are struggling to get template type inference working with Volar.
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.

Overview

Reduce the differences with Nuxt 3 and reduce the burden of migration to Nuxt 3.

Legacy Composition API

Learn how to migrate to Composition API with Nuxt Bridge.
clearError · Nuxt Utils

Utils
clearError
Source

The clearError composable clears all handled errors.

clearError

Within your pages, components, and plugins, you can use clearError to clear all errors and redirect the user.

Parameters:

options?: { redirect?: string }

You can provide an optional path to redirect to (for example, if you want to navigate to a 'safe' page).

// Without redirect

clearError()



// With redirect

clearError({ redirect: '/homepage' })


Errors are set in state using useError(). The clearError composable will reset this state and calls the app:error:cleared hook with the provided options.

 Read more in Docs > Getting Started > Error Handling.

addRouteMiddleware

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

clearNuxtData

Delete cached data, error status and pending promises of useAsyncData and useFetch.
clearNuxtState · Nuxt Utils

Utils
clearNuxtState
Source

Delete the cached state of useState.

This method is useful if you want to invalidate the state of useState.
Type
clearNuxtState (keys?: string | string[] | ((key: string) => boolean)): void

Parameters
keys: One or an array of keys that are used in useState to delete their cached state. If no keys are provided, all state will be invalidated.

clearNuxtData

Delete cached data, error status and pending promises of useAsyncData and useFetch.

createError

Create an error object with additional metadata.
defineNuxtRouteMiddleware · Nuxt Utils

Utils
defineNuxtRouteMiddleware
Source

Create named route middleware using defineNuxtRouteMiddleware helper function.

Route middleware are stored in the middleware/ of your Nuxt application (unless set otherwise).

Type
defineNuxtRouteMiddleware(middleware: RouteMiddleware) => RouteMiddleware



interface RouteMiddleware {

  (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>

}

Parameters
middleware
Type: RouteMiddleware

A function that takes two Vue Router's route location objects as parameters: the next route to as the first, and the current route from as the second.

Learn more about available properties of RouteLocationNormalized in the Vue Router docs.

Examples
Showing Error Page

You can use route middleware to throw errors and show helpful error messages:

middleware/error.ts
export default defineNuxtRouteMiddleware((to) => {

  if (to.params.id === '1') {

    throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })

  }

})


The above route middleware will redirect a user to the custom error page defined in the ~/error.vue file, and expose the error message and code passed from the middleware.

Redirection

Use useState in combination with navigateTo helper function inside the route middleware to redirect users to different routes based on their authentication status:

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

  const auth = useState('auth')

  

  if (!auth.value.isAuthenticated) {

    return navigateTo('/login')

  }



  if (to.path !== '/dashboard') {

    return navigateTo('/dashboard')

  }

})


Both navigateTo and abortNavigation are globally available helper functions that you can use inside defineNuxtRouteMiddleware.

defineNuxtComponent

defineNuxtComponent() is a helper function for defining type safe components with Options API.

definePageMeta

Define metadata for your page components.
createError · Nuxt Utils

Utils
createError
Source

Create an error object with additional metadata.

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.

Parameters
err: { cause, data, message, name, stack, statusCode, statusMessage, fatal }
In Vue App

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
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' })

}

</script>

In API Routes

Use createError to trigger error handling in server API routes.

Example
export default eventHandler(() => {

  throw createError({

    statusCode: 404,

    statusMessage: 'Page Not Found'

  })

})

 Read more in Docs > Getting Started > Error Handling.

clearNuxtState

Delete the cached state of useState.

defineNuxtComponent

defineNuxtComponent() is a helper function for defining type safe components with Options API.
clearNuxtData · Nuxt Utils

Utils
clearNuxtData
Source

Delete cached data, error status and pending promises of useAsyncData and useFetch.

This method is useful if you want to invalidate the data fetching for another page.
Type
clearNuxtData (keys?: string | string[] | ((key: string) => boolean)): void

Parameters
keys: One or an array of keys that are used in useAsyncData to delete their cached data. If no keys are provided, all data will be invalidated.

clearError

The clearError composable clears all handled errors.

clearNuxtState

Delete the cached state of useState.
useSeoMeta · Nuxt Composables

Composables
useSeoMeta
Source

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

This helps you avoid common mistakes, such as using name instead of property, as well as typos - with over 100+ meta tags fully typed.

This is the recommended way to add meta tags to your site as it is XSS safe and has full TypeScript support.
 Read more in Docs > Getting Started > Seo Meta.
Usage
app.vue
<script setup lang="ts">

useSeoMeta({

  title: 'My Amazing Site',

  ogTitle: 'My Amazing Site',

  description: 'This is my amazing site, let me tell you all about it.',

  ogDescription: 'This is my amazing site, let me tell you all about it.',

  ogImage: 'https://example.com/image.png',

  twitterCard: 'summary_large_image',

})

</script>


When inserting tags that are reactive, you should use the computed getter syntax (() => value):

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

const title = ref('My title')



useSeoMeta({

  title,

  description: () => `description: ${title.value}`

})

</script>

Parameters

There are over 100 parameters. See the full list of parameters in the source code.

 Read more in Docs > Getting Started > Seo Meta.

useRuntimeConfig

Access runtime config variables with the useRuntimeConfig composable.

useServerSeoMeta

The useServerSeoMeta composable lets you define your site's SEO meta tags as a flat object with full TypeScript support.
Migrate to Nuxt 3: Server

Upgrade Guide
Migrate to Nuxt 3
Server

Learn how to migrate from Nuxt 2 to Nuxt 3 server.

In a built Nuxt 3 application, there is no runtime Nuxt dependency. That means your site will be highly performant, and ultra-slim. But it also means you can no longer hook into runtime Nuxt server hooks.

 Read more in Docs > Guide > Concepts > Server Engine.
Steps
Remove the render key in your nuxt.config.
Any files in ~/server/api and ~/server/middleware will be automatically registered; you can remove them from your serverMiddleware array.
Update any other items in your serverMiddleware array to point to files or npm packages directly, rather than using inline functions.
 Read more in Docs > Guide > Directory Structure > Server.
 Read more in Docs > Guide > Going Further > Hooks #server Hooks Runtime.

Build Tooling

Learn how to migrate from Nuxt 2 to Nuxt 3 build tooling.

Modules

Learn how to migrate from Nuxt 2 to Nuxt 3 modules.
Migrate to Nuxt 3: Runtime Config

Upgrade Guide
Migrate to Nuxt 3
Runtime Config

Learn how to migrate from Nuxt 2 to Nuxt 3 runtime config.

If you wish to reference environment variables within your Nuxt 3 app, you will need to use runtime config.

When referencing these variables within your components, you will have to use the useRuntimeConfig composable in your setup method (or Nuxt plugin).

In the server/ portion of your app, you can use useRuntimeConfig without any import.

 Read more in Docs > Guide > Going Further > Runtime Config.
Migration
Add any environment variables that you use in your app to the runtimeConfig property of the nuxt.config file.
Migrate process.env to useRuntimeConfig throughout the Vue part of your app.
nuxt.config.ts
pages/index.vue
server/api/hello.ts
.env
export default defineNuxtConfig({

  runtimeConfig: {

    // Private config that is only available on the server

    apiSecret: '123',

    // Config within public will be also exposed to the client

    public: {

      apiBase: '/api'

    }

  },

})


Component Options

Learn how to migrate from Nuxt 2 components options to Nuxt 3 composables.

Build Tooling

Learn how to migrate from Nuxt 2 to Nuxt 3 build tooling.
Migrate to Nuxt 3: Overview

Upgrade Guide
Migrate to Nuxt 3
Overview

Nuxt 3 is a complete rewrite of Nuxt 2, and also based on a new set of underlying technologies.

There are significant changes when migrating a Nuxt 2 app to Nuxt 3, although you can expect migration to become more straightforward as we move toward a stable release.

This migration guide is under progress to align with the development of Nuxt 3.

Some of these significant changes include:

Moving from Vue 2 to Vue 3, including defaulting to the Composition API and script setup.
Moving from webpack 4 and Babel to Vite or webpack 5 and esbuild.
Moving from a runtime Nuxt dependency to a minimal, standalone server compiled with nitropack.
If you need to remain on Nuxt 2, but want to benefit from Nuxt 3 features in Nuxt 2, you can alternatively check out how to get started with Bridge.
Next Steps
Learn about differences in configuration

Configuration

Learn how to configure Nuxt Bridge to your own needs.

Configuration

Learn how to migrate from Nuxt 2 to Nuxt 3 new configuration.
Migrate to Nuxt 3: Build Tooling

Upgrade Guide
Migrate to Nuxt 3
Build Tooling

Learn how to migrate from Nuxt 2 to Nuxt 3 build tooling.

We use the following build tools by default:

Vite or webpack
Rollup
PostCSS
esbuild

For this reason, most of your previous build configuration in nuxt.config will now be ignored, including any custom babel configuration.

If you need to configure any of Nuxt's build tools, you can do so in your nuxt.config, using the new top-level vite, webpack and postcss keys.

In addition, Nuxt ships with TypeScript support.

 Read more in Docs > Guide > Concepts > Typescript.
Steps
Remove @nuxt/typescript-build and @nuxt/typescript-runtime from your dependencies and modules.
Remove any unused babel dependencies from your project.
Remove any explicit core-js dependencies.
Migrate require to import.

Runtime Config

Learn how to migrate from Nuxt 2 to Nuxt 3 runtime config.

Server

Learn how to migrate from Nuxt 2 to Nuxt 3 server.
useRouter · Nuxt Composables

Composables
useRouter
Source

The useRouter composable returns the router instance.

pages/index.vue
<script setup>

const router = useRouter()

</script>


If you only need the router instance within your template, use $router:

pages/index.vue
<template>

  <button @click="$router.back()">Back</button>

</template>


If you have a pages/ directory, useRouter is identical in behavior to the one provided by vue-router.

Read vue-router documentation about the Router interface.
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.
resolve(): Returns the normalized version of a route location. Also includes an href property that includes any existing base.
Example
const router = useRouter()



router.addRoute({ name: 'home', path: '/home', component: Home })

router.removeRoute('home')

router.getRoutes()

router.hasRoute('home')

router.resolve({ name: 'home' })

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 pages, Vue components and composable.
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 instead.
replace(): Programmatically navigate to a new URL by replacing the current entry in the routes history stack. It is recommended to use navigateTo instead.
Example
const router = useRouter()



router.back()

router.forward()

router.go(3)

router.push({ path: "/home" })

router.replace({ hash: "#bio" })

Read more about the browser's History API.
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.

 Read more in 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.
 Read more in Vue Router Docs.
Universal Router Instance

If you do not have a pages/ folder, then useRouter 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.

useRoute

The useRoute composable returns the current route.

useRuntimeConfig

Access runtime config variables with the useRuntimeConfig composable.
<ClientOnly> · Nuxt Components

Components
<ClientOnly>
Source

Render components only in client-side with the <ClientOnly> component.

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

  <div>

    <Sidebar />

    <ClientOnly fallback-tag="span" fallback="Loading comments...">

      <Comment />

    </ClientOnly>

  </div>

</template>

Slots
#fallback: specify a content to be displayed server-side.
<template>

  <div>

    <Sidebar />

    <ClientOnly>

      <!-- ... -->

      <template #fallback>

        <!-- this will be rendered on server side -->

        <p>Loading comments...</p>

      </template>

    </ClientOnly>

  </div>

</template>


Nightly Release Channel

The nightly release channel allows using Nuxt built directly from the latest commits to the repository.

<NuxtClientFallback>

Nuxt provides the <NuxtClientFallback> component to render its content on the client if any of its children trigger an error in SSR
Migrate to Nuxt 3: Auto Imports

Upgrade Guide
Migrate to Nuxt 3
Auto Imports

Nuxt 3 adopts a minimal friction approach, meaning wherever possible components and composables are auto-imported.

In the rest of the migration documentation, you will notice that key Nuxt and Vue utilities do not have explicit imports. This is not a typo; Nuxt will automatically import them for you, and you should get full type hinting if you have followed the instructions to use Nuxt's TypeScript support.

Read more about auto imports

Migration
If you have been using @nuxt/components in Nuxt 2, you can remove components: true in your nuxt.config. If you had a more complex setup, then note that the component options have changed somewhat. See the components documentation for more information.
You can look at .nuxt/types/components.d.ts and .nuxt/types/imports.d.ts to see how Nuxt has resolved your components and composable auto-imports.

Configuration

Learn how to migrate from Nuxt 2 to Nuxt 3 new configuration.

Meta Tags

Manage your meta tags, from Nuxt 2 to Nuxt 3.
Migrate to Nuxt 3: Plugins and Middleware

Upgrade Guide
Migrate to Nuxt 3
Plugins and Middleware

Learn how to migrate from Nuxt 2 to Nuxt 3 plugins and middleware.

Plugins

Plugins now have a different format, and take only one argument (nuxtApp).

Nuxt 2
Nuxt 3
export default (ctx, inject) => {

  inject('injected', () => 'my injected function')

})

 Read more in Docs > Guide > Directory Structure > Plugins.
Read more about the format of nuxtApp.
Migration
Migrate your plugins to use the defineNuxtPlugin helper function.
Remove any entries in your nuxt.config plugins array that are located in your plugins/ folder. All files in this directory at the top level (and any index files in any subdirectories) will be automatically registered. Instead of setting mode to client or server, you can indicate this in the file name. For example, ~/plugins/my-plugin.client.ts will only be loaded on client-side.
Route Middleware

Route middleware has a different format.

Nuxt 2
Nuxt 3
export default function ({ store, redirect }) {

  // If the user is not authenticated

  if (!store.state.authenticated) {

    return redirect('/login')

  }

}


Much like Nuxt 2, route middleware placed in your ~/middleware folder is automatically registered. You can then specify it by name in a component. However, this is done with definePageMeta rather than as a component option.

navigateTo is one of a number of route helper functions.

 Read more in Docs > Guide > Directory Structure > Middleware.
Migration
Migrate your route middleware to use the defineNuxtRouteMiddleware helper function.
Any global middleware (such as in your nuxt.config) can be placed in your ~/middleware folder with a .global extension, for example ~/middleware/auth.global.ts.

Meta Tags

Manage your meta tags, from Nuxt 2 to Nuxt 3.

Pages and Layouts

Learn how to migrate from Nuxt 2 to Nuxt 3 pages and layouts.
Migrate to Nuxt 3: Meta Tags

Upgrade Guide
Migrate to Nuxt 3
Meta Tags

Manage your meta tags, from Nuxt 2 to Nuxt 3.

Nuxt 3 provides several different ways to manage your meta tags:

Through your nuxt.config.
Through the useHead composable
Through global meta components

You can customize title, titleTemplate, base, script, noscript, style, meta, link, htmlAttrs and bodyAttrs.

Nuxt currently uses vueuse/head to manage your meta tags, but implementation details may change.
 Read more in Docs > Getting Started > Seo Meta.
Migration
In your nuxt.config, rename head to meta. Consider moving this shared meta configuration into your app.vue instead. (Note that objects no longer have a hid key for deduplication.)
If you need to access the component state with head, you should migrate to using useHead . You might also consider using the built-in meta-components.
If you need to use the Options API, there is a head() method you can use when you use defineNuxtComponent.
useHead
Nuxt 2
Nuxt 3
<script>

export default {

  data: () => ({

    title: 'My App',

    description: 'My App Description'

  })

  head () {

    return {

      title: this.title,

      meta: [{

        hid: 'description',

        name: 'description',

        content: this.description

      }]

    }

  }

}

</script>

Meta-components

Nuxt 3 also provides meta components that you can use to accomplish the same task. While these components look similar to HTML tags, they are provided by Nuxt and have similar functionality.

Nuxt 2
Nuxt 3
<script>

export default {

  head () {

    return {

      title: 'My App',

      meta: [{

        hid: 'description',

        name: 'description',

        content: 'My App Description'

      }]

    }

  }

}

</script>

Make sure you use capital letters for these component names to distinguish them from native HTML elements (<Title> rather than <title>).
You can place these components anywhere in your template for your page.
Options API
Nuxt 3 (Options API)
<script>

// if using options API `head` method you must use `defineNuxtComponent`

export default defineNuxtComponent({

  head (nuxtApp) {

    // `head` receives the nuxt app but cannot access the component instance

    return {

      meta: [{

        name: 'description',

        content: 'This is my page description.'

      }]

    }

  }

})

</script>


Auto Imports

Nuxt 3 adopts a minimal friction approach, meaning wherever possible components and composables are auto-imported.

Plugins and Middleware

Learn how to migrate from Nuxt 2 to Nuxt 3 plugins and middleware.
Layers · Nuxt Examples

Examples
Advanced
Layers

This example shows how to use the extends key in `nuxt.config.ts`.

This example shows how to use the extends key in nuxt.config.ts to use the base/ directory as a base Nuxt application, and use its components, composables or config and override them if necessary.

 Read more in Docs > Getting Started > Layers.
Loading Sandbox...

Universal Router

This example demonstrates Nuxt universal routing utilities without depending on `pages/` and `vue-router`.

Error Handling

This example shows how to handle errors in different contexts: pages, plugins, components and middleware.
Auto Imports · Nuxt Examples

Examples
Features
Auto Imports

This example demonstrates the auto-imports feature in Nuxt.

Example of the auto-imports feature in Nuxt with:

Vue components in the components/ directory are auto-imported and can be used directly in your templates.
Vue composables in the composables/ directory are auto-imported and can be used directly in your templates and JS/TS files.
JS/TS variables and functions in the utils/ directory are auto-imported and can be used directly in your templates and JS/TS files.
 Read more in Docs > Guide > Directory Structure > Components.
 Read more in Docs > Guide > Directory Structure > Composables.
 Read more in Docs > Guide > Directory Structure > Utils.
Loading Sandbox...

Hello World

A minimal Nuxt 3 application only requires the `app.vue` and `nuxt.config.js` files.

Data Fetching

This example demonstrates data fetching with Nuxt 3 using built-in composables and API routes.
nuxi dev · Nuxt Commands

Commands
nuxi dev
Source

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

Terminal
npx nuxi dev [rootDir] [--dotenv] [--log-level] [--clipboard] [--open, -o] [--no-clear] [--port, -p] [--host, -h] [--https] [--ssl-cert] [--ssl-key]


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

Option	Default	Description
rootDir	.	The root directory of the application to serve.
--dotenv	.	Point to another .env file to load, relative to the root directory.
--clipboard	false	Copy URL to clipboard.
--open, -o	false	Open URL in browser.
--no-clear	false	Does not clear the console after startup.
--port, -p	3000	Port to listen.
--host, -h	localhost	Hostname of the server.
--https	false	Listen with https protocol with a self-signed certificate by default.
--ssl-cert	null	Specify a certificate for https.
--ssl-key	null	Specify the key for the https certificate.

The port and host can also be set via NUXT_PORT, PORT, NUXT_HOST or HOST environment variables.

Additionally to the above options, nuxi can pass options through to listhen, e.g. --no-qr to turn off the dev server QR code. You can find the list of listhen options in the unjs/listhen docs.

This command sets process.env.NODE_ENV to development.

If you are using a self-signed certificate in development, you will need to set NODE_TLS_REJECT_UNAUTHORIZED=0 in your environment.

nuxi cleanup

Remove common generated Nuxt files and caches.

nuxi devtools

The devtools command allows you to enable or disable Nuxt DevTools on a per-project basis.
app.vue · Nuxt Directory Structure

Guide
Directory Structure
app.vue

The app.vue file is the main component of your Nuxt application.

Minimal Usage

With Nuxt 3, the pages/ directory is optional. If not present, Nuxt won't include vue-router dependency. This is useful when working on a landing page or an application that does not need routing.

app.vue
<template>

  <h1>Hello World!</h1>

</template>

 Read and edit a live example in Docs > Examples > Hello World.
Usage with Pages

If you have a pages/ directory, to display the current page, use the <NuxtPage> component:

app.vue
<template>

  <div>

    <NuxtLayout>

      <NuxtPage/>

    </NuxtLayout>

  </div>

</template>

Since <NuxtPage> internally uses Vue's <Suspense> component, it cannot be set as a root element.
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/ directory.

app.config.ts

Expose reactive configuration within your application with the App Config file.

nuxt.config.ts

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

Community
Releases

Discover the latest releases of Nuxt & Nuxt official modules.

nuxt/nuxt

Nuxt framework releases.

nuxt/cli

Nuxt CLI (nuxi) releases.

nuxt/content

Nuxt Content releases.

nuxt/devtools

Nuxt DevTools releases.

nuxt/image

Nuxt Image releases.

nuxt/ui

Nuxt UI releases.

Discover the nuxt organization on GitHub

Roadmap

Nuxt is constantly evolving, with new features and modules being added all the time.

Overview

Reduce the differences with Nuxt 3 and reduce the burden of migration to Nuxt 3.
Reporting Bugs · Nuxt Community

Community
Reporting Bugs

One of the most valuable roles in open source is taking the time to report bugs helpfully.

Try as we might, we will never completely eliminate bugs.

Even if you can't fix the underlying code, reporting a bug well can enable someone else with a bit more familiarity with the codebase to spot a pattern or make a quick fix.

Here are a few key steps.

Is It Really a Bug?

Consider if you're looking to get help with something, or whether you think there's a bug with Nuxt itself. If it's the former, we'd love to help you - but the best way to do that is through asking for help rather than reporting a bug.

Search the Issues

Search through the open issues and discussions first. If you find anything that seems like the same bug, it's much better to comment on an existing thread than create a duplicate.

Create a Minimal Reproduction

It's important to be able to reproduce the bug reliably - in a minimal way and apart from the rest of your project. This narrows down what could be causing the issue and makes it possible for someone not only to find the cause, but also to test a potential solution.

Start with the Nuxt 3 or Nuxt Bridge sandbox and add the minimum amount of code necessary to reproduce the bug you're experiencing.

If your issue concerns Vue 3 or Vite, please try to reproduce it first with the Vue 3 SSR starter.

Nuxt 3:

Nuxt 3 on StackBlitz

Nuxt 3 on CodeSandbox

Nuxt Bridge:

Nuxt Bridge on CodeSandbox

Vue 3:

Vue 3 SSR on StackBlitz

Vue 3 SSR on CodeSandbox

Vue 3 SSR Template on GitHub

Once you've reproduced the issue, remove as much code from your reproduction as you can (while still recreating the bug). The time spent making the reproduction as minimal as possible will make a huge difference to whoever sets out to fix the issue.

Figure Out What the Cause Might Be

With a Nuxt project, there are lots of moving pieces - from Nuxt modules to other JavaScript libraries. Try to report the bug at the most relevant and specific place. That will likely be the Nuxt module causing an issue, or the upstream library that Nuxt is depending on.

Getting Help

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

Contribution

Nuxt is a community project - and so we love contributions of all kinds! ❤️
useAppConfig · Nuxt Composables

Composables
useAppConfig
Source

Access the reactive app config defined in the project.

Usage
const appConfig = useAppConfig()



console.log(appConfig)

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

<Teleport>

The <Teleport> component teleports a component to a different location in the DOM.

useAsyncData

useAsyncData provides access to data that resolves asynchronously in a SSR-friendly composable.