0
import { useRoutes } from "react-router-dom";
// ...

export default function App() {
  // check auth here?
  const routes = useRoutes([
    {
      path: "/",
      element: <HomePage />
    },
    {
      path: "/login",
      element: <LoginPage />
    }
  ]);
  return routes;
}

I want to limit available pages based on user roles and login status.

As the example code shows, can I add a auth check logic (maybe an AuthProvider), then if auth status changes, create the routes based on user role?

const [routes, setRoutes] = useState([])
useEffect(
  () => {
    if (user.role === 'admin') {
      setRoutes(...)
    } else if ...
  },
  [routes]
)

Is this a good idea?

CSSer
  • 2,131
  • 2
  • 18
  • 37
  • Are you basically asking how to implement [protected routes](/a/66289280/8690857)? – Drew Reese Jun 19 '23 at 17:45
  • @DrewReese Kind of. But I want to calculate the routes based on user role after login, for once, then I don't need to check user role every time the url changes. Just want to make sure it won't cause any bug or is anti-pattern. – CSSer Jun 20 '23 at 15:15
  • You will use any *condition* necessary to protect a route. Some routes might need *authentication* to access, others *authentication **and** specific user roles*. You can nest these route protectors to compose the access scheme your app/routes need. This [answer](/a/73931932/8690857) is an example of a protected route component using user roles. – Drew Reese Jun 20 '23 at 15:56
  • FWIW I've seen trying to conditionally render one set of routes or another have synchronicity issues between updating the React state the conditional logic is based upon *and* trying to navigate to any of their routes, e.g. a user logs in and the code (a) sets state (*setRoutes*) and then immediately (b) tried to navigate (*`navigate("/protected-route-that-hasnt-mounted-yet-because-state-hasnt-updated-and-routes-rerendered");`*). Does this make sense? – Drew Reese Jun 20 '23 at 15:59
  • @DrewReese This does seem to be a problem. And the answer you linked seems a good solution, though the check happens every time navigating to that page right? Maybe I should find a way to return routes from server as user login, or hold navigation until routes are ready, or fix the redirect to a page that do not need authorization. – CSSer Jun 20 '23 at 16:27
  • I can't imagine it being an expensive computation if you are just checking if the user object has a specific role property, array or not. – Drew Reese Jun 20 '23 at 16:38

0 Answers0