DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Implementing Route Guards in React: Protecting Your Routes with Authentication and Roles

Route Guards in React

Route Guards in React refer to the mechanism that restricts or allows access to certain routes based on specific conditions or criteria, such as user authentication, roles, permissions, or even data availability. This is a common requirement in applications with private or protected routes (e.g., admin dashboards, user profiles, or other sensitive areas).

Route guards prevent unauthorized users from accessing restricted routes by either redirecting them to another page or displaying an error message when they try to access a route they are not permitted to view.

In React, route guards can be implemented by utilizing React Router in combination with custom logic, such as authentication states or role-based access control.


How Route Guards Work

  1. Check User Authentication: Determine if the user is logged in.
  2. Redirect or Restrict Access: If the user is not authorized, either redirect them to a login page, a permission-denied page, or any other appropriate view.
  3. Access Control Based on Role: For apps with multiple user roles (e.g., admin, guest, or regular user), restrict access based on the user's role.

Example of Implementing Route Guards in React

Let’s look at how to implement route guards using React Router with a basic authentication guard. We'll check if the user is authenticated and conditionally render the routes based on that.


Basic Example: Protecting Routes Based on Authentication

In this example, we will use a route guard to check if the user is authenticated before allowing access to a restricted route like /dashboard.

Step 1: Create the Route Guard Component

We’ll create a PrivateRoute component that checks if a user is authenticated and either allows access to the protected route or redirects them to the login page.

import React from 'react';
import { Route, Navigate } from 'react-router-dom';

// PrivateRoute component for protecting routes
const PrivateRoute = ({ element, isAuthenticated, ...rest }) => {
  return (
    <Route
      {...rest}
      element={isAuthenticated ? element : <Navigate to="/login" />}
    />
  );
};

export default PrivateRoute;
Enter fullscreen mode Exit fullscreen mode
  • The PrivateRoute component takes the element (which is the protected route component), the isAuthenticated boolean, and the rest of the route props (...rest).
  • If isAuthenticated is true, it renders the protected component (element). If not, it redirects the user to the login page using the <Navigate /> component.

Step 2: Set Up Routes with Route Guards

Now, let’s set up the main application where we use the PrivateRoute to protect certain routes like /dashboard.

import React, { useState } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import PrivateRoute from './PrivateRoute'; // Import the route guard

// Simple page components
const Home = () => <h2>Home Page</h2>;
const Login = () => <h2>Login Page</h2>;
const Dashboard = () => <h2>Dashboard (Private)</h2>;

const App = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false); // Authentication state

  return (
    <BrowserRouter>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
          <li><Link to="/dashboard">Dashboard</Link></li>
        </ul>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        {/* Protected route using PrivateRoute */}
        <PrivateRoute
          path="/dashboard"
          isAuthenticated={isAuthenticated}
          element={<Dashboard />}
        />
      </Routes>

      <div>
        {/* Toggle authentication state */}
        <button onClick={() => setIsAuthenticated(!isAuthenticated)}>
          {isAuthenticated ? "Logout" : "Login"}
        </button>
      </div>
    </BrowserRouter>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We use a simple isAuthenticated state to track whether the user is logged in or not.
  • If the user is logged in (i.e., isAuthenticated is true), they can access the /dashboard route. Otherwise, they are redirected to the /login page.
  • The PrivateRoute component is used to guard the /dashboard route.
  • We toggle the isAuthenticated state using the login button. If the user clicks the button, they are either logged in or logged out.

Example 2: Route Guards Based on User Roles

In this example, we'll implement a route guard that only allows access to the /admin route if the user has an admin role.

Step 1: Create a Role-Based Route Guard

We will modify the PrivateRoute component to handle both authentication and role-based access.

import React from 'react';
import { Route, Navigate } from 'react-router-dom';

// Role-based Route Guard
const RoleBasedRoute = ({ element, isAuthenticated, userRole, requiredRole, ...rest }) => {
  return (
    <Route
      {...rest}
      element={
        isAuthenticated && userRole === requiredRole
          ? element
          : <Navigate to="/login" />
      }
    />
  );
};

export default RoleBasedRoute;
Enter fullscreen mode Exit fullscreen mode

Step 2: Protect Routes Based on Role

In the main application, we’ll set up a role-based route guard that only allows access to the /admin route if the user is an admin.

import React, { useState } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import RoleBasedRoute from './RoleBasedRoute'; // Import the role-based guard

const Home = () => <h2>Home Page</h2>;
const Login = () => <h2>Login Page</h2>;
const Dashboard = () => <h2>Dashboard</h2>;
const Admin = () => <h2>Admin Page (Private)</h2>;

const App = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [userRole, setUserRole] = useState('user'); // Role state (can be 'admin' or 'user')

  return (
    <BrowserRouter>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
          <li><Link to="/dashboard">Dashboard</Link></li>
          <li><Link to="/admin">Admin</Link></li>
        </ul>
      </nav>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="/dashboard" element={<Dashboard />} />

        {/* Protect admin route with role-based guard */}
        <RoleBasedRoute
          path="/admin"
          isAuthenticated={isAuthenticated}
          userRole={userRole}
          requiredRole="admin"  // Only allow 'admin' role to access
          element={<Admin />}
        />
      </Routes>

      <div>
        <button onClick={() => setIsAuthenticated(!isAuthenticated)}>
          {isAuthenticated ? "Logout" : "Login"}
        </button>
        <button onClick={() => setUserRole(userRole === 'user' ? 'admin' : 'user')}>
          Toggle Role (Current Role: {userRole})
        </button>
      </div>
    </BrowserRouter>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The RoleBasedRoute component checks both if the user is authenticated and whether their role matches the required role for the route (e.g., only users with the role 'admin' can access the /admin page).
  • The userRole state determines if the user is an admin or a regular user.
  • You can toggle between 'user' and 'admin' roles using the button.

Conclusion

Route guards are an essential feature for controlling access to specific parts of your application based on conditions like authentication and user roles. They help improve the security and functionality of your app by ensuring that only authorized users can access certain routes. React Router makes it easy to implement route guards by using conditional rendering, the Navigate component for redirection, and custom components to handle complex logic.


Top comments (0)