Skip to content

Instantly share code, notes, and snippets.

@khesayed
Last active April 9, 2025 20:27
Show Gist options
  • Save khesayed/58bc7cd4525c190b02c3f90303c1bb0d to your computer and use it in GitHub Desktop.
Save khesayed/58bc7cd4525c190b02c3f90303c1bb0d to your computer and use it in GitHub Desktop.
🛡️ React protected & RBAC route - Router Data Mode
import { Outlet } from "react-router";
const Layout = () => <Outlet />;
export const Home = () => <>Home</>;
const Dashboard = () => <>Dashboard</>;
const Users = () => <>Users</>;
const Login = () => <>Login</>;
export const NotAuthorized = () => <h1>Not Authorized</h1>;
export const routes = [
{
Component: Layout,
children: [
{
index: true,
Component: Home,
},
{
path: "dashboard",
Component: Dashboard,
authenticated: true,
},
{
path: "users",
Component: Users,
roles: ["users-management"],
},
{
path: "login",
Component: Login,
guest: true,
},
],
},
];
import { redirect } from "react-router";
import { NotAuthorized } from "./index";
// mock hasRoles
const hasRoles = (roles) => {
const userRoles = ["users-management", "admin"];
if (!userRoles) return false;
return roles.some((role) => userRoles.includes(role));
};
const authenticated = true;
export const RBACRoute = (routes) => {
return routes.map((route) => {
if (route.children) {
route = {
...route,
children: RBACRoute(route.children),
};
}
if (route.authenticated && !authenticated) {
delete route.Component;
route = {
...route,
Component: () => <NotAuthorized />,
};
}
if (route.roles && !hasRoles(route.roles)) {
delete route.Component;
route = {
...route,
Component: () => <NotAuthorized />,
};
}
if (route.guest && authenticated) {
route = {
...route,
/**
// redirect to home page if authenticated
change / to any path you want
*/
loader: async () => redirect("/"),
};
}
return route;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment