useRole()
Role-based access for Admin, CMS Manager and Customer: a useRole() hook, a RoleGuard, server-side page guards, and every 403 routed to a forbidden page.
Hooks
How it works
Every role question in the app (is this an admin, can they publish, is this staff) goes through one hook, which reads from one map of roles and permissions. Add a role or move a permission there, and every check follows.
The client only hides what a role can’t use. The server decides: guarded pages are checked before they render, and when the API refuses a request with 403, the app routes to a forbidden page that names the request.
Try it
Viewing as
/app
Signed in as CustomerNo staff tools
Every button is shown, so you can watch the API refuse:
Who can do what
| Permission | Customer | CMS Manager | Admin |
|---|---|---|---|
| content:read | Allowed | Allowed | Allowed |
| orders:read-own | Allowed | Not allowed | Not allowed |
| content:write | Not allowed | Allowed | Allowed |
| content:publish | Not allowed | Allowed | Allowed |
| dashboard:view | Not allowed | Allowed | Allowed |
| orders:read-all | Not allowed | Not allowed | Allowed |
| users:manage | Not allowed | Not allowed | Allowed |
| settings:manage | Not allowed | Not allowed | Allowed |
Files it creates
src/hooks/use-role.ts
"use client";
import { use, useMemo } from "react";
import { RoleContext } from "@/components/auth/role-provider";
import {
ROLE_LABELS,
can,
canAll,
hasAccess,
hasAnyRole,
hasRole,
isAtLeast,
type Access,
type Permission,
type Role,
} from "@/lib/auth/roles";
// Every role question a component asks, answered from one place:
//
// const { is, isAnyOf, isAtLeast, can } = useRole();
// is("admin") exactly this role
// isAnyOf(["admin", "cms_manager"]) one of these
// isAtLeast("cms_manager") this tier or above
// can("content:publish") has this permission (prefer this)
export function useRole() {
const ctx = use(RoleContext);
if (!ctx) throw new Error("useRole must be used inside <RoleProvider>.");
const { role, sessionRole, previewing, preview } = ctx;
return useMemo(
() => ({
role,
label: role ? ROLE_LABELS[role] : "Signed out",
sessionRole,
previewing,
preview,
isSignedIn: role !== null,
is: (target: Role) => hasRole(role, target),
isAnyOf: (targets: readonly Role[]) => hasAnyRole(role, targets),
isAtLeast: (min: Role) => isAtLeast(role, min),
can: (permission: Permission) => can(role, permission),
canAll: (permissions: readonly Permission[]) => canAll(role, permissions),
hasAccess: (access: Access) => hasAccess(role, access),
}),
[role, sessionRole, previewing, preview],
);
}