0
0
Vueframework~5 mins

Navigation guards (beforeEach, beforeEnter) in Vue

Choose your learning style9 modes available
Introduction

Navigation guards help control access to pages in a Vue app. They let you check or stop navigation before it happens.

To check if a user is logged in before entering a page.
To show a warning before leaving a form with unsaved changes.
To redirect users from old URLs to new ones.
To load data before showing a page.
To block access to admin pages for regular users.
Syntax
Vue
router.beforeEach((to, from, next) => {
  // code to run before every route change
  next()
})

const route = {
  path: '/secret',
  component: SecretPage,
  beforeEnter: (to, from, next) => {
    // code to run before entering this route
    next()
  }
}

beforeEach runs before every route change in the app.

beforeEnter runs only before entering a specific route.

Examples
Redirects to login if the page needs login and user is not logged in.
Vue
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !userLoggedIn()) {
    next('/login')
  } else {
    next()
  }
})
Blocks access to admin page if user is not an admin.
Vue
const route = {
  path: '/admin',
  component: AdminPage,
  beforeEnter: (to, from, next) => {
    if (!isAdminUser()) {
      next('/not-authorized')
    } else {
      next()
    }
  }
}
Sample Program

This Vue router setup uses beforeEach to log every navigation. The beforeEnter guard on the dashboard route checks if the user is logged in. If not, it redirects to login.

Vue
import { createRouter, createWebHistory } from 'vue-router'
import HomePage from './HomePage.vue'
import LoginPage from './LoginPage.vue'
import DashboardPage from './DashboardPage.vue'

const routes = [
  { path: '/', component: HomePage },
  { path: '/login', component: LoginPage },
  {
    path: '/dashboard',
    component: DashboardPage,
    meta: { requiresAuth: true },
    beforeEnter: (to, from, next) => {
      if (!isUserLoggedIn()) {
        next('/login')
      } else {
        next()
      }
    }
  }
]

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

function isUserLoggedIn() {
  // Simulate user login status
  return false
}

router.beforeEach((to, from, next) => {
  console.log(`Navigating from ${from.path} to ${to.path}`)
  next()
})

export default router
OutputSuccess
Important Notes

Always call next() to continue navigation or redirect.

Use beforeEach for global checks and beforeEnter for route-specific checks.

Navigation guards help improve app security and user experience.

Summary

Navigation guards run code before changing pages.

beforeEach runs for every route change.

beforeEnter runs only for a specific route.