mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-14 01:53:55 +00:00
dc47c64f14
Co-authored-by: Daniel Roe <daniel@roe.dev> Co-authored-by: Sébastien Chopin <seb@nuxtjs.com> Co-authored-by: Pooya Parsa <pooya@pi0.io> Co-authored-by: pooya parsa <pyapar@gmail.com> Co-authored-by: Clément Ollivier <clement.o2p@gmail.com>
1.6 KiB
1.6 KiB
title |
---|
abortNavigation |
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.
::
Type
abortNavigation(err?: Error | string): false
Parameters
err
-
Type:
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:
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:
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
object, e.g. caught by the catch
-block:
export default defineNuxtRouteMiddleware((to, from) => {
try {
/* code that might throw an error */
} catch (err) {
abortNavigation(err)
}
})