Quick start
A five-minute path from install to a guarded button and a hook-based check.
When to use
- First time integrating the library
- You want copy-paste snippets that match the real API
Example
tsx
import {
RoleGuardProvider,
Can,
useCan,
} from 'advanced-react-role-guard';
export function App() {
return (
<RoleGuardProvider
user={{ roles: ['admin'], permissions: [] }}
config={{
roles: { admin: ['user:delete', 'user:edit'] },
}}
>
<Toolbar />
</RoleGuardProvider>
);
}
function Toolbar() {
const canDelete = useCan({ permission: 'user:delete' });
return (
<nav>
<Can permission="user:edit" fallback={<span>Read-only</span>}>
<button type="button">Edit</button>
</Can>
{canDelete ? (
<button type="button">Delete</button>
) : null}
</nav>
);
}Checklist
- Wrap the tree with
RoleGuardProvider(user+config). - Use
<Can permission="…" />or<Can role="…" />for declarative UI. - Use
useCan({ permission: '…' })(orrole/permissions) for imperative branches.
Pitfalls
- Forgetting the provider →
useCanthrows (components that use context must be underRoleGuardProvider). - Using
matchwithout an array →matchapplies only to{ permissions: [...] }onuseCanand onCan/Guard.
Best practices
- Keep role-to-permission maps in
config.roles; put direct grants onuser.permissionswhen the API sends them explicitly.
Common mistakes
- Expecting
post:*inuser.permissionsto imply everypost:*action — prefix wildcards apply to entries underconfig.rolesfor each role, not as pattern expansion on arbitrary strings inuser.permissions(see Permissions model).