Route Guards Lifecycle and Usage Tips

In the Nuxt framework, route guards control navigation flow through predefined lifecycle hooks such as beforeEach, beforeRouteEnter, beforeRouteLeave, etc. These hooks are triggered in a specific order to ensure necessary logic executes before routing changes occur:

  • beforeEach: A global guard used to intercept all navigation events; it allows customizing the navigation behavior globally.
  • beforeRouteEnter: Triggered just before entering a route, allowing access to component props or injected context data.
  • beforeRouteLeave: Triggered immediately before leaving a route; commonly used to prevent users from navigating away without confirmation (e.g., unsaved changes).
  • beforeEnter: Only triggered when switching routes with dynamic parameters; useful for validating parameter values at the transition point.

Usage Tips

  1. Permission Verification : Retrieve component props via beforeRouteEnter and combine them with user permission data to make access decisions.
  2. Data Caching : Use beforeRouteUpdate to cache data during route updates, avoiding redundant API requests.
  3. Global Interception : Intercept all navigation changes using beforeEach for unified handling of authentication states or global permission checks.
  4. Route Meta Information : Set the meta property in route configurations and use guard logic dynamically to control access permissions based on metadata.
  5. Nested Guard Execution Order: In nested routes, ensure that beforeRouteLeave triggers after beforeRouteEnter to maintain correct execution flow.

Practical Example

// Example: Dynamic Route Parameter Validation  
const routes = [
  {
    path: '/user/:id',
    meta: { requiresAuth: true },
    components: { 
      default: () => import('./views/User.vue'), 
      header: () => import('./components/Header.vue') 
    }
  }
];

// Route Guard Configuration  
export default {
  beforeRouteEnter(to, from, next) {
    if (!localStorage.getItem('token')) {
      // Redirect to login page if no token exists
      next('/login');
    } else {
      next();
    }
  },
  beforeRouteUpdate(to, from, next) {
    const userId = to.params.id;
    let cachedUserId = localStorage.getItem('cachedUser');
    
    // Cache the user ID if it differs from stored value
    if (userId !== cachedUserId) {
      localStorage.setItem('cachedUser', userId);
    }
    
    next();
  }
};

Combining Route Guards

  • Combination of Navigation and Component Guards : Use beforeEach to intercept global navigation events, then apply component-specific guards for detailed route logic.
  • Lifecycle Management for Dynamic Parameters: Retrieve parameters in beforeRouteEnter, update related data in beforeRouteUpdate, and execute follow-up actions via afterRouteUpdate.
  • Dynamic Control of Route Meta Information : Combine the meta property with guard conditions to implement conditional access restrictions dynamically based on route metadata.