'React roles based route accesss
I've an application in React 17 and router version is 6, I already know basic authentication and authorization, but what I'm struggling is with, there are certain paths which are allowed to the user, and others are not. here is my code structure
import React from 'react'
function App() {
let userRoles = [
"products/list",
"products/add",
"products/update",
"products/delete",
"action/list",
"action/add",
"action/edit"
]
return (
<Route>
< Route path="/action" element={< Action />} />
< Route path="/edit-action" element={< EditActions />} />
< Route path="/add-actions" element={< AddActions />} />
< Route path="/products" element={< Products />} />
< Route path="/edit-product" element={< AddProducts />} />
< Route path="/add-products" element={< AddProducts />} />
{/* Not allowed to the user */}
< Route path="/broker-firm" element={< BrokerFirm />} />
< Route path="/add-broker-firm" element={< AddBrokerFirm />} />
< Route path="/edit-broker-firm" element={< EditBrokerFirm />} />
</Route>
)
}
export default App
What is want it that if a user tries to navigate to any route that is not allowed, it should stay on the same page, and show a toast notification that you're not allowed to this route.
I can show the toast message with toast.error("Some error message")
But I'm not getting to making to make it work, like this.
What I already tried is wrapping the route inside the condition like this
{userRoles.includes("product/list") && < Route path="/products" element={< Products />} />}
but the problem with this approach is that I can't show the error message to the user, since that React Router simple doesn't know anything about that route, it simply will not generate that route
Solution 1:[1]
There is another way to do what you want. Instead of checking it in the app.js you can check it in the individual components.
You can pass the data to the component and there you can check it if the user is allowed to access it or not.
if(!userRoles.includes("product/list")) {
navigate('/')
}
Solution 2:[2]
You simply wrap the routes that you wish to restrict with an auth validating component.
Their docs have a really good example, docs explanation, stackblitz example
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharmik Patel |
| Solution 2 | Art |
