React Routing-Basics: Route Guards Use Cases and Permission Control

Route guards in React Router are mechanisms used to control pre-load behavior of routes, commonly utilized in the following scenarios:

  • Permission Verification: Allow only logged-in users to access specific pages (e.g., backend management interfaces).
  • Pre-load Page Checks: For example, verifying if a user has been authorized or determining if they need to re-login.
  • Prevention of Unauthorized Access: For example, blocking unauthenticated users from accessing routes requiring authentication.
  • Page-level Route Control: For example, displaying different content based on the user's role (e.g., admin vs. user).

Implementation Methods for Permission Control

The core of permission control lies in determining whether a user has the authority to access a specific route. React Router offers several ways to implement this logic:

1. Using React Router Hooks

  • useNavigate: Used to navigate to a target route; can be combined with useLocation to retrieve current route information.
  • useEffect: Triggers side effects when routes change, such as checking user status.

2. Custom Route Guards

By defining functional components as route guards, the route loading logic is controlled:

useEffect(() => {
  if (!isAuthenticated) {
    navigate('/login');
  }
}, [isAuthenticated, navigate]);

3. State Management and Local Storage

  • Local Storage: Save user login status (e.g., in localStorage) to dynamically judge based on route changes.
  • Redux or Context API: Centrally manage user permission state to ensure global consistency.

4. Permission Verification Logic

  • Role-based: Determine route content based on the user's role (e.g., admin or user).
  • Permission-code based: Verify via API whether the user possesses specific permissions (e.g., edit-article).

Code Examples

// Define a route guard function
const authGuard = (navigate) => {
  const isAuth = useAuth(); // Assumes the existence of a useAuth hook
  if (!isAuth) {
    navigate('/login');
  }
};

// Use the guard in route configuration
<Route path="/admin" component={AdminPage} />

Precautions

  • Performance Optimization: Avoid executing time-consuming operations within route guards; use useEffect to optimize performance.
  • Security Practices: Ensure permission verification logic does not leak sensitive information and prevent security risks caused by misjudgments.
  • State Synchronization: After user logout, update local storage or state management to ensure route guard logic takes effect in real-time.