Nuxt/docs/3.api/3.utils/abort-navigation.md
Sébastien Chopin f26a801775
docs: update to new website (#23743)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Roe <daniel@roe.dev>
2023-10-18 12:59:43 +02:00

1.8 KiB

title description links
abortNavigation abortNavigation is a helper function that prevents navigation from taking place and throws an error if one is set as a parameter.
label icon to size
Source i-simple-icons-github https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/composables/router.ts xs

::callout{color="amber" icon="i-ph-warning-duotone"} 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()
  }
 
  if (to.path !== '/edit-post') {
    return navigateTo('/edit-post')
  }
})

err as a String

You 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 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) {
    return abortNavigation(err)
  }
})