matijao/webdev huggingface dataset:
useNuxtData · Nuxt Composables

Composables
useNuxtData
Source

Access the current cached value of data fetching composables.

useNuxtData gives you access to the current cached value of useAsyncData , useLazyAsyncData, useFetch and useLazyFetch with explicitly provided key.
Usage

The example below shows how you can use cached data as a placeholder while the most recent data is being fetched from the server.

pages/posts.vue
<script setup>

// We can access same data later using 'posts' key

const { data } = await useFetch('/api/posts', { key: 'posts' })

</script>

pages/posts/[id].vue
// Access to the cached value of useFetch in posts.vue (parent route)

const { id } = useRoute().params

const { data: posts } = useNuxtData('posts')

const { data } = useLazyFetch(`/api/posts/${id}`, {

  key: `post-${id}`,

  default() {

    // Find the individual post from the cache and set it as the default value.

    return posts.value.find(post => post.id === id)

  }

})

Optimistic Updates

We can leverage the cache to update the UI after a mutation, while the data is being invalidated in the background.

pages/todos.vue
<script setup>

// We can access same data later using 'todos' key

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

</script>

components/NewTodo.vue
<script setup>

const newTodo = ref('')

const previousTodos = ref([])



// Access to the cached value of useFetch in todos.vue

const { data: todos } = useNuxtData('todos')



const { data } = await useFetch('/api/addTodo', {

  method: 'post',

  body: {

    todo: newTodo.value

  },

  onRequest () {

    previousTodos.value = todos.value // Store the previously cached value to restore if fetch fails.



    todos.value.push(newTodo.value) // Optimistically update the todos.

  },

  onRequestError () {

    todos.value = previousTodos.value // Rollback the data if the request failed.

  },

  async onResponse () {

    await refreshNuxtData('todos') // Invalidate todos in the background if the request succeeded.

  }

})

</script>

Type
useNuxtData<DataT = any> (key: string): { data: Ref<DataT | null> }


useNuxtApp

Access the shared runtime context of the Nuxt Application.

useRequestEvent

Access the incoming request event with the useRequestEvent composable.
useRequestHeaders · Nuxt Composables

Composables
useRequestHeaders
Source

Use useRequestHeaders to access the incoming request headers.

You can use built-in useRequestHeaders composable to access the incoming request headers within your pages, components, and plugins.

// Get all request headers

const headers = useRequestHeaders()



// Get only cookie request header

const headers = useRequestHeaders(['cookie'])

In the browser, useRequestHeaders will return an empty object.
Example

We can use useRequestHeaders to access and proxy the initial request's authorization header to any future internal requests during SSR.

The example below adds the authorization request header to an isomorphic $fetch call.

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

const { data } = await useFetch('/api/confidential', {

  headers: useRequestHeaders(['authorization'])

})

</script>


useRequestEvent

Access the incoming request event with the useRequestEvent composable.

useRequestURL

Access the incoming request URL with the useRequestURL composable.
useRequestEvent · Nuxt Composables

Composables
useRequestEvent
Source

Access the incoming request event with the useRequestEvent composable.

Within your pages, components, and plugins you can use useRequestEvent to access the incoming request.

// Get underlying request event

const event = useRequestEvent()



// Get the URL

const url = event.path

In the browser, useRequestEvent will return undefined.

useNuxtData

Access the current cached value of data fetching composables.

useRequestHeaders

Use useRequestHeaders to access the incoming request headers.
useLazyFetch · Nuxt Composables

Composables
useLazyFetch
Source

This wrapper around useFetch triggers navigation immediately.

Description

By default, useFetch blocks navigation until its async handler is resolved. useLazyFetch provides a wrapper around useFetch that triggers navigation before the handler is resolved by setting the lazy option to true.

useLazyFetch has the same signature as useFetch.
 Read more in Docs > API > Composables > Use Fetch.
Example
pages/index.vue
<script setup lang="ts">

/* Navigation will occur before fetching is complete.

  Handle pending and error states directly within your component's template

*/

const { pending, data: posts } = await useLazyFetch('/api/posts')

watch(posts, (newPosts) => {

  // Because posts might start out null, you won't have access

  // to its contents immediately, but you can watch it.

})

</script>



<template>

  <div v-if="pending">

    Loading ...

  </div>

  <div v-else>

    <div v-for="post in posts">

      <!-- do something -->

    </div>

  </div>

</template>

useLazyFetch is a reserved function name transformed by the compiler, so you should not name your own function useLazyFetch.
 Read more in Docs > Getting Started > Data Fetching.

useLazyAsyncData

This wrapper around useAsyncData triggers navigation immediately.

useNuxtApp

Access the shared runtime context of the Nuxt Application.
useLazyAsyncData · Nuxt Composables

Composables
useLazyAsyncData
Source

This wrapper around useAsyncData triggers navigation immediately.

Description

By default, useAsyncData blocks navigation until its async handler is resolved. useLazyAsyncData provides a wrapper around useAsyncData that triggers navigation before the handler is resolved by setting the lazy option to true.

useLazyAsyncData has the same signature as useAsyncData.
 Read more in Docs > API > Composables > Use Async Data.
