react-rbac-manager
v0.1.3
Published
react-rbac-manager is a lightweight and flexible role-based access control (RBAC) utility for protecting routes and components in React applications.
Readme
RBAC Manager for React/Next.js
A simple and reusable utility to protect components or routes in your React or Next.js app using Role-Based Access Control (RBAC). Easily define who can access specific routes or components based on roles and permissions.
✨ Features
- ✅ Simple and flexible RBAC support
- 🔐 Component-level access protection
- 💡 Dynamic control based on role and permission
- ⚙️ Fallback rendering for unauthorized access
- ⚛️ Works with both React and Next.js
📦 Installation
npm install react-rbac-manager
# or
yarn add react-rbac-manager🚀 Usage
🔒 Protecting a Component
import { protectedRoute } from "react-rbac-manager";
const Dashboard = () => <div>Welcome to the Admin Dashboard</div>;
const ProtectedDashboard = protectedRoute(Dashboard, {
role: currentUser.role,
allowedRoles: ["admin"],
});
export default ProtectedDashboard;🔑 With Permissions (Granular Access)
import { protectedRoute } from "react-rbac-manager";
const Settings = () => <div>System Settings</div>;
const ProtectedSettings = protectedRoute(Settings, {
role: currentUser.role,
allowedRoles: ["admin", "superuser"],
permissions: {
admin: { update: true },
superuser: { update: false },
},
action: "update",
fallback: <div>Access Denied</div>,
});
export default ProtectedSettings;📘 API
protectedRoute(Component, options)
| Option | Type | Required | Description |
|---------------|-------------------------------|----------|-------------|
| role | "admin" \| "user" \| "guest" | ✅ | Current user's role |
| allowedRoles | Role[] | ✅ | List of roles allowed to access |
| permissions | Partial<RolePermissions> | ❌ | Fine-grained permissions |
| action | "read" \| "write" \| etc. | ⚠️ If using permissions | Specific action to check |
| fallback | ReactNode | ❌ | Custom fallback UI for unauthorized access |
🧩 Notes
- If
permissionsis provided,actionmust be specified. - If
permissionsis not provided, access is checked based onroleonly. fallbackcan be a string, element, component, or redirect.
🧾 TypeScript Support
All types like Role, PermissionAction, and WithProtectedOptions are exposed for flexibility and full TypeScript support.
📄 License
MIT Licensed. Free to use in personal and commercial projects. PRs and contributions welcome ❤️
