abortNavigation is only usable inside a route middleware handler.export function abortNavigation (err?: Error | string): false
errError | stringabortNavigation.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()
}
if (to.path !== '/edit-post') {
return navigateTo('/edit-post')
}
})
err as a StringYou can pass the error as a string:
export default defineNuxtRouteMiddleware((to, from) => {
const user = useState('user')
if (!user.value.isAuthorized) {
return abortNavigation('Insufficient permissions.')
}
})
err as an Error ObjectYou 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) {
return abortNavigation(err)
}
})