Example
pages/index.vue
<script setup lang="ts">

/* Navigation will occur before fetching is complete.

  Handle pending and error states directly within your component's template

*/

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



watch(count, (newCount) => {

  // Because count might start out null, you won't have access

  // to its contents immediately, but you can watch it.

})

</script>



<template>

  <div>

    {{ pending ? 'Loading' : count }}

  </div>

</template>

useLazyAsyncData is a reserved function name transformed by the compiler, so you should not name your own function useLazyAsyncData.
 Read more in Docs > Getting Started > Data Fetching #uselazyasyncdata.

useHydration

Allows full control of the hydration cycle to set and receive data from the server.

useLazyFetch

This wrapper around useFetch triggers navigation immediately.
useHeadSafe · Nuxt Composables

Composables
useHeadSafe
Source

The recommended way to provide head data with user input.

The useHeadSafe composable is a wrapper around the useHead composable that restricts the input to only allow safe values.

Usage

You can pass all the same values as useHead

useHeadSafe({

  script: [

    { id: 'xss-script', innerHTML: 'alert("xss")' }

  ],

  meta: [

    { 'http-equiv': 'refresh', content: '0;javascript:alert(1)' }

  ]

})

// Will safely generate

// <script id="xss-script"></script>

// <meta content="0;javascript:alert(1)">

Read more on unhead documentation.
Type
useHeadSafe(input: MaybeComputedRef<HeadSafe>): void


The whitelist of safe values is:

export default {

  htmlAttrs: ['id', 'class', 'lang', 'dir'],

  bodyAttrs: ['id', 'class'],

  meta: ['id', 'name', 'property', 'charset', 'content'],

  noscript: ['id', 'textContent'],

  script: ['id', 'type', 'textContent'],

  link: ['id', 'color', 'crossorigin', 'fetchpriority', 'href', 'hreflang', 'imagesrcset', 'imagesizes', 'integrity', 'media', 'referrerpolicy', 'rel', 'sizes', 'type'],

}


See @unhead/schema for more detailed types.

useFetch

Fetch data from an API endpoint with a SSR-friendly composable.

useHead

useHead customizes the head properties of individual pages of your Nuxt app.
useHydration · Nuxt Composables

Composables
useHydration
Source

Allows full control of the hydration cycle to set and receive data from the server.

useHydration is a built-in composable that provides a way to set data on the server side every time a new HTTP request is made and receive that data on the client side. This way useHydration allows you to take full control of the hydration cycle.

This is an advanced composable and is mostly used internally (useAsyncData) or by Nuxt modules.
Type
signature
useHydration <T> (key: string, get: () => T, set: (value: T) => void) => {}


You can use useHydration() within composables, plugins and components.

useHydration accepts three parameters:

key: unique key that identifies the data in your Nuxt application
Type: String
get: function that returns the value to set the initial data
Type: Function
set: function that receives the data on the client-side
Type: Function

Once the initial data is returned using the get function on the server side, you can access that data within nuxtApp.payload using the unique key that is passed as the first parameter in useHydration composable.

 Read more in Docs > Getting Started > Data Fetching.

useHead

useHead customizes the head properties of individual pages of your Nuxt app.

useLazyAsyncData

This wrapper around useAsyncData triggers navigation immediately.
useHead · Nuxt Composables

Composables
useHead
Source

useHead customizes the head properties of individual pages of your Nuxt app.

The useHead composable function allows you to manage your head tags in a programmatic and reactive way, powered by Unhead. If the data comes from a user or other untrusted source, we recommend you check out useHeadSafe.

 Read more in Docs > Getting Started > Seo Meta.
Type
useHead(meta: MaybeComputedRef<MetaObject>): void


Below are the non-reactive types for useHead .

interface MetaObject {

  title?: string

  titleTemplate?: string | ((title?: string) => string)

  base?: Base

  link?: Link[]

  meta?: Meta[]

  style?: Style[]

  script?: Script[]

  noscript?: Noscript[]

  htmlAttrs?: HtmlAttributes

  bodyAttrs?: BodyAttributes

}


See @unhead/schema for more detailed types.

The properties of useHead can be dynamic, accepting ref, computed and reactive properties. meta parameter can also accept a function returning an object to make the entire object reactive.
Params
meta

Type: MetaObject

An object accepting the following head metadata:

meta: Each element in the array is mapped to a newly-created <meta> tag, where object properties are mapped to the corresponding attributes.
Type: Array<Record<string, any>>
link: Each element in the array is mapped to a newly-created <link> tag, where object properties are mapped to the corresponding attributes.
Type: Array<Record<string, any>>
style: Each element in the array is mapped to a newly-created <style> tag, where object properties are mapped to the corresponding attributes.
Type: Array<Record<string, any>>
script: Each element in the array is mapped to a newly-created <script> tag, where object properties are mapped to the corresponding attributes.
Type: Array<Record<string, any>>
noscript: Each element in the array is mapped to a newly-created <noscript> tag, where object properties are mapped to the corresponding attributes.
Type: Array<Record<string, any>>
titleTemplate: Configures dynamic template to customize the page title on an individual page.
Type: string | ((title: string) => string)
title: Sets static page title on an individual page.
Type: string
bodyAttrs: Sets attributes of the <body> tag. Each object property is mapped to the corresponding attribute.
Type: Record<string, any>
htmlAttrs: Sets attributes of the <html> tag. Each object property is mapped to the corresponding attribute.
Type: Record<string, any>

