From 1f0e400705f54b21c4e821423c1a8bc53672c544 Mon Sep 17 00:00:00 2001 From: Andrey Yolkin Date: Thu, 17 Aug 2023 00:58:40 +0300 Subject: [PATCH] feat(docs): `addRouteMiddleware` --- docs/3.api/4.advanced/2.kit.md | 92 +++++++++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/docs/3.api/4.advanced/2.kit.md b/docs/3.api/4.advanced/2.kit.md index 41811a7989..7a328752bb 100644 --- a/docs/3.api/4.advanced/2.kit.md +++ b/docs/3.api/4.advanced/2.kit.md @@ -1397,7 +1397,97 @@ export default defineNuxtModule({ }) ``` -- `addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions)` +### `addRouteMiddleware` + +Route middleware functions within the Vue section of your Nuxt application. Distinct from server middleware, these middlewares are specifically for the Vue side. They enable you to incorporate specific logic to your routes, such as authentication and authorization. You can define these middlewares within a Nuxt module via this utility. + +::alert{type=info icon=👉} +Read more about route middlewares in the [Route middleware documentation](/docs/getting-started/routing#route-middleware). +:: + +#### Type + +```ts +function addRouteMiddleware (input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions) + +type NuxtMiddleware = { + name: string + path: string + global?: boolean +} + +interface AddRouteMiddlewareOptions { + override?: boolean +} +``` + +#### Parameters + +##### `input` + +**Type**: `NuxtMiddleware | NuxtMiddleware[]` + +**Required**: `true` + +A middleware object or an array of middleware objects with the following properties: + +- `name` (required) + + **Type**: `string` + + Middleware name. + +- `path` (required) + + **Type**: `string` + + Path to the middleware. + +- `global` (optional) + + **Type**: `boolean` + + If enabled, registers middleware to be available for all routes. + +##### `options` + +**Type**: `AddRouteMiddlewareOptions` + +**Default**: `{}` + +Options to pass to the middleware. If `override` is set to `true`, it will override the existing middleware with the same name. + +#### Examples + +::code-group + +```ts [runtime/auth.ts] +export default defineNuxtRouteMiddleware((to, from) => { + // isAuthenticated() is an example method verifying if a user is authenticated + if (isAuthenticated() === false) { + return navigateTo('/login') + } +}) +``` + +```ts +import { createResolver, defineNuxtModule, addRouteMiddleware } from '@nuxt/kit' + +export default defineNuxtModule({ + setup() { + const resolver = createResolver(import.meta.url) + + addRouteMiddleware({ + name: 'auth', + path: resolver.resolve('runtime/auth.ts'), + global: true + }) + } +}) +``` + +:: + ## Plugins