Private and Role Based Route in React Router V6 

‘Private Routing’ and ‘Role-Based Routing’ concepts play a vital role in ensuring that the right content is accessible to the right users while safeguarding sensitive information.

Private Routing

Private routing involves controlling access to certain sections or pages of a website based on user authentication. It allows you to prevent unauthorized users from accessing the screens. Users need to log in or authenticate themselves before they can access the protected content. By implementing private routing, you enhance the security of your blog and maintain a sense of exclusivity for certain portions of your audience.

Creating Private route component

import { Navigate } from "react-router-dom";

const PrivateRoute = ({ Component }) => {
  let auth = false;

  return auth ? <Component /> : <Navigate to="/login" />;
};


export default PrivateRoute;
  • The PrivateRoute component takes a Component prop and checks an auth variable (representing user authentication).
  • If auth is true, it renders the provided Component; if auth is false, it navigates to “/login” using the Navigate component.
  • setup allows conditional rendering of routes based on user authentication status.
  • The component is exported for use in controlling access to specific routes in a React application

import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Admin from "./Admin";
import User from "./User";
import PrivateRoute from "./privateRoute";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/admin"
          element={<PrivateRoute Component={Admin} />}
        ></Route>
        <Route
          path="/user"
          element={<PrivateRoute Component={User} />}
        ></Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;

In your App.js file, the App component configures the main structure of your React application using the BrowserRouter from react-router-dom. Within the Routes, two routes are defined: when the path is “/admin” or “/user”, the PrivateRoutes component is used to determine if the user is authenticated. If authenticated, it renders the Admin or User component respectively, otherwise, it redirects to a login page. This structure ensures that access to the “admin” and “user” routes is controlled based on user authentication, providing a secure and organized app navigation.

Role-Based Routing

While private routing establishes a basic level of access control, role-based routing takes things further by tailoring content based on specific user roles. In the context of a blog, different users might have different roles, such as “Admin” and “Employee”. Role-based routing enables you to display content and features that are relevant to each user’s role.

Creating Role-Based route component

import { Navigate } from "react-router-dom";

const RoleBasedRoute = ({ Component, roles }) => {
  let userRole = "admin";
  return roles.includes(userRole) ? (
    <Component />
  ) : (
    <Navigate to="/unauthorized" />
  );
};

export default RoleBasedRoute;
  • The RoleBasedRoute component takes a Component prop and a roles prop (array of allowed roles).
  • It checks the user’s role (hardcoded as “admin” here) against the allowed roles.
  • If the user’s role matches an allowed role, it renders the provided Component; if not, it uses the Navigate component to redirect to “/unauthorized”.
  • The component allows route access based on user roles and is exported for use in controlling access to specific routes in a React application.
import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Admin from "./Admin";
import User from "./User";
import RoleBasedRoute from "./roleBasedRoute.";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/admin"
          element={
            <RoleBasedRoute Component={Admin} roles={["admin", "user"]} />
          }
        ></Route>
        <Route
          path="/user"
          element={<RoleBasedRoute Component={User} roles={["user"]} />}
        ></Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App;

In App.js file, we have rendered the RoleBasedRoute component and sent the roles list as a prop that can accessed. The RoleBasedRoute component renders the specified component if the role matches; otherwise, it will navigate to the unauthorized component.

These components provide developers with powerful ways to manage user access and authentication based on status and user roles.

Related Blogs

Elevate ASP.NET Core Web API speed with caching. Explore in-memory, distributed, and