1
0
mirror of https://github.com/nuxt/nuxt.git synced 2024-12-04 19:37:18 +00:00
Nuxt/docs/3.api/3.utils/add-route-middleware.md
Sébastien Chopin f26a801775
docs: update to new website ()
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Roe <daniel@roe.dev>
2023-10-18 12:59:43 +02:00

2.6 KiB

title description links
addRouteMiddleware addRouteMiddleware() is a helper function to dynamically add middleware in your application.
label icon to size
Source i-simple-icons-github https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/router.ts xs

::callout Route middleware are navigation guards stored in the middleware/ directory of your Nuxt application (unless set otherwise). ::

Type

addRouteMiddleware (name: string | RouteMiddleware, middleware?: RouteMiddleware, options: AddRouteMiddlewareOptions = {})

Parameters

name

  • Type: string | RouteMiddleware

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

Learn more about available properties of route objects.

middleware

  • Type: RouteMiddleware

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

options

  • Type: AddRouteMiddlewareOptions

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

Examples

Anonymous Route Middleware

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

export default defineNuxtPlugin(() => {
  addRouteMiddleware((to, from) => {
    if (to.path === '/forbidden') {
      return false
    }
  })
})

Named Route Middleware

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

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

export default defineNuxtPlugin(() => {
  addRouteMiddleware('named-middleware', () => {
    console.log('named middleware added in Nuxt plugin')
  })
})

Global Route Middleware

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

export default defineNuxtPlugin(() => {
  addRouteMiddleware('global-middleware', (to, from) => {
      console.log('global middleware that runs on every route change')
    },
    { global: true }
  )
})