useHeadSafe

The recommended way to provide head data with user input.

useHydration

Allows full control of the hydration cycle to set and receive data from the server.
useError · Nuxt Composables

Composables
useError
Source

useError composable returns the global Nuxt error that is being handled.

The composable returns the global Nuxt error that is being handled and it is available on both client and server.

const error = useError()


useError sets an error in the state and creates a reactive as well as SSR-friendly global Nuxt error across components.

Nuxt errors have the following properties:

interface {

  //  HTTP response status code

  statusCode: number

  // HTTP response status message

  statusMessage: string

  // Error message

  message: string

}

 Read more in Docs > Getting Started > Error Handling.

useCookie

useCookie is an SSR-friendly composable to read and write cookies.

useFetch

Fetch data from an API endpoint with a SSR-friendly composable.
<Teleport> · Nuxt Components

Components
<Teleport>

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

The to target of <Teleport> expects a CSS selector string or an actual DOM node. Nuxt currently has SSR support for teleports to body only, with client-side support for other targets using a <ClientOnly> wrapper.
Body Teleport
<template>

  <button @click="open = true">

    Open Modal

  </button>

  <Teleport to="body">

    <div v-if="open" class="modal">

      <p>Hello from the modal!</p>

      <button @click="open = false">

        Close

      </button>

    </div>

  </Teleport>

</template>

Client-side Teleport
<template>

  <ClientOnly>

    <Teleport to="#some-selector">

      <!-- content -->

    </Teleport>

  </ClientOnly>

</template>

 Read and edit a live example in Docs > Examples > Advanced > Teleport.

<NuxtPicture>

Nuxt provides a <NuxtPicture> component to handle automatic image optimization.

useAppConfig

Access the reactive app config defined in the project.
<NuxtPicture> · Nuxt Components

Components
<NuxtPicture>
Source

Nuxt provides a <NuxtPicture> component to handle automatic image optimization.

<NuxtPicture> is a drop-in replacement for the native <picture> tag.

Usage of <NuxtPicture> is almost identical to <NuxtImg> but it also allows serving modern formats like webp when possible.

Learn more about the <picture> tag on MDN.

Setup

In order to use <NuxtPicture> you should install and enable the Nuxt Image module:

Terminal
npx nuxi@latest module add image

Read more about the <NuxtPicture> component.

<NuxtImg>

Nuxt provides a <NuxtImg> component to handle automatic image optimization.

<Teleport>

The <Teleport> component teleports a component to a different location in the DOM.
<NuxtImg> · Nuxt Components

Components
<NuxtImg>
Source

Nuxt provides a <NuxtImg> component to handle automatic image optimization.

<NuxtImg> is a drop-in replacement for the native <img> tag.

Uses built-in provider to optimize local and remote images
Converts src to provider-optimized URLs
Automatically resizes images based on width and height
Generates responsive sizes when providing sizes option
Supports native lazy loading as well as other <img> attributes
Setup

In order to use <NuxtImg> you should install and enable the Nuxt Image module:

Terminal
npx nuxi@latest module add image

Usage

<NuxtImg> outputs a native img tag directly (without any wrapper around it). Use it like you would use the <img> tag:

<NuxtImg src="/nuxt-icon.png" />


Will result in:

<img src="/nuxt-icon.png" />

Read more about the <NuxtImg> component.

<NuxtIsland>

Nuxt provides the <NuxtIsland> component to render a non-interactive component without any client JS.

<NuxtPicture>

Nuxt provides a <NuxtPicture> component to handle automatic image optimization.
<NuxtIsland> · Nuxt Components

Components
<NuxtIsland>
Source

Nuxt provides the <NuxtIsland> component to render a non-interactive component without any client JS.

When rendering an island component, the content of the island component is static, thus no JS is downloaded client-side.

Changing the island component props triggers a refetch of the island component to re-render it again.

This component is experimental and in order to use it you must enable the experimental.componentIslands option in your nuxt.config.
Global styles of your application are sent with the response.
Server only components use <NuxtIsland> under the hood
Props
name : Name of the component to render.
type: string
required
lazy: Make the component non-blocking.
type: boolean
default: false
props: Props to send to the component to render.
type: Record<string, any>
source: Remote source to call the island to render.
type: string
Remote islands need experimental.componentIslands to be 'local+remote' in your nuxt.config.
Slots

Slots can be passed to an island component if declared.

Every slot is interactive since the parent component is the one providing it.

Some slots are reserved to NuxtIsland for special cases.

#fallback: Specify the content to be rendered before the island loads (if the component is lazy) or if NuxtIsland fails to fetch the component.

<NuxtWelcome>

The <NuxtWelcome> component greets users in new projects made from the starter template.

<NuxtImg>

Nuxt provides a <NuxtImg> component to handle automatic image optimization.
<NuxtWelcome> · Nuxt Components

