Course contentsShow
← Web Development
Lesson 982 of 2,98217. URL and History ManagementFree lesson

Route Guards and Navigation Hooks

Implement authorization checks and data fetching before allowing route transitions.

Route Guards and Navigation Hooks

You'll learn how to control access to routes and prepare data before navigation completes using guard functions and lifecycle hooks.

What Are Route Guards?

Imagine a bouncer at a club checking IDs before letting people in. Route guards work similarly—they're functions that run before a route transition completes, deciding whether to allow, block, or redirect the navigation. Navigation hooks extend this by letting you perform setup tasks like fetching data or showing loading states.

Core Concept

Route guards intercept navigation attempts and execute logic to:

  • Check authorization: Does the user have permission to view this route?
  • Validate conditions: Are required prerequisites met?
  • Fetch data: Load content before showing the page
  • Redirect: Send users elsewhere if conditions aren't met

A basic guard pattern looks like this:

function canActivateRoute(routeName, state) {
  if (routeName === '/dashboard') {
    const isLoggedIn = checkAuthStatus();
    if (!isLoggedIn) {
      history.pushState(null, '', '/login');
      return false; // Block navigation
    }
  }
  return true; // Allow navigation
}

Navigation Lifecycle Hooks

Beyond simple guards, you can add hooks at different navigation stages:

async function beforeNavigate(from, to) {
  // Fetch data needed for the new route
  const userData = await fetchUserData(to.params.id);
  to.state.userData = userData;
}

function afterNavigate(route) {
  // Update page title, track analytics
  document.title = route.title;
}

These hooks integrate with your popstate event handler, running checks before calling history.pushState() or after detecting back/forward navigation.

Practical Pattern

Guards prevent unauthorized access while hooks prepare the UI, creating smooth, secure navigation experiences.

Key Takeaway: Route guards and navigation hooks let you implement authorization checks and data fetching before route transitions, ensuring users only access appropriate content with all necessary data ready.