Frontend Patterns

Pattern

Navigation Middleware

Execute logic before, during, or after navigation events.

Navigation Middleware

Problem

Cross-cutting concerns like analytics tracking, logging, or state cleanup are scattered throughout route handlers. Common navigation logic gets duplicated across routes, making it difficult to ensure consistent behavior or update global navigation handling.

Solution

Intercept route changes to run logic before navigation completes. This enables authentication checks, data preloading, or blocking navigation based on unsaved changes.

Example

This example shows navigation middleware that checks authentication before allowing access to protected routes, redirecting to login when necessary.

// Run this function before every route change
router.beforeEach((to, from, next) => {
  // Check if target route requires authentication
  if (to.meta.requiresAuth && !isAuthenticated()) {
    // Redirect to login if not authenticated
    next('/login');
  } else {
    // Allow navigation to proceed
    next();
  }
});

Benefits

  • Centralizes cross-cutting concerns like authentication and analytics in one place.
  • Enables blocking navigation based on conditions like unsaved changes.
  • Provides hooks for data preloading before routes render.
  • Makes navigation logic consistent across the entire application.

Tradeoffs

  • Can make navigation flow harder to understand and debug.
  • May slow down route transitions if middleware performs expensive operations.
  • Requires careful design to avoid creating middleware that’s too powerful or complex.
  • Can create tight coupling if middleware depends on specific route structures.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.