Components
<NuxtWelcome>
Source

The <NuxtWelcome> component greets users in new projects made from the starter template.

It includes links to the Nuxt documentation, source code, and social media accounts.

app.vue
<template>

  <NuxtWelcome />

</template>

Preview the <NuxtWelcome /> component.
This component is part of nuxt/assets.

<NuxtErrorBoundary>

The <NuxtErrorBoundary> component handles client-side errors happening in its default slot.

<NuxtIsland>

Nuxt provides the <NuxtIsland> component to render a non-interactive component without any client JS.
<NuxtLayout> · Nuxt Components

Components
<NuxtLayout>
Source

Nuxt provides the <NuxtLayout> component to show layouts on pages and error pages.

You can use <NuxtLayout /> component to activate the default layout on app.vue or error.vue.

app.vue
<template>

  <NuxtLayout>

    some page content

  </NuxtLayout>

</template>

 Read more in Docs > Guide > Directory Structure > Layouts.
Props
name: Specify a layout name to be rendered, can be a string, reactive reference or a computed property. It must match the name of the corresponding layout file in the layouts/ directory.
type: string
default: default
pages/index.vue
<script setup lang="ts">

// layouts/custom.vue

const layout = 'custom'

</script>



<template>

  <NuxtLayout :name="layout">

    <NuxtPage />

  </NuxtLayout>

</template>

Please note the layout name is normalized to kebab-case, so if your layout file is named errorLayout.vue, it will become error-layout when passed as a name property to <NuxtLayout />.
error.vue
<template>

  <NuxtLayout name="error-layout">

    <NuxtPage />

  </NuxtLayout>

</template>

Read more about dynamic layouts.
Additional Props

NuxtLayout also accepts any additional props that you may need to pass to the layout. These custom props are then made accessible as attributes.

pages/some-page.vue
<template>

  <div>

    <NuxtLayout name="custom" title="I am a custom layout">

      <-- ... -->

    </NuxtLayout>

  </div>

</template>


In the above example, the value of title will be available using $attrs.title in the template or useAttrs().title in <script setup> at custom.vue.

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

const layoutCustomProps = useAttrs()



console.log(layoutCustomProps.title) // I am a custom layout

</script>

Transitions

<NuxtLayout /> renders incoming content via <slot />, which is then wrapped around Vue’s <Transition /> component to activate layout transition. For this to work as expected, it is recommended that <NuxtLayout /> is not the root element of the page component.

pages/index.vue
<template>

  <div>

    <NuxtLayout name="custom">

      <template #header> Some header template content. </template>

    </NuxtLayout>

  </div>

</template>

 Read more in Docs > Getting Started > Transitions.
Layout's Ref

To get the ref of a layout component, access it through ref.value.layoutRef.

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

const layout = ref()



function logFoo () {

  layout.value.layoutRef.foo()

}

</script>



<template>

  <NuxtLayout ref="layout" />

</template>

 Read more in Docs > Guide > Directory Structure > Layouts.

<NuxtPage>

The <NuxtPage> component is required to display pages located in the pages/ directory.

<NuxtLink>

Nuxt provides <NuxtLink> component to handle any kind of links within your application.
<NuxtErrorBoundary> · Nuxt Components

Components
<NuxtErrorBoundary>
Source

The <NuxtErrorBoundary> component handles client-side errors happening in its default slot.

The <NuxtErrorBoundary> uses Vue's onErrorCaptured hook under the hood.
Events
@error: Event emitted when the default slot of the component throws an error.
<template>

  <NuxtErrorBoundary @error="logSomeError">

    <!-- ... -->

  </NuxtErrorBoundary>

</template>

Slots
#error: Specify a fallback content to display in case of error.
  <template>

    <NuxtErrorBoundary>

      <!-- ... -->

      <template #error="{ error }">

        <p>An error occurred: {{ error }}</p>

      </template>

    </NuxtErrorBoundary>

  </template>

 Read more in Docs > Getting Started > Error Handling.

<NuxtLoadingIndicator>

Display a progress bar between page navigations.

<NuxtWelcome>

The <NuxtWelcome> component greets users in new projects made from the starter template.
<NuxtLoadingIndicator> · Nuxt Components

Components
<NuxtLoadingIndicator>
Source

Display a progress bar between page navigations.

Usage

Add <NuxtLoadingIndicator/> in your app.vue or layouts/.

app.vue
<template>

  <NuxtLayout>

    <div>

      <NuxtLoadingIndicator /> <!-- here -->

      <NuxtPage />

    </div>

  </NuxtLayout>

</template>

 Read and edit a live example in Docs > Examples > Routing > Pages.
Slots

You can pass custom HTML or components through the loading indicator's default slot.

Props
color: The color of the loading bar. It can be set to false to turn off explicit color styling.
height: Height of the loading bar, in pixels (default 3).
duration: Duration of the loading bar, in milliseconds (default 2000).
throttle: Throttle the appearing and hiding, in milliseconds (default 200).
This component is optional.
To achieve full customization, you can implement your own one based on its source code.

<NuxtLink>

Nuxt provides <NuxtLink> component to handle any kind of links within your application.

