Skip to content

RoleGuardProvider

Supplies user, role-to-permission mapping, and feature flags to all child components via React context.

When to use

  • Once at the root of the tree (or per logical subtree) so Can, Guard, Feature, and useCan share state.

Signature

tsx
import { RoleGuardProvider } from 'advanced-react-role-guard';

<RoleGuardProvider user={user} config={config}>
  {children}
</RoleGuardProvider>

Props

PropTypeDescription
userUser | null | undefinedCurrent user; defaults to null.
user.rolesstring[]Optional role names.
user.permissionsstring[]Optional direct permission strings.
configRoleGuardConfigOptional; defaults to {}.
config.rolesRecord<string, string[]>Maps role name → permission list (supports * and prefix:*).
config.featuresRecord<string, boolean>Feature flag map.
childrenReactNodeApp tree.

Behavior

  • Memoized contextuser and config are recomputed when dependencies change.
  • Children receive hasRole, hasPermission, hasAnyPermission, hasAllPermissions, and hasFeature through context (see useCan and Feature).

Edge cases

  • user is null or undefined — Treated as no roles and no permissions; role checks fail; permission checks fail unless you rely solely on config (feature flags still read config.features).
  • Empty config.roles — Only user.permissions (and * rules) apply.

Error / fallback

The provider does not throw on invalid props. Consumers throw if useRoleGuardContext / hooks are used outside the provider.

Examples

Simple

tsx
<RoleGuardProvider
  user={{ roles: ['viewer'] }}
  config={{
    roles: {
      viewer: ['doc:read'],
    },
  }}
>
  <App />
</RoleGuardProvider>

Advanced (roles + features)

tsx
<RoleGuardProvider
  user={{
    roles: ['editor'],
    permissions: ['audit:view'],
  }}
  config={{
    roles: {
      editor: ['post:*', 'comment:moderate'],
      admin: ['*'],
    },
    features: {
      newEditor: true,
    },
  }}
>
  <App />
</RoleGuardProvider>

Do / don’t

DoDon’t
Keep config.roles and user.roles naming alignedPut secrets in config expecting them to stay hidden
Pass plain objects for serialization across SSR boundariesRely on this provider alone for API security

Advanced exports

  • useRoleGuardContext — Low-level access to the full context value; throws if used outside RoleGuardProvider.
  • Exported typesUser, Role, Permission, RoleConfig, Features, RoleGuardConfig, RoleGuardProviderProps, etc.

Released under the MIT License.