mirror of
https://github.com/nuxt/nuxt.git
synced 2024-12-25 05:37:12 +00:00
f26a801775
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Roe <daniel@roe.dev>
2.3 KiB
2.3 KiB
title | description |
---|---|
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
).
::code-group
export default (ctx, inject) => {
inject('injected', () => 'my injected function')
})
export default defineNuxtPlugin(nuxtApp => {
// now available on `nuxtApp.$injected`
nuxtApp.provide('injected', () => 'my injected function')
// You can alternatively use this format, which comes with automatic type support
return {
provide: {
injected: () => 'my injected function'
}
}
})
::
:read-more{to="/docs/guide/directory-structure/plugins"}
::read-more{to="/docs/api/composables/use-nuxt-app"}
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 yourplugins/
folder. All files in this directory at the top level (and any index files in any subdirectories) will be automatically registered. Instead of settingmode
toclient
orserver
, 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.
::code-group
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.authenticated) {
return redirect('/login')
}
}
export default defineNuxtRouteMiddleware((to, from) => {
const auth = useState('auth')
if (!auth.value.authenticated) {
return navigateTo('/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{to="/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
.