<NuxtErrorBoundary>

The <NuxtErrorBoundary> component handles client-side errors happening in its default slot.
<NuxtPage> · Nuxt Components

Components
<NuxtPage>
Source

The <NuxtPage> component is required to display pages located in the pages/ directory.

<NuxtPage> is a built-in component that comes with Nuxt. It lets you display top-level or nested pages located in the pages/ directory.

<NuxtPage> is a wrapper around <RouterView> component from Vue Router.
It accepts same name and route props.
Props
name: tells RouterView to render the component with the corresponding name in the matched route record's components option.
type: string
route: route location that has all of its components resolved.
type: RouteLocationNormalized
pageKey: control when the NuxtPage component is re-rendered.
type: string or function
Nuxt automatically resolves the name and route by scanning and rendering all Vue component files found in the /pages directory.
Example

For example, passing static key, NuxtPage component is rendered only once when it is mounted.

app.vue
<template>

  <NuxtPage page-key="static" />

</template>


You can also use a dynamic key based on the current route:

<NuxtPage :page-key="route => route.fullPath" />

Don't use $route object here as it can cause problems with how <NuxtPage> renders pages with <Suspense>.

Alternatively, pageKey can be passed as a key value via definePageMeta from the <script> section of your Vue component in the /pages directory.

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

definePageMeta({

  key: route => route.fullPath

})

</script>

 Read and edit a live example in Docs > Examples > Routing > Pages.
Page's Ref

To get the ref of a page component, access it through ref.value.pageRef

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

const page = ref()



function logFoo () {

  page.value.pageRef.foo()

}

</script>



<template>

  <NuxtPage ref="page" />

</template>

Custom Props

In addition, <NuxtPage> also accepts custom props that you may need to pass further down the hierarchy.

These custom props are accessible via attrs in the Nuxt app.

<NuxtPage :foobar="123" />


For example, in the above example, the value of foobar will be available using $attrs.foobar in the template or useAttrs().foobar in <script setup>.

 Read more in Docs > Guide > Directory Structure > Pages.

<NuxtClientFallback>

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

<NuxtLayout>

Nuxt provides the <NuxtLayout> component to show layouts on pages and error pages.
<NuxtClientFallback> · Nuxt Components

Components
<NuxtClientFallback>
Source (client)
Source (server)

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

This component is experimental and in order to use it you must enable the experimental.clientFallback option in your nuxt.config.
Events
@ssr-error: Event emitted when a child triggers an error in SSR. Note that this will only be triggered on the server.
<template>

  <NuxtClientFallback @ssr-error="logSomeError">

    <!-- ... -->

  </NuxtClientFallback>

</template>

Props
placeholderTag | fallbackTag: Specify a fallback tag to be rendered if the slot fails to render.
type: string
default: div
placeholder | fallback: Specify fallback content to be rendered if the slot fails to render.
type: string
keepFallback: Keep the fallback content if it failed to render server-side.
type: boolean
default: false
  <template>

    <!-- render <span>Hello world</span> server-side if the default slot fails to render -->

    <NuxtClientFallback fallback-tag="span" fallback="Hello world">

      <BrokeInSsr />

    </NuxtClientFallback>

  </template>

Slots
#fallback: specify content to be displayed server-side if the slot fails to render.
<template>

  <NuxtClientFallback>

    <!-- ... -->

    <template #fallback>

      <!-- this will be rendered on server side if the default slot fails to render in ssr -->

      <p>Hello world</p>

    </template>

  </NuxtClientFallback>

</template>


<ClientOnly>

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

<NuxtPage>

The <NuxtPage> component is required to display pages located in the pages/ directory.
Migrate to Nuxt 3: Modules

Upgrade Guide
Migrate to Nuxt 3
Modules

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

Module Compatibility

Nuxt 3 has a basic backward compatibility layer for Nuxt 2 modules using @nuxt/kit auto wrappers. But there are usually steps to follow to make modules compatible with Nuxt 3 and sometimes, using Nuxt Bridge is required for cross-version compatibility.

We have prepared a Dedicated Guide for authoring Nuxt 3 ready modules using @nuxt/kit. Currently best migration path is to follow it and rewrite your modules. Rest of this guide includes preparation steps if you prefer to avoid a full rewrite yet making modules compatible with Nuxt 3.

Explore Nuxt 3 compatible modules.
Plugin Compatibility

Nuxt 3 plugins are not fully backward compatible with Nuxt 2.

 Read more in Docs > Guide > Directory Structure > Plugins.
Vue Compatibility

Plugins or components using the Composition API need exclusive Vue 2 or Vue 3 support.

By using vue-demi they should be compatible with both Nuxt 2 and 3.

Module Migration

When Nuxt 3 users add your module, you will not have access to the module container (this.*) so you will need to use utilities from @nuxt/kit to access the container functionality.

Test with @nuxt/bridge

Migrating to @nuxt/bridge is the first and most important step for supporting Nuxt 3.

If you have a fixture or example in your module, add @nuxt/bridge package to its config (see example)

Migrate from CommonJS to ESM

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

Ensure Plugins Default Export

If you inject a Nuxt plugin that does not have export default (such as global Vue plugins), ensure you add export default () => { } to the end of it.

