-
I have a project that was built many years ago and I plan to update it, I saw the new router approach and tried to implement on it but immediately stumbled upon conditioned routes issue. In my case routes defined based on context provider: export const useMyRoutes = () => {
const auth = useContext(GlobalContext)
return (
<>
<Route ... />
{auth.isAuthenticated ? (
<>
<Route ... />
{auth.user.isAdmin && (...)}
</>
) : (
<>
<Route ... />
</>
)}
</>
)
} It was written in a way like this, I tried new I searched for other Discussions and find old from 2023, #10478 but it doesn't answer my question. Forget to specify, but I'm thinking about Data mode for now, because Framework mode require dev packages and I need a stable solution. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
The answer of the discussion you mentioned so answer your question, for both data and framework mode what you need to do is to use loaders to conditionally allow or not the user to access a route. |
Beta Was this translation helpful? Give feedback.
You can't use context in data or framework mode to define what routes exists, the routes needs to be defined before that so the router can optimize how data is loaded on navigation.
So the way to do it is by storing auth state outside React (not using a React state) in a way you can do
getUser()
in loader and actions, where to store this depends on you, it can be as simple as using localStorage, if you use some external store like Zustand or Redux that also works as you can always dostore.getState()
in the loaders, or you could use a cookie and then fetch the user from the API every time you need it.Then you can perform authentication and authorization in the loaders/actions to allow th…