Blog>
Snippets

Guarded Path Matcher

Explain how to integrate route guards with custom route matchers for protected routes based on specific matching conditions.
const checkAuth = () => {
  // Mock function to check if the user is authenticated
  return !!sessionStorage.getItem('userIsAuthenticated');
};
Defines a mock function `checkAuth` that checks if the user is authenticated by seeing if a specific session storage item is set. Replace this with real authentication logic as needed.
const routes = [
  {
    path: '/protected',
    guard: checkAuth,
    component: ProtectedComponent,
    onGuardFailure: '/login'
  },
  // ... other routes
];
Sets up a route configuration array that includes protected and unprotected paths. The protected route here uses the `checkAuth` function and redirects to '/login' if it fails.
function matchRoute(path) {
  for (const route of routes) {
    // Add actual path matching logic below, e.g., regular expressions
    if (route.path === path) {
      return route;
    }
  }
  return null;
}
Implements a `matchRoute` function to match the current path against registered routes. Replace the simplistic equality check with more complex matching if needed (e.g., path parameters, wildcards).
function navigate(path) {
  const route = matchRoute(path);
  if (route && route.guard && !route.guard()) {
    window.location.href = route.onGuardFailure;
    return;
  }
  if (route) {
    // Logic to render the component associated with the route
    // e.g., route.component.mount()
  } else {
    // Show a 404 page or similar
  }
}
Simulates navigating to a new route. `navigate` function attempts to match the route, checks if a guard exists and the guard fails, then redirects. Otherwise, it proceeds with component rendering or shows a fallback for unmatched routes.