Before
After
// ~/plugins/vuelidate.js

import Vue from 'vue'

import Vuelidate from 'vuelidate'



Vue.use(Vuelidate)

Avoid Runtime Modules

With Nuxt 3, Nuxt is now a build-time-only dependency, which means that modules shouldn't attempt to hook into the Nuxt runtime.

Your module should work even if it's only added to buildModules (instead of modules). For example:

Avoid updating process.env within a Nuxt module and reading by a Nuxt plugin; use runtimeConfig instead.
(*) Avoid depending on runtime hooks like vue-renderer:* for production
(*) Avoid adding serverMiddleware by importing them inside the module. Instead, add them by referencing a file path so that they are independent of the module's context

(*) Unless it is for nuxt dev purpose only and guarded with if (nuxt.options.dev) { }.

Continue reading about Nuxt 3 modules in the Modules Author Guide.
Use TypeScript (Optional)

While it is not essential, most of the Nuxt ecosystem is shifting to use TypeScript, so it is highly recommended to consider migration.

You can start migration by renaming .js files, to .ts. TypeScript is designed to be progressive!
You can use TypeScript syntax for Nuxt 2 and 3 modules and plugins without any extra dependencies.

Server

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

Hello World

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

Examples
Advanced
useCookie

This example shows how to use the useCookie API to persist small amounts of data that both client and server can use.

 Read more in Docs > API > Composables > Use Cookie.
Loading Sandbox...

Testing

This example shows how to test your Nuxt application.

Use Custom Fetch Composable

This example shows a convenient wrapper for the useFetch composable from nuxt. It allows you to customize the fetch request with default values and user authentication token.
Module Extend Pages · Nuxt Examples

Examples
Advanced
Module Extend Pages

This example defines a new `test` page using `extendPages` within a module.

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

Locale

This example shows how to define a locale composable to handle the application's locale, both server and client side.

Teleport

This example shows how to use the <Teleport> with client-side and server-side rendering.
Use Custom Fetch Composable · Nuxt Examples

Examples
Advanced
Use Custom Fetch Composable

This example shows a convenient wrapper for the useFetch composable from nuxt. It allows you to customize the fetch request with default values and user authentication token.

Loading Sandbox...

useCookie

This example shows how to use the useCookie API to persist small amounts of data that both client and server can use.

WASM

This example demonstrates the server-side support of WebAssembly in Nuxt 3.
JSX / TSX · Nuxt Examples

Examples
Advanced
JSX / TSX

This example shows how to use JSX syntax with typescript in Nuxt pages and components.

 Read more in https://vuejs.org/guide/extras/render-function.html#jsx-tsx.
Loading Sandbox...

Error Handling

This example shows how to handle errors in different contexts: pages, plugins, components and middleware.

Locale

This example shows how to define a locale composable to handle the application's locale, both server and client side.
Teleport · Nuxt Examples

Examples
Advanced
Teleport

This example shows how to use the <Teleport> with client-side and server-side rendering.

Vue 3 provides the <Teleport> component which allows content to be rendered elsewhere in the DOM, outside of the Vue application.

This example shows how to use the <Teleport> with client-side and server-side rendering.

 Read more in Docs > API > Components > Teleports.
Loading Sandbox...

Module Extend Pages

This example defines a new `test` page using `extendPages` within a module.

Testing

This example shows how to test your Nuxt application.
Locale · Nuxt Examples

Examples
Advanced
Locale

This example shows how to define a locale composable to handle the application's locale, both server and client side.

You can right-click to "View Page Source" and see that Nuxt renders the correct date in SSR based on the visitor's locale.
Loading Sandbox...

JSX / TSX

This example shows how to use JSX syntax with typescript in Nuxt pages and components.

Module Extend Pages

This example defines a new `test` page using `extendPages` within a module.
Error Handling · Nuxt Examples

Examples
Advanced
Error Handling

This example shows how to handle errors in different contexts: pages, plugins, components and middleware.

 Read more in Docs > Getting Started > Error Handling.
Loading Sandbox...

Layers

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

JSX / TSX

This example shows how to use JSX syntax with typescript in Nuxt pages and components.
Pages · Nuxt Examples

Examples
Routing
Pages

This example shows how to use the pages/ directory to create application routes.

 Read more in Docs > Guide > Directory Structure > Pages.
Loading Sandbox...

Middleware

This example shows how to add route middleware with the middleware/ directory or with a plugin, and how to use them globally or per page.

Universal Router

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

Examples
Features
Layouts

This example shows how to define default and custom layouts.

 Read more in Docs > Getting Started > Views #layouts.
 Read more in Docs > Guide > Directory Structure > Layouts.
Loading Sandbox...

Meta Tags

This example shows how to use the Nuxt helpers and composables for SEO and meta management.

Middleware

This example shows how to add route middleware with the middleware/ directory or with a plugin, and how to use them globally or per page.
Meta Tags · Nuxt Examples

Examples
Features
Meta Tags

This example shows how to use the Nuxt helpers and composables for SEO and meta management.

 Read more in Docs > Getting Started > Seo Meta.
Loading Sandbox...

