0
0
VueHow-ToBeginner · 3 min read

How to Use beforeEach in Vue Router for Navigation Guards

Use router.beforeEach to register a global navigation guard in Vue Router that runs before every route change. It receives to, from, and next arguments to control navigation flow by calling next() to proceed or redirect.
📐

Syntax

The beforeEach method registers a global guard that runs before every route change. It takes a callback with three parameters:

  • to: the target Route Object being navigated to
  • from: the current Route Object being navigated away from
  • next: a function to resolve the navigation, which you must call to continue or redirect

Calling next() allows navigation to proceed. Calling next(false) cancels navigation. Calling next('/path') redirects to a different route.

javascript
router.beforeEach((to, from, next) => {
  // your logic here
  next(); // proceed
});
💻

Example

This example shows how to protect a route by checking if a user is logged in before allowing navigation. If not logged in, it redirects to the login page.

javascript
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  { path: '/', component: () => import('./Home.vue') },
  { path: '/dashboard', component: () => import('./Dashboard.vue'), meta: { requiresAuth: true } },
  { path: '/login', component: () => import('./Login.vue') }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// Simulated auth check
function isLoggedIn() {
  return false; // change to true to simulate logged in
}

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login'); // redirect to login if not authenticated
  } else {
    next(); // allow navigation
  }
});

export default router;
Output
Navigating to '/dashboard' redirects to '/login' if not logged in; otherwise, it proceeds to '/dashboard'.
⚠️

Common Pitfalls

Common mistakes when using beforeEach include:

  • Not calling next() or calling it multiple times, which blocks navigation or causes errors.
  • Forgetting to handle asynchronous checks properly, causing navigation to hang.
  • Using beforeEach for route-specific guards instead of beforeEnter or component guards.
javascript
router.beforeEach((to, from, next) => {
  // Wrong: missing next call blocks navigation
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login');
  }
  // next() missing here causes hang
});

// Correct way
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login');
  } else {
    next();
  }
});
📊

Quick Reference

beforeEach Navigation Guard Cheat Sheet:

MethodPurpose
router.beforeEach(callback)Runs before every route change globally
next()Continue navigation
next(false)Cancel navigation
next('/path')Redirect to another route
MethodPurpose
router.beforeEach(callback)Runs before every route change globally
next()Continue navigation
next(false)Cancel navigation
next('/path')Redirect to another route

Key Takeaways

Use router.beforeEach to run code before every route change in Vue Router.
Always call next() exactly once to resolve navigation and avoid blocking.
Use next('/path') to redirect and next(false) to cancel navigation.
beforeEach is global; use route or component guards for specific routes.
Handle async checks carefully to prevent navigation from hanging.