Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

docs(api): add defineNuxtRouteMiddleware util #6933

Merged
merged 5 commits into from
Aug 26, 2022
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 58 additions & 3 deletions docs/content/3.api/3.utils/define-nuxt-route-middleware.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,62 @@
# `defineNuxtRouteMiddleware`

::ReadMore{link="/guide/features/routing"}
::
You can create named route middleware using `defineNuxtRouteMiddleware` helper function.

Route middleware are stored in the `middleware/` directory of your Nuxt application (unless [set otherwise](/api/configuration/nuxt.config#middleware)).

## Type

```ts
defineNuxtRouteMiddleware(middleware: RouteMiddleware) => RouteMiddleware

interface RouteMiddleware {
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>
}
```

## Parameters

### `middleware`

- **Type**: `RouteMiddleware`

A function which takes two Vue Router's route location objects as parameters: the next route `to` as the first, and the current route `from` as the second.
pi0 marked this conversation as resolved.
Show resolved Hide resolved

Learn more about available properties of `RouteLocationNormalized` in theΒ **[Vue Router docs](https://router.vuejs.org/api/interfaces/RouteLocationNormalized.html)**.

::NeedContribution
## Examples

### Showing Error Page

You can use route middleware to throw errors and show helpful error messages:

```ts [middleware/error.ts]
export default defineNuxtRouteMiddleware((to) => {
if (to.params.id === '1') {
throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
}
})
```

The above route middleware will redirect a user to the custom error page defined in the `~/error.vue` file, and expose the error message and code passed from the middleware.

### Redirection

You can use `useState` in combination with `navigateTo` helper function inside the route middleware to redirect users to different routes based on their authentication status:

```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
const auth = useState('auth')

if (!auth.value.isAuthenticated) {
return navigateTo('/login')
}

return navigateTo('/dashboard')
})
```

Both [navigateTo](/api/utils/navigate-to) and [abortNavigation](/api/utils/abort-navigation) are globally available helper functions that you can use inside `defineNuxtRouteMiddleware`.

::ReadMore{link="/guide/features/routing"}
::