State Management

This example shows how to use the `useState` composable to create a reactive and SSR-friendly shared state across components.

Layouts

This example shows how to define default and custom layouts.
State Management · Nuxt Examples

Examples
Features
State Management

This example shows how to use the `useState` composable to create a reactive and SSR-friendly shared state across components.

 Read more in Docs > Getting Started > State Management.
 Read more in Docs > API > Composables > Use State.
Loading Sandbox...

Data Fetching

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

Meta Tags

This example shows how to use the Nuxt helpers and composables for SEO and meta management.
Data Fetching · Nuxt Examples

Examples
Features
Data Fetching

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

 Read more in Docs > Getting Started > Data Fetching.
 Read more in Docs > Guide > Directory Structure > Server.
Loading Sandbox...

Auto Imports

This example demonstrates the auto-imports feature in Nuxt.

State Management

This example shows how to use the `useState` composable to create a reactive and SSR-friendly shared state across components.
Hello World · Nuxt Examples

Examples
Hello World

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

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

Modules

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

Auto Imports

This example demonstrates the auto-imports feature in Nuxt.
Nightly Release Channel · Nuxt Advanced

Guide
Going Further
Nightly Release Channel

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

Nuxt lands commits, improvements, and bug fixes every day. You can opt in to test them earlier before the next release.

After a commit is merged into the main branch of nuxt/nuxt and passes all tests, we trigger an automated npm release, using GitHub Actions.

You can use these 'nightly' releases to beta test new features and changes.

The build and publishing method and quality of these 'nightly' releases are the same as stable ones. The only difference is that you should often check the GitHub repository for updates. There is a slight chance of regressions not being caught during the review process and by the automated tests. Therefore, we internally use this channel to double-check everything before each release.

Features that are only available on the nightly release channel are marked with an alert in the documentation.
Opting In

Update nuxt dependency inside package.json:

package.json
{

  "devDependencies": {

--    "nuxt": "^3.0.0"

++    "nuxt": "npm:nuxt-nightly@latest"

  }

}


Remove lockfile (package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb) and reinstall dependencies.

Opting Out

Update nuxt dependency inside package.json:

package.json
{

  "devDependencies": {

--    "nuxt": "npm:nuxt-nightly@latest"

++    "nuxt": "^3.0.0"

  }

}


Remove lockfile (package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb) and reinstall dependencies.

Using Nightly nuxi
All cli dependencies are bundled because of the building method for reducing nuxi package size.
You can get dependency updates and CLI improvements using the nightly release channel.

To try the latest version of nuxt/cli:

Terminal
npx nuxi-nightly@latest [command]

Read more about the available commands.

Runtime Config

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

<ClientOnly>

Render components only in client-side with the <ClientOnly> component.
Debugging · Nuxt Advanced

Guide
Going Further
Debugging

In Nuxt 3, you can get started with debugging your application directly in the browser as well as in your IDE.

Sourcemaps

Sourcemaps are enabled for your server build by default, and for the client build in dev mode, but you can enable them more specifically in your configuration.

export default defineNuxtConfig({

  // or sourcemap: true

  sourcemap: {

    server: true,

    client: true

  }

})

Debugging in Your IDE

It is possible to debug your Nuxt app in your IDE while you are developing it.

Example VS Code Debug Configuration

You may need to update the config below with a path to your web browser. For more information, visit the VS Code documentation about debug configuration.

{

  // Use IntelliSense to learn about possible attributes.

  // Hover to view descriptions of existing attributes.

  "version": "0.2.0",

  "configurations": [

    {

      "type": "chrome",

      "request": "launch",

      "name": "client: chrome",

      "url": "http://localhost:3000",

      "webRoot": "${workspaceFolder}"

    },

    {

      "type": "node",

      "request": "launch",

      "name": "server: nuxt",

      "outputCapture": "std",

      "program": "${workspaceFolder}/node_modules/nuxi/bin/nuxi.mjs",

      "args": [

        "dev"

      ],

    }

  ],

  "compounds": [

    {

      "name": "fullstack: nuxt",

      "configurations": [

        "server: nuxt",

        "client: chrome"

      ]

    }

  ]

}


If you prefer your usual browser extensions, add this to the chrome configuration above:

"userDataDir": false,

Example JetBrains IDEs Debug Configuration

You can also debug your Nuxt app in JetBrains IDEs such as IntelliJ IDEA, WebStorm, or PhpStorm.

Create a new file in your project root directory and name it nuxt.run.xml.
Open the nuxt.run.xml file and paste the following debug configuration:
<component name="ProjectRunConfigurationManager">

  <configuration default="false" name="client: chrome" type="JavascriptDebugType" uri="http://localhost:3000" useFirstLineBreakpoints="true">

    <method v="2" />

  </configuration>



  <configuration default="false" name="server: nuxt" type="NodeJSConfigurationType" application-parameters="dev" path-to-js-file="$PROJECT_DIR$/node_modules/nuxi/bin/nuxi.mjs" working-dir="$PROJECT_DIR$">

    <method v="2" />

  </configuration>



  <configuration default="false" name="fullstack: nuxt" type="CompoundRunConfigurationType">

    <toRun name="client: chrome" type="JavascriptDebugType" />

    <toRun name="server: nuxt" type="NodeJSConfigurationType" />

    <method v="2" />

  </configuration>

