Protected Routes

Loading

In a React application, protected routes are routes that can only be accessed by users who meet certain conditions, such as being logged in or having the necessary permissions. Typically, these routes are used to ensure that sensitive or restricted pages (e.g., user dashboards, account settings) are not accessible to unauthorized users.

React Router provides an easy way to implement protected routes by combining conditional rendering with React Router’s routing components.

1. Basic Protected Route Example

A common approach to implementing protected routes is by checking if a user is authenticated before allowing access to the route. If the user is not authenticated, you can redirect them to a login page or another public route.

Example of Protected Routes with Redirect (React Router v5)

import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom';

function Home() {
  return <h2>Home Page</h2>;
}

function Dashboard() {
  return <h2>User Dashboard (Protected)</h2>;
}

function Login() {
  return <h2>Login Page</h2>;
}

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false); // Example: Login state
  
  return (
    <Router>
      <div>
        <Switch>
          <Route path="/home" component={Home} />
          <Route path="/login" component={Login} />
          
          {/* Protected route */}
          <Route path="/dashboard">
            {isAuthenticated ? <Dashboard /> : <Redirect to="/login" />}
          </Route>

          {/* Default redirect */}
          <Redirect from="/" to="/home" />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

In this example:

  • The Dashboard route is a protected route.
  • If the user is not authenticated (isAuthenticated is false), they are redirected to the Login page using the Redirect component.
  • If the user is authenticated, they are granted access to the Dashboard page.

2. Protected Route Using Navigate (React Router v6)

In React Router v6, the Navigate component is used to redirect users to different routes, replacing the Redirect component from React Router v5.

Example of Protected Routes with Navigate (React Router v6)

import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';

function Home() {
  return <h2>Home Page</h2>;
}

function Dashboard() {
  return <h2>User Dashboard (Protected)</h2>;
}

function Login() {
  return <h2>Login Page</h2>;
}

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false); // Example: Login state
  
  return (
    <Router>
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/login" element={<Login />} />
        
        {/* Protected route */}
        <Route path="/dashboard" element={isAuthenticated ? <Dashboard /> : <Navigate to="/login" />} />
        
        {/* Default route */}
        <Route path="/" element={<Navigate to="/home" />} />
      </Routes>
    </Router>
  );
}

export default App;

In this example:

  • The Dashboard route is protected, and the user is redirected to the Login page if they are not authenticated.
  • Navigate is used to perform the redirect if the user is not logged in.

3. Protected Route with a Higher-Order Component (HOC)

For cleaner and more reusable code, you can create a Higher-Order Component (HOC) to handle protected routes. The HOC will wrap your route components and handle the authentication logic.

Example of Protected Route HOC

import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';

function Home() {
  return <h2>Home Page</h2>;
}

function Dashboard() {
  return <h2>User Dashboard (Protected)</h2>;
}

function Login() {
  return <h2>Login Page</h2>;
}

function ProtectedRoute({ element, ...rest }) {
  const isAuthenticated = false; // Example condition
  
  return (
    <Route
      {...rest}
      element={isAuthenticated ? element : <Navigate to="/login" />}
    />
  );
}

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/login" element={<Login />} />
        
        {/* Use ProtectedRoute for protected pages */}
        <ProtectedRoute path="/dashboard" element={<Dashboard />} />
        
        <Route path="/" element={<Navigate to="/home" />} />
      </Routes>
    </Router>
  );
}

export default App;

In this example:

  • The ProtectedRoute component is a Higher-Order Component (HOC) that checks if the user is authenticated.
  • If the user is authenticated, they are granted access to the protected route (Dashboard); otherwise, they are redirected to the login page.
  • The HOC provides a more modular and reusable solution for protected routes in your application.

4. Role-Based Protected Routes

For more advanced use cases, you may need to protect routes based on user roles or permissions. You can extend the previous examples to include role-based access control (RBAC).

Example of Role-Based Protected Route

import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';

function AdminDashboard() {
  return <h2>Admin Dashboard</h2>;
}

function UserDashboard() {
  return <h2>User Dashboard</h2>;
}

function Login() {
  return <h2>Login Page</h2>;
}

function App() {
  const [userRole, setUserRole] = useState('user'); // Example: 'user' or 'admin'

  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        
        {/* Role-based Protected Route */}
        <Route
          path="/admin-dashboard"
          element={userRole === 'admin' ? <AdminDashboard /> : <Navigate to="/login" />}
        />
        
        <Route
          path="/user-dashboard"
          element={userRole === 'user' ? <UserDashboard /> : <Navigate to="/login" />}
        />
        
        <Route path="/" element={<Navigate to="/login" />} />
      </Routes>
    </Router>
  );
}

export default App;

In this example:

  • The route for AdminDashboard is protected, and only users with the admin role can access it. If a user with the user role attempts to access the admin dashboard, they are redirected to the Login page.
  • Similarly, the UserDashboard is protected for users with the user role.

Leave a Reply

Your email address will not be published. Required fields are marked *