Bird
Raised Fist0
Vueframework~10 mins

Navigation guards (beforeEach, beforeEnter) in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Navigation guards (beforeEach, beforeEnter)
User tries to navigate
↓
Global beforeEach guard runs
↓
Route-specific beforeEnter guard runs
↓
Navigation completes
When a user tries to change pages, Vue runs global guards first, then route-specific guards. Each guard can allow or stop navigation.
Execution Sample
Vue
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    next('/login')
  } else {
    next()
  }
})
This code checks before every navigation if the target page needs login; if not logged in, it redirects to login.
Execution Table
StepGuard TypeCondition CheckedResultNavigation Action
1beforeEachto.meta.requiresAuth = true, isLoggedIn() = falseCondition trueRedirect to '/login'
2beforeEnter (for '/login')No special conditionAllowProceed to '/login'
3NavigationAt '/login'CompletePage loads '/login'
4User tries to go to '/dashboard'to.meta.requiresAuth = true, isLoggedIn() = trueCondition falseAllow navigation
5beforeEnter (for '/dashboard')No special conditionAllowProceed to '/dashboard'
6NavigationAt '/dashboard'CompletePage loads '/dashboard'
7User tries to go to '/public'to.meta.requiresAuth = falseCondition falseAllow navigation
8beforeEnter (for '/public')No special conditionAllowProceed to '/public'
9NavigationAt '/public'CompletePage loads '/public'
10User tries to go to '/admin'to.meta.requiresAuth = true, isLoggedIn() = falseCondition trueRedirect to '/login'
11Navigation abortedRedirectedStopNavigation stops, user redirected
💡 Navigation stops or proceeds based on guard checks; redirects cause new navigation cycle.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 7After Step 10Final
to.meta.requiresAuthvariestruetruefalsetruetrue or false depending on route
isLoggedIn()falsefalsetruetruefalsevaries
Navigation Actionnoneredirect to '/login'allowallowredirect to '/login'final navigation or redirect
Key Moments - 3 Insights
Why does navigation redirect to '/login' even though the user tried to go to '/admin'?
Because the global beforeEach guard checks if the route requires authentication and the user is not logged in (see execution_table step 10). It redirects before entering the route.
What happens if beforeEach calls next() without arguments?
Navigation continues to the next guard or the route itself (see execution_table steps 4 and 7 where next() allows navigation).
Can beforeEnter guard override the decision of beforeEach?
Yes, beforeEnter runs after beforeEach and can allow or block navigation independently (see execution_table steps 2 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what navigation action happens at step 1?
AAllow navigation to requested route
BAbort navigation without redirect
CRedirect to '/login'
DReload current page
💡 Hint
Check the 'Navigation Action' column at step 1 in the execution_table.
At which step does the user successfully navigate to '/dashboard'?
AStep 6
BStep 3
CStep 9
DStep 11
💡 Hint
Look for '/dashboard' in the 'Navigation' column in the execution_table.
If isLoggedIn() returned false at step 4, what would happen?
ANavigation would abort without redirect
BNavigation would redirect to '/login'
CNavigation would proceed to '/dashboard'
DNavigation would reload the current page
💡 Hint
Refer to the condition and action in execution_table step 1 and step 10 for similar cases.
Concept Snapshot
Vue Navigation Guards:
- beforeEach: global guard runs before every route change
- beforeEnter: route-specific guard runs before entering that route
- Guards check conditions and call next() to allow or redirect
- Navigation stops if next() is called with a redirect or false
- Guards run in order: beforeEach then beforeEnter
- Use guards to protect routes or redirect users
Full Transcript
When a user tries to change pages in a Vue app, the router runs global guards called beforeEach first. These guards check conditions like if the user is logged in. If the guard calls next() with a redirect path, navigation stops and restarts at the new path. If next() is called without arguments, navigation continues. After beforeEach, route-specific guards called beforeEnter run for the target route. They can also allow or block navigation. This process ensures only allowed users can access certain pages. The execution table shows steps where navigation is allowed or redirected based on login status and route requirements.

Practice

(1/5)
1. What is the main purpose of Vue Router's beforeEach navigation guard?
easy
A. To run a function before every route change globally
B. To run a function only after a route has been entered
C. To modify the route's component before rendering
D. To delay the route change indefinitely

Solution

  1. Step 1: Understand the role of beforeEach

    beforeEach is a global navigation guard that runs before every route change in the app.
  2. Step 2: Compare options with the guard's behavior

    To run a function before every route change globally correctly states it runs before every route change globally. Other options describe incorrect or unrelated behaviors.
  3. Final Answer:

    To run a function before every route change globally -> Option A
  4. Quick Check:

    Global guard before route change = A [OK]
Hint: beforeEach runs before every route change globally [OK]
Common Mistakes:
  • Confusing beforeEach with afterEach
  • Thinking beforeEach runs only on specific routes
  • Assuming beforeEach modifies components directly
2. Which of the following is the correct syntax to add a beforeEnter guard to a route in Vue Router?
easy
A. { path: '/home', component: Home, beforeEnter(to, from, next) { next() } }
B. { path: '/home', component: Home, beforeEnter: function(to, from, next) { next() } }
C. { path: '/home', component: Home, beforeEnter: (to, from, next) => { next() } }
D. router.beforeEnter('/home', (to, from, next) => next())

Solution

  1. Step 1: Identify correct route object syntax

    Vue Router expects beforeEnter as a property with a function value inside the route object.
  2. Step 2: Check each option's syntax

    { path: '/home', component: Home, beforeEnter: function(to, from, next) { next() } } uses 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.
  3. Final Answer:

    { path: '/home', component: Home, beforeEnter: function(to, from, next) { next() } } -> Option B
  4. Quick Check:

    Route guard syntax uses colon and function = C [OK]
Hint: Use colon and function for beforeEnter in route object [OK]
Common Mistakes:
  • Omitting colon before beforeEnter
  • Trying to call beforeEnter on router instance
  • Using arrow function without colon
3. Given this Vue Router setup, what will happen when navigating to /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()
})
medium
A. Navigation blocked with no console output
B. Console logs 'Global guard' and navigates to /dashboard regardless
C. Console logs 'Global guard' and navigates to /login if not logged in
D. Syntax error due to missing next() call

