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

Commit

Permalink
docs(api): enhance abortNavigation util (#6936)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel Roe <daniel@roe.dev>
Co-authored-by: Damian Głowala <48835293+DamianGlowala@users.noreply.github.com>
  • Loading branch information
3 people committed Aug 26, 2022
1 parent a64c056 commit 4306bd7
Showing 1 changed file with 57 additions and 5 deletions.
62 changes: 57 additions & 5 deletions docs/content/3.api/3.utils/abort-navigation.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,68 @@
# `abortNavigation`

`abortNavigation` is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.

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

## Type

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

* **err**: Optional error to be thrown by `abortNavigation()`.
## Parameters

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

- **Type**: [`Error`](https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Error) | `string`

Optional error to be thrown by `abortNavigation`.

## Examples

The example below shows how you can use `abortNavigation` in a route middleware to prevent unauthorized route access:

Inside a route middleware handler, `abortNavigation()` will abort navigation, and throw an error if one is set as a parameter.
```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
const user = useState('user')

if (!user.value.isAuthorized) {
return abortNavigation()
}

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('Insufficient permissions.')
}
})
```

### `err` as an Error Object

You can pass the error as an [`Error`](https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Error) object, e.g. caught by the `catch`-block:

```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
try {
/* code that might throw an error */
} catch (err) {
abortNavigation(err)
}
})
```

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

0 comments on commit 4306bd7

Please sign in to comment.