In an application i have 2 types of users vendor and buyer want to manage the routing in such a away the vendor can not access buyer pages and vice versa using React Router Dom V6. Attempt to do so should route to an access denied page.
Login logic from the login page
if (res.data.data.user?.role?.name.toLowerCase() === "vendor") {
navigate("/dashboard")
}
else {
navigate("/buyer-dashboard")
}
App.jsx
<BrowserRouter>
<BuyerRoute />
<VendorRoute />
<PublicRoute />
</BrowserRouter>
PublicRoute.jsx
<Routes>
<Route index element={<Login />} />
<Route path='/signup' element={<SignUp />} />
<Route path='/email-confirmation' element={<Confirmation />} />
<Route path='/forget-password' element={<ForgetPassword />} />
<Route path='/set-password/:email' element={<SetPassword />} />
<Route path='*' element={<>404</>} />
</Routes>
BuyerRoute.jsx
<Routes>
<Route path="/buyer-dashboard" element={<Dashboard />} />
<Route path="/other" element={< Other />} />
</Routes>
VendorRoute.jsx
<Routes>
<Route path="/dashboard" element={<VendorDashboard />} />
<Route path="/items" element={< Items />} />
</Routes>
Login successfully route to the expected page, buy i change the route in the address bar i am able to navigate to dashboard when i logged in as a buyer.
For the approach you want in your app you need to use protected routes you can learn more in this blog : https://blog.logrocket.com/authentication-react-router-v6/
Create routes using createBrowserRouter
Make a function to retrieve to roles of the user on login
now make a component for protected route