Authorization Hooks For Frontend Developers
The@repo/auth-hooks package provides React hooks for authorization in zopio applications. It works in conjunction with the authorization runner to provide a seamless way to check user permissions in React components.
Installation
Usage
The main hook provided by this package isuseAccess, which allows you to check if a user has permission to perform a specific action on a resource.
API Reference
useAccess
A React hook that evaluates access permissions for resources.Parameters
The hook accepts a single object with the following properties:| Property | Type | Description | Required |
|---|---|---|---|
| resource | string | The resource being accessed (e.g., ‘posts’, ‘users’) | Yes |
| action | string | The action being performed (e.g., ‘create’, ‘read’, ‘update’, ‘delete’) | Yes |
| field | string | Optional field within the resource | No |
| record | any | The record data being accessed | No |
| context | any | Context information for evaluation (e.g., current user, roles) | Yes |
Return Value
The hook returns an object with the following properties:| Property | Type | Description |
|---|---|---|
| can | boolean | Indicates if access is allowed |
| reason | string | Optional explanation for the access decision |
| loading | boolean | Indicates if the access check is in progress |
Integration with Authorization Runner
TheuseAccess hook internally uses the evaluateAccess function from the @repo/auth-runner package to perform the actual permission check. This ensures consistency between your React components and other parts of your application.
Example: Conditional Rendering
Example: Disabling UI Elements
Best Practices
- Use with Server Components: For Next.js applications, consider using the authorization runner directly in Server Components and the hooks in Client Components.
- Caching Results: The hook automatically memoizes results based on the parameters, but consider implementing additional caching for complex authorization rules.
- Error Handling: Always handle the loading state to provide a good user experience while permissions are being checked.
- Combine with Authentication: Use alongside your authentication solution to create a complete access control system.