Yay, I have come up with another super cool story I would call it RBAC-V2 because it is my second story on the same topic, there was some reason behind version-2 that are listed below.
Updates in version-2:
The solution is exactly the same which I used in version-1 so if you didn’t check version-1, I would highly recommend going through so, you can better understand what exactly going on…
The idea is simply prevent the app to generate unnecessary routes,****rather checking the role on each route and showing fallback UI it would be a great idea to generate only the routes in which user have access, so if the user navigate manually to a route ie: (typing in the address bar) he/she will get 404 Not Found screen because route is not registered.
🙋🏻♂️ Stop Stop Stop
Yes, it is possible if you have heard about react-router 4 philosophy it supports dynamic routing and we can take advantage of it.
When we say dynamic routing, we mean routing that takes place as your app is rendering, not in a configuration or convention outside of a running app.
Let’s start
Step #1
Because we are looking for a role-based solution so let’s define the roles first, roles are nothing just a plain javascript object having key-value pair, below is the placeholder roles for my demo app you can replace these with yours.
User Roles
File: src/config/Roles
export default {
SUPER_ADMIN: 'SUPER_ADMIN',
ADMIN: 'ADMIN',
MANAGER: 'MANAGER',
CUSTOMER: 'CUSTOMER',
GUEST: 'GUEST'
};
Step #2
Define the private routes configuration, r_oute config object supports all the react-router’s route component props with some additional props ie: **(title, permission, children)** you can add or remove props from config object it means it is super customizable and support up to N nesting, child routes must follow the same parent shape, it means the config object is same for both there is no additional key for the child nor for a parent._
#software-development #web-development #react #programming #javascript