vuejs
/

Vue Route Guards

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

vuejs

Vue Route Guards

What are Route Guards?

Route guards are functions that run before or during navigation to control access to routes in a Vue application.

Types of Route Guards

TypeUsage
Global GuardsApplied to all routes
Per-Route GuardsDefined inside route config
In-Component GuardsDefined inside components

Global Before Guard

JavaScriptRead-only
1
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

Per-Route Guard

JavaScriptRead-only
1
{
  path: '/admin',
  component: Admin,
  beforeEnter: (to, from, next) => {
    if (!isAdmin) next('/');
    else next();
  }
}

In-Component Guard

JavaScriptRead-only
1
beforeRouteEnter(to, from, next) {
  next(vm => {
    // access component instance
  });
}

Common Use Cases

  • Authentication check
  • Authorization control
  • Redirecting users
  • Preventing access to certain routes

Navigation Flow

Guards run in sequence before navigation is confirmed, allowing control over routing behavior.

Best Practices

  • Use global guards for auth checks
  • Keep guard logic simple
  • Avoid heavy operations in guards
  • Use meta fields for route rules

Common Mistakes

  • Forgetting to call next()
  • Blocking navigation unintentionally
  • Using complex logic inside guards
  • Not handling async operations properly

Conclusion

Route guards are essential for controlling navigation and securing routes in Vue applications.

Try it yourself

router.beforeEach((to, from, next) => { next(); });

Test Your Knowledge

Q1
of 3

Route guards used for?

A
Styling
B
Routing control
C
Database
D
API
Q2
of 3

Global guard?

A
beforeEach
B
mounted
C
created
D
updated
Q3
of 3

Must call?

A
return
B
next()
C
emit
D
bind

Frequently Asked Questions

What is a route guard?

A function that controls route navigation.

What is beforeEach?

A global route guard.

Why use route guards?

To protect routes and control access.

Previous

vue dynamic routing

Next

vue state management

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.