React
@anievo-id/rbac-evolution-react lets React components ask "can the current user do this?" without a network request. The server sends a small snapshot of the user's roles and permissions; a provider puts it in context; hooks and components read it synchronously.
UI only
Everything in this package runs in the browser. It decides what the UI shows, not what the user is allowed to do: anyone can change client-side state. Always enforce authorization on the server too — with @anievo-id/rbac-evolution-next, @anievo-id/rbac-evolution-express or the core rbac.for(user).can(). See Security.
Installation
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-reactpnpm add @anievo-id/rbac-evolution @anievo-id/rbac-evolution-reactyarn add @anievo-id/rbac-evolution @anievo-id/rbac-evolution-reactRequires React 18 or newer.
How it works
Server: build a snapshot for the signed-in user with
await rbac.for(user).snapshot(). It is a plain, serializable object:tsinterface RbacSnapshot { roles: string[] permissions: string[] // direct + via roles denied?: string[] // only with snapshot({ checkBefore }), see "before hooks" below }Client: pass it to
<RbacProvider snapshot={...}>near the root of your tree.Anywhere below: call
useCan(), render<Can>, and so on. Checks are synchronous. While you fetch the snapshot on the client, passloadingso nothing flashes (see below).
Setting up the provider
Any React app can fetch the snapshot from an endpoint of yours and hand it to the provider. null (or undefined) means "guest": every check fails.
// server: e.g. an Express route
app.get('/api/me/permissions', async (req, res) => {
res.json(req.rbac ? await req.rbac.snapshot() : null)
})// client
import { useEffect, useState } from 'react'
import { RbacProvider } from '@anievo-id/rbac-evolution-react'
import type { RbacSnapshot } from '@anievo-id/rbac-evolution'
export function Root() {
const [snapshot, setSnapshot] = useState<RbacSnapshot | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
fetch('/api/me/permissions')
.then((r) => r.json())
.then(setSnapshot)
.finally(() => setLoading(false))
}, [])
return (
<RbacProvider snapshot={snapshot} loading={loading} wildcard>
<App />
</RbacProvider>
)
}Provider props
| Prop | Type | Description |
|---|---|---|
snapshot | RbacSnapshot | null | undefined | Roles & permissions of the current user. null / undefined = guest. |
wildcard | boolean | Treat granted permissions as wildcard patterns (articles.*). Default false. |
superAdminRoles | string[] | Users with any of these roles pass every permission check. |
loading | boolean | Snapshot still being fetched: <Can>, <Cannot>, <HasRole> render nothing, not even fallback. Hooks return false; useRbac().loading is true. Default false. |
children | ReactNode |
Providers can be nested; components use the nearest one.
Hooks
All hooks read from the nearest <RbacProvider> and throw if there is none.
| Hook | Returns true when the user… |
|---|---|
useCan(permission) | has the permission |
useCannot(permission) | does not have the permission |
useCanAny(...permissions) | has any of the permissions |
useCanAll(...permissions) | has all of the permissions |
useHasRole(role | roles[]) | has the role — or any of the roles for an array |
useHasAnyRole(...roles) | has any of the roles |
useHasAllRoles(...roles) | has all of the roles |
useRbac() | — returns the underlying checker object |
The list hooks accept varargs, arrays, or a mix: useCanAny('a', 'b') and useCanAny(['a', 'b']) are the same.
import { useCan, useCanAny, useHasRole } from '@anievo-id/rbac-evolution-react'
export function ArticleToolbar() {
const canPublish = useCan('articles.publish')
const canModerate = useCanAny('articles.delete', 'articles.archive')
const isEditor = useHasRole(['editor', 'admin'])
return (
<div>
<button disabled={!canPublish}>Publish</button>
{canModerate && <button>Moderate</button>}
{isEditor && <span className="badge">Editor</span>}
</div>
)
}useRbac() returns the full checker: can, cannot, canAny, canAll, hasRole, hasAnyRole, hasAllRoles, plus roles, permissions and isSuperAdmin. It is handy when you need several checks in a loop:
const rbac = useRbac()
const visibleItems = menu.filter((item) => !item.permission || rbac.can(item.permission))Components
<Can>, <Cannot> and <HasRole> render their children when the check passes and an optional fallback when it does not.
import { Can, Cannot, HasRole } from '@anievo-id/rbac-evolution-react'
export function ArticleActions() {
return (
<>
<Can permission="articles.edit">
<button>Edit</button>
</Can>
<Can anyOf={['articles.delete', 'articles.archive']} fallback={<span>Read only</span>}>
<button>Remove</button>
</Can>
<Can allOf={['articles.edit', 'articles.publish']}>
<button>Edit & publish</button>
</Can>
<Cannot permission="articles.edit">
<p>Ask an editor to make changes.</p>
</Cannot>
<HasRole role="admin">
<a href="/admin">Admin panel</a>
</HasRole>
<HasRole anyOf={['admin', 'editor']}>…</HasRole>
<HasRole allOf={['writer', 'reviewer']}>…</HasRole>
</>
)
}| Component | Condition props (pick one) | Renders children when… |
|---|---|---|
<Can> | permission, anyOf, allOf | the permission check passes |
<Cannot> | permission, anyOf, allOf | the same check fails |
<HasRole> | role, anyOf, allOf | the role check passes |
All three accept fallback. TypeScript only allows exactly one condition prop. If a component ends up with no condition at all (for example from untyped JavaScript), it is treated as denied: <Can> and <HasRole> render the fallback.
Spatie users
<Can> maps to @can / @canany, <Cannot> to @cannot, and <HasRole> to @role / @hasanyrole / @hasallroles.
Wildcards and super-admins
The client does not know your server configuration, so mirror it with props.
wildcard
If the engine was created with createRbac({ wildcard: true }), pass wildcard to the provider so a granted articles.* also satisfies useCan('articles.edit'). The Rbac instance exposes the setting, so on the server you can forward it directly: wildcard={rbac.wildcard}.
<RbacProvider snapshot={snapshot} wildcard={rbac.wildcard}>Matching uses the same wildcardImplies() as the core. See Wildcard permissions.
superAdminRoles
The snapshot contains only names, so a server-side superAdminRoles setting is not visible to the browser. Pass the same list to the provider; users with one of these roles then pass every permission check (can, canAny, canAll, <Can>). Role checks are unaffected — a super-admin without the editor role still fails <HasRole role="editor">.
// lib/rbac-config.ts — share one constant between server and client
export const SUPER_ADMIN_ROLES = ['super-admin']<RbacProvider snapshot={snapshot} superAdminRoles={SUPER_ADMIN_ROLES}>before hooks: denied
A before hook runs on the server only. When it denies something, for example "nobody may delete the audit log", a super-admin's UI would still show the button and the server would answer 403. Ask the snapshot to run the hook for the names your UI checks, with checkBefore. The names the hook denies are sent as denied, and the provider treats them as not allowed, for super-admins and stored grants alike:
app.get('/api/me/permissions', async (req, res) => {
res.json(req.rbac ? await req.rbac.snapshot({ checkBefore: ['audit-log.delete', 'users.impersonate'] }) : null)
})
// → { roles: ['super-admin'], permissions: [], denied: ['audit-log.delete'] }import { Can, RbacProvider } from '@anievo-id/rbac-evolution-react'
import type { RbacSnapshot } from '@anievo-id/rbac-evolution'
export function Toolbar({ snapshot }: { snapshot: RbacSnapshot }) {
return (
<RbacProvider snapshot={snapshot} superAdminRoles={['super-admin']}>
<Can permission="audit-log.delete">
<button>Delete audit log</button> {/* hidden: denied by the server's before hook */}
</Can>
</RbacProvider>
)
}deniedholds exact names: it is matched without wildcards, like the names the hook was asked about.- Only denials travel. A hook that allows (returns
true) through custom logic is not visible in the browser; expose that through a role or a separate flag. - A snapshot without
denied(older servers, or nocheckBefore) behaves exactly as before. - The hook runs once per name when the snapshot is built, with the same subject, guard and team as
can().
See Super-admin.
Next.js App Router
The package's bundle begins with a 'use client' directive, so you can render <RbacProvider> directly from a server component (for example your root layout) and pass it a snapshot built on the server.
// app/layout.tsx — server component
import { RbacProvider } from '@anievo-id/rbac-evolution-react'
import { rbac } from '@/lib/rbac'
import { auth } from '@/auth'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const session = await auth()
const snapshot = session?.user?.id
? await rbac.for({ type: 'user', id: session.user.id }).snapshot()
: null
return (
<html lang="en">
<body>
<RbacProvider snapshot={snapshot} wildcard={rbac.wildcard}>
{children}
</RbacProvider>
</body>
</html>
)
}Components that use the hooks or <Can> must be client components, so they need 'use client' at the top of their own file:
// app/articles/article-actions.tsx
'use client'
import { Can, useCan } from '@anievo-id/rbac-evolution-react'
export function ArticleActions() {
const canPublish = useCan('articles.publish')
return (
<>
<Can permission="articles.edit">
<button>Edit</button>
</Can>
<button disabled={!canPublish}>Publish</button>
</>
)
}With @anievo-id/rbac-evolution-next the snapshot line becomes snapshot={await getSnapshot()}, which also handles guests, guards and teams for you.
Using the checker outside React
createRbacChecker(snapshot, { wildcard?, superAdminRoles? }) is the pure function behind the provider. It honours the snapshot's denied too. Use it in tests, utilities or non-React code:
import { createRbacChecker } from '@anievo-id/rbac-evolution-react'
const checker = createRbacChecker(
{ roles: ['editor'], permissions: ['articles.*'] },
{ wildcard: true },
)
checker.can('articles.edit') // true
checker.hasRole('admin') // falseNotes
- Exact names. Matching is exact after trimming whitespace, like the core. Without
wildcard,articles.*is just a literal name. - Guards and teams. A snapshot belongs to one guard and one team. Build it with the same
{ guard, team }you use for server-side checks:rbac.for(user, { guard: 'web', team: teamId }).snapshot(). - Freshness. A snapshot is a copy taken at one moment. After changing a user's roles, give the provider a new snapshot (refetch, or
router.refresh()in Next.js). - Empty lists never pass.
useCanAny(),useCanAll()anduseHasAllRoles()returnfalsefor an empty list, and<Can allOf={[]}>renders its fallback — the same deny-by-default rule as the Vue package.
Full API: reference
