Performance: Navigation guards (beforeEach, beforeEnter)
This affects page load speed and interaction responsiveness by controlling route changes and blocking navigation until checks complete.
router.beforeEach(async (to, from, next) => { try { const isAuthenticated = await asyncAuthCheck(); if (isAuthenticated) next(); else next('/login'); } catch { next('/login'); } });
router.beforeEach((to, from, next) => { // Synchronous heavy computation or blocking API call const isAuthenticated = heavyAuthCheck(); if (isAuthenticated) next(); else next('/login'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy guard | Minimal | 0 | Blocks paint until done | [X] Bad |
| Asynchronous guard with async/await | Minimal | 0 | Non-blocking paint | [OK] Good |
beforeEach navigation guard?beforeEachbeforeEach is a global navigation guard that runs before every route change in the app.beforeEnter guard to a route in Vue Router?beforeEnter as a property with a function value inside the route object.beforeEnter: function(to, from, next) { next() } which is valid. { path: '/home', component: Home, beforeEnter(to, from, next) { next() } } misses the colon. { path: '/home', component: Home, beforeEnter: (to, from, next) => { next() } } uses arrow function which is valid but less common in examples. router.beforeEnter('/home', (to, from, next) => next()) is invalid syntax for route config./dashboard?
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/login', component: Login },
{ path: '/dashboard', component: Dashboard, beforeEnter(to, from, next) {
if (!isLoggedIn()) next('/login')
else next()
} }
]
})
router.beforeEach((to, from, next) => {
console.log('Global guard')
next()
})router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
if (!userIsLoggedIn) {
next('/login')
}
}
next()
})to.meta.requiresAuth is true and user is not logged in, next('/login') is called. Then outside the if block, next() is called again unconditionally./admin/settings so that only logged-in users can access it. You have a global beforeEach guard and a route-level beforeEnter guard on /admin. Which approach correctly ensures the user is redirected to /login if not logged in, without redundant checks?beforeEach runs before every route, including nested ones. Route-level beforeEnter runs after global guards.Pass the test and this pattern moves unknown