Navigation Guards

As the name suggests, the navigation guards provided by Vue router are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component.

Global Before Guards

You can register global before guards using router.beforeEach:

  1. const router = createRouter({ ... })
  2. router.beforeEach((to, from) => {
  3. // ...
  4. // explicitly return false to cancel the navigation
  5. return false
  6. })

Global before guards are called in creation order, whenever a navigation is triggered. Guards may be resolved asynchronously, and the navigation is considered pending before all hooks have been resolved.

Every guard function receives two arguments:

And can optionally return any of the following values:

  • false: cancel the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.
  • A Route Location: Redirect to a different location by passing a route location as if you were calling router.push(), which allows you to pass options like replace: true or name: 'home'. The current navigation is dropped and a new one is created with the same from.

It’s also possible to throw an Error if an unexpected situation was met. This will also cancel the navigation and call any callback registered via router.onError().

If nothing, undefined or true is returned, the navigation is validated, and the next navigation guard is called.

All of the the things above work the same way with async functions and Promises:

  1. router.beforeEach(async (to, from) => {
  2. // canUserAccess() returns `true` or `false`
  3. const canAccess = await canUserAccess(to)
  4. if (!canAccess) return '/login'
  5. })

Optional third argument next

In previous versions of Vue Router, it was also possible to use a third argument next, this was a common source of mistakes and went through an RFC to remove it. However, it is still supported, meaning you can pass a third argument to any navigation guard. In that case, you must call next exactly once in any given pass through a navigation guard. It can appear more than once, but only if the logical paths have no overlap, otherwise the hook will never be resolved or produce errors. Here is a bad example of redirecting to user to /login if they are not authenticated:

  1. // BAD
  2. router.beforeEach((to, from, next) => {
  3. if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  4. // if the user is not authenticated, `next` is called twice
  5. next()
  6. })

Here is the correct version:

  1. // GOOD
  2. router.beforeEach((to, from, next) => {
  3. if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  4. else next()
  5. })

Global Resolve Guards

You can register a global guard with router.beforeResolve. This is similar to router.beforeEach because it triggers on every navigation, but resolve guards are called right before the navigation is confirmed, after all in-component guards and async route components are resolved. Here is an example that ensures the user has given access to the Camera for routes that have defined a custom meta property requiresCamera:

  1. router.beforeResolve(async to => {
  2. if (to.meta.requiresCamera) {
  3. try {
  4. await askForCameraPermission()
  5. } catch (error) {
  6. if (error instanceof NotAllowedError) {
  7. // ... handle the error and then cancel the navigation
  8. return false
  9. } else {
  10. // unexpected error, cancel the navigation and pass the error to the global handler
  11. throw error
  12. }
  13. }
  14. }
  15. })

router.beforeResolve is the ideal spot to fetch data or do any other operation that you want to avoid doing if the user cannot enter a page.

Global After Hooks

You can also register global after hooks, however unlike guards, these hooks do not get a next function and cannot affect the navigation:

  1. router.afterEach((to, from) => {
  2. sendToAnalytics(to.fullPath)
  3. })

They are useful for analytics, changing the title of the page, accessibility features like announcing the page and many other things.

They also reflect navigation failures as the third argument:

  1. router.afterEach((to, from, failure) => {
  2. if (!failure) sendToAnalytics(to.fullPath)
  3. })

Learn more about navigation failures on its guide.

Per-Route Guard

You can define beforeEnter guards directly on a route’s configuration object:

  1. const routes = [
  2. {
  3. path: '/users/:id',
  4. component: UserDetails,
  5. beforeEnter: (to, from) => {
  6. // reject the navigation
  7. return false
  8. },
  9. },
  10. ]

beforeEnter guards only trigger when entering the route, they don’t trigger when the params, query or hash change e.g. going from /users/2 to /users/3 or going from /users/2#info to /users/2#projects. They are only triggered when navigating from a different route.

You can also pass an array of functions to beforeEnter, this is useful when reusing guards for different routes:

  1. function removeQueryParams(to) {
  2. if (Object.keys(to.query).length)
  3. return { path: to.path, query: {}, hash: to.hash }
  4. }
  5. function removeHash(to) {
  6. if (to.hash) return { path: to.path, query: to.query, hash: '' }
  7. }
  8. const routes = [
  9. {
  10. path: '/users/:id',
  11. component: UserDetails,
  12. beforeEnter: [removeQueryParams, removeHash],
  13. },
  14. {
  15. path: '/about',
  16. component: UserDetails,
  17. beforeEnter: [removeQueryParams],
  18. },
  19. ]

Note it is possible to achieve a similar behavior by using route meta fields and global navigation guards.

In-Component Guards

Finally, you can directly define route navigation guards inside route components (the ones passed to the router configuration)

Using the options API

You can add the following options to route components:

  • beforeRouteEnter
  • beforeRouteUpdate
  • beforeRouteLeave
  1. const UserDetails = {
  2. template: `...`,
  3. beforeRouteEnter(to, from) {
  4. // called before the route that renders this component is confirmed.
  5. // does NOT have access to `this` component instance,
  6. // because it has not been created yet when this guard is called!
  7. },
  8. beforeRouteUpdate(to, from) {
  9. // called when the route that renders this component has changed,
  10. // but this component is reused in the new route.
  11. // For example, given a route with params `/users/:id`, when we
  12. // navigate between `/users/1` and `/users/2`, the same `UserDetails` component instance
  13. // will be reused, and this hook will be called when that happens.
  14. // Because the component is mounted while this happens, the navigation guard has access to `this` component instance.
  15. },
  16. beforeRouteLeave(to, from) {
  17. // called when the route that renders this component is about to
  18. // be navigated away from.
  19. // As with `beforeRouteUpdate`, it has access to `this` component instance.
  20. },
  21. }

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:

  1. beforeRouteEnter (to, from, next) {
  2. next(vm => {
  3. // access to component public instance via `vm`
  4. })
  5. }

Note that beforeRouteEnter is the only guard that supports passing a callback to next. For beforeRouteUpdate and beforeRouteLeave, this is already available, so passing a callback is unnecessary and therefore not supported:

  1. beforeRouteUpdate (to, from) {
  2. // just use `this`
  3. this.name = to.params.name
  4. }

The leave guard is usually used to prevent the user from accidentally leaving the route with unsaved edits. The navigation can be canceled by returning false.

  1. beforeRouteLeave (to, from) {
  2. const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
  3. if (!answer) return false
  4. }

Using the composition API

If you are writing your component using the composition API and a setup function, you can add update and leave guards through onBeforeRouteUpdate and onBeforeRouteLeave respectively. Please refer to the Composition API section for more details.

The Full Navigation Resolution Flow

  1. Navigation triggered.
  2. Call beforeRouteLeave guards in deactivated components.
  3. Call global beforeEach guards.
  4. Call beforeRouteUpdate guards in reused components.
  5. Call beforeEnter in route configs.
  6. Resolve async route components.
  7. Call beforeRouteEnter in activated components.
  8. Call global beforeResolve guards.
  9. Navigation is confirmed.
  10. Call global afterEach hooks.
  11. DOM updates triggered.
  12. Call callbacks passed to next in beforeRouteEnter guards with instantiated instances.