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

docs(api): enhance abortNavigation util #6936

Merged
merged 4 commits into from
Aug 26, 2022
Merged
Changes from 2 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
52 changes: 51 additions & 1 deletion docs/content/3.api/3.utils/abort-navigation.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,66 @@
# `abortNavigation`

`abortNavigation` is a helper function that prevents the navigation from taking place.

## Usage

```ts
abortNavigation(err?: Error | string): false
```

* **err**: Optional error to be thrown by `abortNavigation()`.
`abortNavigation` takes one optional argument which can be of type `string` or an `Error` object.

- **err**: Optional error to be thrown byΒ `abortNavigation()`.

::alert{type="warning"}
`abortNavigation()` is only usable inside a [route middleware handler](/guide/directory-structure/middleware).
::

Inside a route middleware handler, `abortNavigation()` will abort navigation, and throw an error if one is set as a parameter.

## Examples

The example below shows how you can use `abortNavigation` in route middleware to prevent unauthorised route access.

```jsx
DamianGlowala marked this conversation as resolved.
Show resolved Hide resolved
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
const user = useState('user')
if (!user.value.isAuthorized) {
abortNavigation()
DamianGlowala marked this conversation as resolved.
Show resolved Hide resolved
DamianGlowala marked this conversation as resolved.
Show resolved Hide resolved
}
return navigateTo('/edit-post')
})
```

### `err` as a string

You can pass the error as a `string`.

```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
const auth = useState('auth')
if (!user.value.isAuthorized) {
abortNavigation('This feature requires special permission.')
}
})
```

### `err` as an Error object

You can pass the error as an `Error` object that includes the error code and a message.

```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
const auth = useState('auth')
if (to.params.id === '1') {
abortNavigation({
statusCode: 401,
statusMessage: 'This feature requires special permission.'
})
}
})
```

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