2022-10-06 09:15:30 +00:00
---
2023-10-18 10:59:43 +00:00
title: 'abortNavigation'
description: 'abortNavigation is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.'
links:
- label: Source
icon: i-simple-icons-github
to: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/router.ts
size: xs
2022-10-06 09:15:30 +00:00
---
2024-02-21 17:09:45 +00:00
::warning
2022-11-16 10:04:28 +00:00
`abortNavigation` is only usable inside a [route middleware handler ](/docs/guide/directory-structure/middleware ).
2022-08-26 10:54:52 +00:00
::
## Type
2022-04-07 13:46:30 +00:00
```ts
abortNavigation(err?: Error | string): false
```
2022-08-26 10:54:52 +00:00
## Parameters
2022-04-07 13:46:30 +00:00
2022-08-26 10:54:52 +00:00
### `err`
- **Type**: [`Error` ](https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Error ) | `string`
2023-06-05 15:03:06 +00:00
Optional error to be thrown by `abortNavigation` .
2022-08-26 10:54:52 +00:00
## Examples
The example below shows how you can use `abortNavigation` in a route middleware to prevent unauthorized route access:
2022-04-06 05:56:08 +00:00
2022-08-26 10:54:52 +00:00
```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
const user = useState('user')
if (!user.value.isAuthorized) {
return abortNavigation()
}
2024-02-21 17:09:45 +00:00
2023-05-04 14:08:07 +00:00
if (to.path !== '/edit-post') {
return navigateTo('/edit-post')
}
2022-08-26 10:54:52 +00:00
})
```
### `err` as a String
You can pass the error as a string:
```ts [middleware/auth.ts]
export default defineNuxtRouteMiddleware((to, from) => {
2023-06-12 08:45:53 +00:00
const user = useState('user')
2022-08-26 10:54:52 +00:00
if (!user.value.isAuthorized) {
2023-03-22 11:07:02 +00:00
return abortNavigation('Insufficient permissions.')
2022-08-26 10:54:52 +00:00
}
})
```
### `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) {
2023-03-22 11:07:02 +00:00
return abortNavigation(err)
2022-08-26 10:54:52 +00:00
}
})
```