How to use react protected routes with react dom v6 and js-cookie?

Viewed 43

I am trying to implement a protected route to only allow logged in users to access my app and also a user roles route to allow specific users to log into some pages and protect other pages.

To check if a user is logged In, in my backend file, i created this route :

app.get("/login", (req, res) => {
  if (req.session.user) {
    res.send({ loggedIn: true, user: req.session.user });
  } else {
    res.send({ loggedIn: false });
  }
});

In the login component, I created an axios request to see if a user is logged In or not and store the result in a cookie, to reuse it in the protected route component

  useEffect(() => {
    Axios.get("http://localhost:3001/login").then((response) => {
      if (response) {
        Cookies.set("loggedIn", response.data.loggedIn);
      }
    });
  }, []);

The protected route component :

const PrivateRoute = () => {
  let auth = Cookies.get("loggedIn");
  return auth ? <Outlet /> : <Navigate to="/login" />;
};

export default PrivateRoute;

When i set the auth variable manually to true or false it worked but when i am trying to use Cookies.get("loggedIn") it didn't work, maybe something depend on JavaScript asynchronous programming is the reason.

Probably that's not the correct way to implement a user roles route for that it didn't worked me, but i couldn't find a clear way to implement the user roles route, so, in my app.js i tried something like that :

About the cookie "role" i get it from the response when a user enter a correct email and password. I have a table of users in my database who have a role column take one these values (0,1,2,3), 0 for admin, 1 for normal user .....

function App() {
  const role = Cookies.get("role");
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} exact />
          <Route path="/register" element={<Register />} />
          {(role = 0) && (
            <Route path="admin" element={<PrivateRoute />}>
              <Route path="home" element={<HomeAdmin />} />
              <Route path="profile" element={<ProfileAdmin />} />
            </Route>
          )}

        {(role = 1) && (
          <Route path="user" element={<PrivateRoute />}>
            <Route path="home" element={<HomeUser />} />
            <Route path="profile" element={<ProfileUser />} />
          </Route>
          )}
     </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

Is this a correct way to implement protected routes with user roles route ? and what i missed here ?

0 Answers
Related