Nuxt/docs/content/3.docs/3.migration/5.plugins-and-middleware.md
Daniel Roe 1a39eff502
docs: update migration guide for nuxt 3 (#3819)
Co-authored-by: Dan Pastori <dan@521dimensions.com>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
Co-authored-by: pooya parsa <pyapar@gmail.com>
2022-03-30 19:32:30 +02:00

2.3 KiB

Plugins and Middleware

Plugins

Plugins now have a different format, and take only one argument (nuxtApp). Read more in the docs.

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

::

::alert{icon=👉} You can read more about the format of nuxtApp in the docs. ::

Migration

  1. Migrate your plugins to use the defineNuxtPlugin helper function.
  2. 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.

::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, which you can read more about in the documentation about route middleware.

Migration

  1. Migrate your route middleware to use the defineNuxtRouteMiddleware helper function.
  2. 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.