Home > other >  How to check user role on a protected route in Reactjs?
How to check user role on a protected route in Reactjs?

Time:10-03

I Have a protected route, when the user login, I save the user details on localStorage. In the protected route, I check the user details from localStorage If it's empty I redirect to the login page, otherwise, the user can access all the tabs and I have three roles. I want the user should be able to access the tabs-based role. If the role is user only access Dashboard and Admin should be able to access all pages. How to check the user role and give access based on role?

This is my requireAuth.js and code.

import React from "react";
import { Navigate } from "react-router-dom";
export const RequireAuth = ({ children }) => {
  const user = localStorage.getItem("userInfo");
  if (!user) return <Navigate to="/login" />;
  return children;
};

This is my Layout file

import React from "react";
import { Outlet } from "react-router-dom";
import Sidebar from "../../components/Sidebar";
import Headers from "../../components/Header";
import { RequireAuth } from "../../shared/requireAuth";


const Layout = () => {
  return (
    <>
      <RequireAuth>
        <div className="container-fluid">
          <div className="row">
            <Sidebar />
            <div className="col-md-9 ms-sm-auto col-lg-10 px-0  ">
              <Headers />
              <div className="px-lg-5 px-3 py-3">
                <Outlet />
              </div>
            </div>
          </div>
        </div>
        
      </RequireAuth>
    </>
  );
};

export default Layout;

This is my route on App.js

<Route path="/" element={<Layout />}>
  <Route path="/users" element={<UserList />} />
  <Route path="/adduser" element={<AddUser />} />
  <Route path="/dashboard" element={<Dashboard />} />
</Route>;

If the user doesn't have access to the page the redirect this route.

   <Route path="/unauthorized" element={<Unauthorized />} />

CodePudding user response:

Create a RoleAccess layout route that reads the role from localStorage and compares it against a list of roles that can access the route.

Example:

const RoleAccess = ({ roles = [] }) => {
  const user = JSON.parse(localStorage.getItem("userInfo"));
  return !roles.length || roles.includes(user?.role)
    ? <Outlet />
    : <Navigate to="/unauthorized" replace />;
};

...

<Route path="/" element={<Layout />}>
  <Route element={<RoleAccess roles={["user", "admin"]} />}>
    <Route path="/dashboard" element={<Dashboard />} />
  </Route>
  <Route element={<RoleAccess roles={["admin"]} />}>
    <Route path="/users" element={<UserList />} />
    <Route path="/adduser" element={<AddUser />} />
  </Route>
</Route>;
  • Related