</component>

Other IDEs

If you have another IDE and would like to contribute sample configuration, feel free to open a PR!

Custom Routing

In Nuxt 3, your routing is defined by the structure of your files inside the pages directory. However, since it uses vue-router under the hood, Nuxt offers you several ways to add custom routes in your project.

Runtime Config

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

Guide
Going Further
NuxtApp
Source

In Nuxt 3, you can access runtime app context within composables, components and plugins.

In Nuxt 3, you can access runtime app context within composables, components and plugins.

In Nuxt 2, this was referred to as Nuxt context.
Nuxt App Interface
Jump over the NuxtApp interface documentation.
Accessing NuxtApp

Within composables, plugins and components you can access nuxtApp with useNuxtApp():

composables/useMyComposable.ts
export function useMyComposable () {

  const nuxtApp = useNuxtApp()

  // access runtime nuxt app instance

}


Plugins also receive nuxtApp as the first argument for convenience.

 Read more in Docs > Guide > Directory Structure > Plugins.
Providing Helpers

You can provide helpers to be usable across all composables and application. This usually happens within a Nuxt plugin.

const nuxtApp = useNuxtApp()

nuxtApp.provide('hello', (name) => `Hello ${name}!`)



console.log(nuxtApp.$hello('name')) // Prints "Hello name!"

It is possible to inject helpers by returning an object with a provide key in plugins.
In Nuxt 2 plugins, this was referred to as inject function.

Nuxt Kit

@nuxt/kit provides features for module authors.

Authoring Nuxt Layers

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

Guide
Going Further
Nuxt Kit

@nuxt/kit provides features for module authors.

Nuxt Kit provides composable utilities to make interacting with Nuxt Hooks, the Nuxt Interface and developing Nuxt Modules super easy.

Discover all Nuxt Kit utilities.
Usage
Install Dependency

You can install the latest Nuxt Kit by adding it to the dependencies section of your package.json. However, please consider always explicitly installing the @nuxt/kit package even if it is already installed by Nuxt.

package.json
{

  "dependencies": {

    "@nuxt/kit": "npm:@nuxt/kit-nightly@latest"

  }

}

Import Kit Utilities
test.mjs
import { useNuxt } from '@nuxt/kit'

 Read more in Docs > API > Kit.
Nuxt Kit utilities are only available for modules and not meant to be imported in runtime (components, Vue composables, pages, plugins, or server routes).

Nuxt Kit is an esm-only package meaning that you cannot require('@nuxt/kit'). As a workaround, use dynamic import in the CommonJS context:

test.cjs
// This does NOT work!

// const kit = require('@nuxt/kit')

async function main() {

  const kit = await import('@nuxt/kit')

}

main()


Module Author Guide

Learn how to create a Nuxt Module to integrate, enhance or extend any Nuxt applications.

NuxtApp

In Nuxt 3, you can access runtime app context within composables, components and plugins.
Lifecycle Hooks · Nuxt Advanced

Guide
Going Further
Lifecycle Hooks

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

The hooking system is powered by unjs/hookable.
Nuxt Hooks (Build Time)

These hooks are available for Nuxt Modules and build context.

Within nuxt.config
nuxt.config
export default defineNuxtConfig({

  hooks: {

    close: () => { }

  }

})

Within Nuxt Modules
import { defineNuxtModule } from '@nuxt/kit'



export default defineNuxtModule({

  setup (options, nuxt) {

    nuxt.hook('close', async () => { })

  }

})

Explore all available Nuxt hooks.
App Hooks (Runtime)

App hooks can be mainly used by Nuxt Plugins to hook into rendering lifecycle but could also be used in Vue composables.

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

  nuxtApp.hook('page:start', () => {

    /* your code goes here */

  })

})

Explore all available App hooks.
Server Hooks (Runtime)

These hooks are available for server plugins to hook into Nitro's runtime behavior.

~/server/plugins/test.ts
export default defineNitroPlugin((nitroApp) => {

  nitroApp.hooks.hook('render:html', (html, { event }) => {

    console.log('render:html', html)

    html.bodyAppend.push('<hr>Appended by custom plugin')

  })



  nitroApp.hooks.hook('render:response', (response, { event }) => {

    console.log('render:response', response)

  })

})

Learn more about available Nitro lifecycle hooks.
Additional Hooks

You can add additional hooks by augmenting the types provided by Nuxt. This can be useful for modules.

import { HookResult } from "@nuxt/schema";



declare module '#app' {

  interface RuntimeNuxtHooks {

    'your-nuxt-runtime-hook': () => HookResult

  }

  interface NuxtHooks {

    'your-nuxt-hook': () => HookResult

  }

}



declare module 'nitropack' {

  interface NitroRuntimeHooks {

    'your-nitro-hook': () => void;

  }

}


How Nuxt Works?

Nuxt is a minimal but highly customizable framework to build web applications.

Module Author Guide

Learn how to create a Nuxt Module to integrate, enhance or extend any Nuxt applications.