AuthIntermediateSSR-safehooks/auth/useHasRole.ts

useHasRole

Check one or many roles.

Import

TypeScript
import { useHasRole } from '@/hooks';

API

Signature

useHasRole(required, mode? 'all'|'any') → boolean

When to use

Use useHasRole instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Provider can wrap client layouts; seed isLoading during session hydrate.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useHasRole
Editor
function AdminLink() {
  const isAdmin = useHasRole('admin');
  return isAdmin ? <a href="/admin">Admin</a> : null;
}
Preview

Implementation source

Full library source for useHasRole — copy into your project when you are not installing a package yet.

hooks/auth/useHasRole.ts
import { useMemo } from 'react';
import { useRole } from './useRole';

/** Check one or more roles (default: any match). */
export function useHasRole(
  required: string | string[],
  mode: 'all' | 'any' = 'any',
): boolean {
  const roles = useRole();
  return useMemo(() => {
    const list = Array.isArray(required) ? required : [required];
    if (list.length === 0) return true;
    return mode === 'all'
      ? list.every((r) => roles.includes(r))
      : list.some((r) => roles.includes(r));
  }, [roles, required, mode]);
}

Copy-paste example

useHasRole.example.tsx
'use client';

import { useHasRole } from '@/hooks';

export function AdminLink() {
  const isAdmin = useHasRole('admin');
  return isAdmin ? <a href="/admin">Admin</a> : null;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Wrap the tree with AuthProvider and pass your session shape — keep it generic.
  • Source of truth: open hooks/auth/useHasRole.ts for implementation details