Solution

  1. Step 1: Analyze global beforeEach guard

    The global guard logs 'Global guard' and calls next(), so navigation proceeds.
  2. Step 2: Analyze route-specific beforeEnter guard

    beforeEnter checks if user is logged in. If not, it redirects to '/login'. Otherwise, it allows navigation.
  3. Final Answer:

    Console logs 'Global guard' and navigates to /login if not logged in -> Option C
  4. Quick Check:

    Global guard logs + route guard redirects if not logged in = A [OK]
Hint: Global guard runs first, then route guard decides next step [OK]
Common Mistakes:
  • Ignoring global guard console log
  • Assuming navigation always succeeds
  • Forgetting next() call in guards
4. Identify the error in this Vue Router navigation guard code:
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    if (!userIsLoggedIn) {
      next('/login')
    }
  }
  next()
})
medium
A. Missing call to next() inside the if block causes navigation to continue twice
B. userIsLoggedIn should be a function call
C. to.meta.requiresAuth is not a valid property
D. next() is called twice, causing navigation to fail

Solution

  1. Step 1: Trace next() calls in the guard

    If 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.
  2. Step 2: Understand consequences of calling next() twice

    Calling next() twice causes Vue Router to throw an error and navigation fails.
  3. Final Answer:

    next() is called twice, causing navigation to fail -> Option D
  4. Quick Check:

    Two next() calls in one guard = B [OK]
Hint: Call next() only once per guard to avoid errors [OK]
Common Mistakes:
  • Calling next() multiple times in one guard
  • Not returning after next('/login')
  • Assuming meta is always defined
5. You want to protect a nested route /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?
hard
A. Check login only in global beforeEach; remove beforeEnter guard from /admin route
B. Check login only in beforeEnter guard on /admin; global beforeEach does not check login
C. Check login in both global beforeEach and beforeEnter guard on /admin
D. Do not check login in any guard; rely on component logic

Solution

  1. Step 1: Understand guard execution order and redundancy

    Global beforeEach runs before every route, including nested ones. Route-level beforeEnter runs after global guards.
  2. Step 2: Avoid redundant login checks

    Checking login in both guards causes duplicate redirects and complexity. Checking only in global guard covers all routes.
  3. Final Answer:

    Check login only in global beforeEach; remove beforeEnter guard from /admin route -> Option A
  4. Quick Check:

    Single global guard for login check avoids redundancy = A [OK]
Hint: Use global guard for login checks to avoid duplicate logic [OK]
Common Mistakes:
  • Duplicating login checks in multiple guards
  • Relying on component logic instead of guards
  • Ignoring nested route guard order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard