Organizations SDK

SDK reference for the Organizations & RBAC feature. Covers types and utilities from @auth-gate/core, client methods, React hooks and components, and Next.js server helpers.


Core utilities

The @auth-gate/core package exports the types and permission-check utilities used across all packages.

Types

@auth-gate/core types

interface Organization {
  id: string;
  name: string;
  slug: string | null;
  created_at: string;
  updated_at: string;
}

interface OrgRole {
  id: string;
  key: string;
  name: string;
  description: string | null;
  permissions: string[];
  is_default: boolean;
}

interface OrgMembership {
  id: string;
  org_id: string;
  user_id: string;
  role: OrgRole;
  joined_at: string;
}

interface OrgMember {
  user_id: string;
  name: string | null;
  email: string | null;
  picture: string | null;
  membership: OrgMembership;
}

interface OrgInvitation {
  id: string;
  email: string;
  role: OrgRole;
  expires_at: string;
  created_at: string;
}

// Returned by listOrgs — org plus the calling user's membership
interface OrgWithMembership {
  org: Organization;
  membership: OrgMembership;
}

Permission utilities

All utilities accept an OrgMembership as the first argument. See Roles & Permissions for full usage examples.

Import

import {
  hasPermission,
  hasRole,
  hasAnyPermission,
  hasAllPermissions,
} from "@auth-gate/core";
FunctionSignatureReturns
hasPermission(membership, permission: string)boolean — membership has this permission (supports wildcards)
hasRole(membership, roleKey: string)boolean — membership role key matches exactly
hasAnyPermission(membership, permissions: string[])boolean — membership has at least one
hasAllPermissions(membership, permissions: string[])boolean — membership has every one

Client methods

AuthGateClient (from @auth-gate/core or instantiated via createAuthGate from @auth-gate/nextjs) exposes the following organization methods.

Organization CRUD

Org CRUD methods

// Create an organization
const { org } = await client.createOrg({
  name: "Acme Corp",
  slug: "acme-corp", // optional
});

// List organizations the current user belongs to
const { organizations } = await client.listOrgs();
// organizations: OrgWithMembership[]

// Get a single org by ID or slug
const { org } = await client.getOrg("acme-corp");

// Update org name or slug
const { org } = await client.updateOrg("acme-corp", {
  name: "Acme Corporation",
  slug: "acme-corporation",
});

// Delete an organization (admin only)
await client.deleteOrg("org_abc123");

Member management

Member management methods

// List all members of an org
const { members } = await client.listOrgMembers("acme-corp");
// members: OrgMember[]

// Update a member's role
await client.updateOrgMember("acme-corp", "user_xyz", {
  roleKey: "editor",
});

// Remove a member
await client.removeOrgMember("acme-corp", "user_xyz");

// Leave an org (current user removes themselves)
await client.leaveOrg("acme-corp");

Invitations

Invitation methods

// Send an invitation by email
const { invitation } = await client.inviteToOrg("acme-corp", {
  email: "alice@example.com",
  roleKey: "member", // optional — uses default role if omitted
});
// invitation: OrgInvitation

// List pending invitations
const { invitations } = await client.listOrgInvitations("acme-corp");
// invitations: OrgInvitation[]

// Revoke a pending invitation
await client.revokeOrgInvitation("acme-corp", "inv_abc123");

// Accept an invitation (called after the invited user authenticates)
const { membership } = await client.acceptOrgInvitation({
  token: "accept_token_from_email_link",
});
// membership: OrgMembership

React hooks

Import hooks from @auth-gate/react. All hooks fetch from the proxy API using the authenticated user's session.

useOrganizations(baseUrl?)

Lists all organizations the current user belongs to.

const { organizations, loading, error, refresh } = useOrganizations();
ReturnTypeDescription
organizationsOrgWithMembership[]All orgs with the user's membership in each
loadingbooleantrue while fetching
errorError | nullSet if the request failed
refresh() => voidRe-fetch the list

OrgSwitcher component

import { useOrganizations } from "@auth-gate/react";

function OrgSwitcher() {
  const { organizations, loading } = useOrganizations();

  if (loading) return <p>Loading organizations...</p>;

  return (
    <ul>
      {organizations.map(({ org, membership }) => (
        <li key={org.id}>
          {org.name} — {membership.role.name}
        </li>
      ))}
    </ul>
  );
}

useOrganization(orgIdOrSlug, baseUrl?)

Fetches a single organization and the current user's membership within it.

const { organization, membership, loading, error, refresh } =
  useOrganization("acme-corp");
ReturnTypeDescription
organizationOrganization | nullThe org details
membershipOrgMembership | nullThe user's membership (role + permissions)
loadingbooleantrue while fetching
errorError | nullSet if the request failed or user is not a member
refresh() => voidRe-fetch

useOrgMembers(orgIdOrSlug, baseUrl?)

Fetches the member list for an organization.

const { members, loading, error, refresh } = useOrgMembers("acme-corp");
ReturnTypeDescription
membersOrgMember[]All members with user info and membership details
loadingbooleantrue while fetching
errorError | nullSet if the request failed
refresh() => voidRe-fetch

MemberList component

import { useOrgMembers } from "@auth-gate/react";

function MemberList({ orgId }: { orgId: string }) {
  const { members, loading, error } = useOrgMembers(orgId);

  if (loading) return <p>Loading members...</p>;
  if (error) return <p>Could not load members.</p>;

  return (
    <ul>
      {members.map((member) => (
        <li key={member.user_id}>
          {member.name ?? member.email} — {member.membership.role.name}
        </li>
      ))}
    </ul>
  );
}

React components

OrgGuard

Conditionally renders children based on the current user's org membership, role, or permission. Shows fallback if the check fails, and loadingFallback while the membership is loading.

OrgGuard props

interface OrgGuardProps {
  orgId: string;
  permission?: string;   // check hasPermission
  role?: string;         // check hasRole (exact match)
  children: React.ReactNode;
  fallback?: React.ReactNode;        // shown when check fails (default: null)
  loadingFallback?: React.ReactNode; // shown while loading (default: null)
}

Usage examples

import { OrgGuard } from "@auth-gate/react";

// Gate by permission
<OrgGuard orgId={orgId} permission="documents:delete" fallback={<p>No access</p>}>
  <DeleteButton />
</OrgGuard>

// Gate by role
<OrgGuard orgId={orgId} role="admin" fallback={null}>
  <AdminPanel />
</OrgGuard>

// With loading state
<OrgGuard
  orgId={orgId}
  permission="org:manage"
  loadingFallback={<Spinner />}
  fallback={null}
>
  <ManageTeamButton />
</OrgGuard>

Next.js helpers

createOrgHelpers from @auth-gate/nextjs returns server-side helpers for use in Server Components, API routes, and middleware.

Initialize helpers

import { createOrgHelpers } from "@auth-gate/nextjs";

const orgHelpers = createOrgHelpers({
  baseUrl: process.env.AUTHGATE_URL!,
  apiKey: process.env.AUTHGATE_API_KEY!,
});

const { getOrgMembership, checkPermission, listUserOrgs, listOrgMembers } =
  orgHelpers;

getOrgMembership(orgIdOrSlug, userId)

Fetches the membership record for a user in an organization. Returns null if the user is not a member.

Server Component example

import { getSession } from "@/lib/auth";
import { getOrgMembership } from "@/lib/org-helpers";
import { hasPermission } from "@auth-gate/core";

export default async function OrgPage({ params }: { params: { slug: string } }) {
  const user = await getSession();
  const membership = await getOrgMembership(params.slug, user!.id);

  if (!membership) {
    return <p>You are not a member of this organization.</p>;
  }

  const canManage = hasPermission(membership, "org:manage");

  return (
    <div>
      <h1>Organization Dashboard</h1>
      {canManage && <ManageTeamLink />}
    </div>
  );
}

checkPermission(orgIdOrSlug, userId, permission)

Convenience wrapper — fetches the membership and checks a single permission. Returns boolean.

const canDelete = await checkPermission(orgId, userId, "documents:delete");
if (!canDelete) {
  return Response.json({ error: "Forbidden" }, { status: 403 });
}

listUserOrgs(userId)

Returns all organizations a user belongs to, with their membership in each.

const orgs = await listUserOrgs(userId);
// orgs: OrgWithMembership[]

listOrgMembers(orgIdOrSlug)

Returns all members of an organization.

const members = await listOrgMembers("acme-corp");
// members: OrgMember[]

Was this page helpful?