useContentGuard hook provides role-based access control (RBAC) by checking user permissions against required permissions. It fetches the user session, retrieves role permissions, and determines whether the current user is authorized to access a resource.
Import
Signature
Parameters
The permission(s) required to access the protected resource. Can be a single permission string or an array of permissions. Permissions follow the format
"resource:action" (e.g., "assets:read", "sites:write").If omitted, the hook returns isAllowed: true and only provides user information.Return Value
true if the user has any of the required permissions or is a SuperAdmin. false during loading or if unauthorized.true while fetching user session and permissions. false once data is loaded.Array of permission strings the current user has, formatted as
"resource:action" (e.g., ["assets:read", "sites:write"]).The current user session object containing user details and role information.
null if not authenticated.Usage Examples
Basic Permission Check
Check if a user has permission to access a specific resource:Multiple Permissions (OR Logic)
Check if a user has any of several permissions:Access User Information
Retrieve current user details without permission checks:Page Guard Pattern
Used in thePageGuard component for route-level protection:
Component-Level Guarding
Conditionally render UI elements based on permissions:Behavior
SuperAdmin Override
Users with theSuperAdmin role automatically have isAllowed: true regardless of specific permissions.
Testing Mode
WhenisTesting is true (from @/utils/constants), the hook returns:
Permission Format
Permissions are case-insensitive and follow the format"resource:action". Examples:
"assets:read""sites:write""users:delete""recommendations:read"
Data Flow
- Fetches user session from
/api/session - If session contains permissions, uses them directly
- Otherwise, fetches permissions from
/api/v1/roles/{role_id}/permissions - Compares required permissions against user permissions
- Returns authorization result
Notes
This hook makes network requests on mount. Ensure it’s used in Client Components and not called excessively in loops or deeply nested components.
Related
- ContentGuard Components - Pre-built components using this hook
- Authentication - Authentication flow and session management
- Type Definitions - SessionUser and PermissionType types