Skip to content

Control Plane Architecture ​

The multi-tenancy package uses a control plane architecture where a central tenant manages and provisions all other tenants in the system.

Overview ​

The control plane acts as the management layer for your entire multi-tenant system:

  • Centralized Management: All tenant management operations happen on the control plane
  • Entity Synchronization: Resource servers and roles from the control plane are synced to child tenants
  • Organization Mapping: Organizations on the control plane map to individual child tenants
  • Access Control: Controls who can access which tenants via organization membership

Control Plane vs Child Tenants ​

┌───────────────────────────────────────────────────────────────────────┐
│                        CONTROL PLANE (main)                           │
│                                                                       │
│  Organizations                    System Entities                     │
│  ┌───────────────┐               ┌──────────────────┐                 │
│  │ org: "acme"   │               │ Resource Servers │                 │
│  │ users:        │               │  - Management API│                 │
│  │  - alice      │               │  - My API        │                 │
│  │  - bob        │               │                  │                 │
│  └───────────────┘               │ Roles            │                 │
│                                  │  - Admin         │                 │
│  ┌───────────────┐               │  - User          │                 │
│  │ org: "widgets"│               │  - Viewer        │                 │
│  │ users:        │               └──────────────────┘                 │
│  │  - charlie    │                                                    │
│  └───────────────┘                                                    │
│                                                                       │
└─────────────────┬─────────────────────────────────┬───────────────────┘
                  │ Synced Entities                 │
                  ▼                                 ▼
       ┌──────────────────┐              ┌──────────────────┐
       │ TENANT: acme     │              │ TENANT: widgets  │
       │                  │              │                  │
       │ Organizations    │              │ Organizations    │
       │  - Sales Dept    │              │  - Engineering   │
       │  - Marketing     │              │  - Product       │
       │                  │              │                  │
       │ Resource Servers │              │ Resource Servers │
       │  - Management API│ (synced)     │  - Management API│ (synced)
       │  - My API        │ (synced)     │  - My API        │ (synced)
       │                  │              │                  │
       │ Roles            │              │ Roles            │
       │  - Admin         │ (synced)     │  - Admin         │ (synced)
       │  - User          │ (synced)     │  - User          │ (synced)
       │  - Viewer        │ (synced)     │  - Viewer        │ (synced)
       │                  │              │                  │
       │ Users            │              │ Users            │
       │  - end-user-1    │              │  - end-user-2    │
       │  - end-user-2    │              │  - end-user-3    │
       └──────────────────┘              └──────────────────┘

Key Differences ​

AspectControl PlaneChild Tenants
PurposeManages all tenantsIsolated customer environments
OrganizationsMap to child tenantsInternal business units
Users on OrgsTenant administratorsNot used for tenant access
Resource ServersSynced to all tenantsSynced from control plane
RolesSynced to all tenantsSynced from control plane
End UsersSystem administratorsCustomer end users

Entity Synchronization ​

When you create or update entities on the control plane, they are automatically synchronized to all child tenants.

Synced Entities ​

1. Resource Servers ​

Resource servers created on the control plane are automatically synced to all child tenants with the is_system: true flag.

typescript
// Create a resource server on control plane
await adapters.resourceServers.create("main", {
  name: "My API",
  identifier: "https://api.example.com",
  scopes: [
    { value: "read:data", description: "Read data" },
    { value: "write:data", description: "Write data" },
  ],
});

// Automatically synced to all child tenants:
// - tenant: acme
// - tenant: widgets
// - tenant: demo
// All with is_system: true

Key Points:

  • Marked as is_system: true on child tenants
  • Cannot be modified on child tenants
  • Updates on control plane are synced to all tenants
  • Deletions on control plane remove from all tenants

2. Roles ​

Roles created on the control plane are automatically synced to all child tenants.

typescript
// Create a role on control plane
await adapters.roles.create("main", {
  name: "Admin",
  description: "Administrator role",
});

// Automatically synced to all child tenants with is_system: true

Key Points:

  • Marked as is_system: true on child tenants
  • Cannot be modified on child tenants
  • Role permissions are also synced
  • Updates and deletions are propagated

3. Role Permissions ​

When roles are synced, their permissions are also synchronized.

typescript
// Assign permissions on control plane
await adapters.rolePermissions.assign("main", adminRoleId, [
  {
    role_id: adminRoleId,
    resource_server_identifier: "https://api.example.com",
    permission_name: "read:data",
  },
]);

// Permissions are synced to the same role on all child tenants

Opting Out of Sync ​

To keep a resource server or role on the control plane only — without propagating it to child tenants — set metadata.sync to false:

typescript
// Control-plane-only API; never synced to child tenants
await adapters.resourceServers.create("main", {
  name: "Internal Ops API",
  identifier: "https://ops.internal.example.com",
  metadata: { sync: false },
});

The default sync filter checks metadata.sync !== false before mirroring to child tenants, and it applies in both directions:

  • New or updated entities on the control plane are not pushed out.
  • Newly created child tenants do not receive the entity at provisioning time.

The same flag works for roles. For more elaborate rules, supply custom filters when constructing the hooks; they compose with the metadata.sync check rather than replacing it (an entity must pass both to be synced):

typescript
const { entityHooks, tenantHooks } = createSyncHooks({
  controlPlaneTenantId: "main",
  getChildTenantIds,
  getAdapters,
  getControlPlaneAdapters,
  filters: {
    resourceServers: (rs) => !rs.identifier.startsWith("https://internal."),
  },
});

Configuration ​

Enable entity synchronization when setting up multi-tenancy:

initMultiTenant wires the sync hooks for you. For a manual setup, create them with createSyncHooks, give the tenant hooks to the tenants router, and pass the entity hooks and the router to init():

typescript
import { init } from "authhero";
import {
  createSyncHooks,
  createTenantsOpenAPIRouter,
} from "@authhero/multi-tenancy";

const { entityHooks, tenantHooks } = createSyncHooks({
  controlPlaneTenantId: "main",
  getChildTenantIds,
  getAdapters: async (tenantId) => getTenantAdapters(tenantId),
  getControlPlaneAdapters: async () => mainAdapters,
  sync: {
    resourceServers: true,
    roles: true,
  },
});

// Tenant hooks copy the synced entities into a newly created tenant
const tenantsRouter = createTenantsOpenAPIRouter(
  { accessControl: { controlPlaneTenantId: "main" } },
  { tenants: tenantHooks },
);

const { app } = init({
  dataAdapter: mainAdapters,
  // Entity hooks mirror control-plane changes to the child tenants
  entityHooks,
  // Mount the tenants router inside the management API (/api/v2/tenants)
  managementApiExtensions: [
    { path: "/tenants", router: tenantsRouter, controlPlane: true },
  ],
});

Connections are not synced; child tenants read them from the control plane through the runtime fallback.

Protected Entities Middleware ​

System entities synced from the control plane are protected from modification on child tenants:

initMultiTenant installs this guard for you when sync is enabled. With a manual setup, pass it to init():

typescript
import { init } from "authhero";
import { createProtectSyncedMiddleware } from "@authhero/multi-tenancy";

const { app } = init({
  dataAdapter,
  managementApiMiddleware: [createProtectSyncedMiddleware()],
});

// Now attempts to modify synced entities will return 403
// PATCH /api/v2/roles/:id (where is_system: true)
// Response: 403 "This role is a system resource and cannot be modified"

managementApiMiddleware runs inside the management API, after authentication and before the route handlers. Don't add the guard with app.use("/api/v2/*", …) on the app that init() returns. The management routes are already mounted at that point, and Hono never runs middleware registered after the handler that answers. The guard would never run, and synced roles and connections would be writable.

Organizations: Control Plane vs Child Tenants ​

Organizations serve different purposes depending on where they exist:

Organizations on Control Plane ​

Organizations on the control plane represent child tenants:

typescript
// Create a new tenant
await fetch("/management/tenants", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    id: "acme",
    friendly_name: "Acme Corporation",
  }),
});

// This automatically creates:
// 1. Tenant with id "acme"
// 2. Organization on control plane with name "acme"

Key characteristics:

  • Organization name = tenant ID
  • Membership controls tenant administrator access
  • Used for access control to tenant management APIs

Example use case:

typescript
// Alice is added to the "acme" organization on control plane
// This grants her access to manage the acme tenant via:
// - Token with org_name: "acme" or organization_id: "acme"
// - Can call management APIs for acme tenant

Organizations on Child Tenants ​

Organizations on child tenants represent internal business units within that tenant:

typescript
// On the "acme" tenant, create departments
await adapters.organizations.create("acme", {
  name: "sales-dept",
  display_name: "Sales Department",
});

await adapters.organizations.create("acme", {
  name: "engineering",
  display_name: "Engineering Department",
});

Key characteristics:

  • Represent departments, teams, or business units
  • Used for B2B customer organization management
  • Not used for tenant access control
  • End users belong to these organizations

Example use case:

typescript
// Acme Corporation has two departments:
// 1. Sales Department - has access to CRM features
// 2. Engineering - has access to technical resources
// End users get tokens with org_id for their department

API Access Methods ​

There are three ways to call tenant-scoped APIs:

Request a token with an organization claim via silent authentication:

typescript
// Get token for "acme" tenant
const token = await auth.getTokenSilently({
  authorizationParams: {
    organization: "acme",
  },
});

// Call any API for acme tenant
const response = await fetch("https://api.example.com/api/v2/users", {
  headers: {
    Authorization: `Bearer ${token}`,
  },
});

// Token contains org_name: "acme" or organization_id: "org_xxx"
// Middleware automatically routes to acme tenant

How it works:

  • Token includes org_name: "acme" (if allow_organization_name_in_authentication_api is enabled)
  • Or organization_id: "org_xxx" where org.name = "acme"
  • Access control middleware validates organization membership on control plane
  • Request is automatically scoped to the acme tenant

An organization token is bound to its tenant. The token carries the permissions of that organization's roles, and on the control plane an organization is a tenant, so the management API refuses it anywhere else with 403: on another tenant named in tenant-id, and on the control plane's own context. The one exception is the tenants router (/tenants, /tenants/{id} and what hangs off it) in the control plane's context, which checks access per organization itself; /tenants/settings, /tenants/{id}/operations and /tenants/{id}/config-sync are not part of it, since the first acts on the tenant the request is in and the others do no per-organization check. Deleting a tenant with an organization token also requires that token to be for that tenant's organization; membership of it is not enough. A token whose organization is only given by org_id is bound to that organization's name, and one that names no organization is refused. That refusal applies on the tenants router as well. On GET /tenants, a token that carries only org_name counts as organization-scoped like one with org_id, so admin:organizations in it does not return every tenant. A token without an organization claim is not affected, and neither is a token issued by a child tenant. Work on the control plane itself, or across tenants, with a token that is not scoped to an organization.

Best for:

  • Production applications
  • Frontend/mobile apps
  • Standard OAuth2/OIDC flows

2. Control Plane Token + Tenant Header ​

Use a control plane token with an explicit tenant ID header:

typescript
// Get control plane token (no organization)
const token = await auth.getTokenSilently();

// Call API with tenant header
const response = await fetch("https://api.example.com/api/v2/users", {
  headers: {
    Authorization: `Bearer ${token}`,
    "X-Tenant-ID": "acme", // or "tenant-id": "acme"
  },
});

How it works:

  • Token is for control plane (no org_id)
  • Tenant header explicitly specifies target tenant
  • Access control validates user has access to specified tenant
  • Request is scoped to the tenant from header

Best for:

  • Administrative scripts
  • Backend services
  • Migration tools
  • Testing scenarios

3. Tenant-Specific Token ​

Request a token directly from a tenant's token endpoint. For a backend service this is the client_credentials grant, with a client of the acme tenant that has a client grant for its Management API:

typescript
// Machine-to-machine token from the acme tenant
const tokenResponse = await fetch("https://acme.auth.example.com/oauth/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "client_credentials",
    client_id: "acme_m2m_client_id",
    client_secret: "acme_m2m_client_secret",
    audience: "https://acme.auth.example.com/api/v2/",
  }),
});
const { access_token } = await tokenResponse.json();

// Use token for acme tenant
const response = await fetch("https://acme.auth.example.com/api/v2/users", {
  headers: {
    Authorization: `Bearer ${access_token}`,
  },
});

The password grant (grant_type=password) is not supported. Users sign in to a tenant through /authorize and its login pages instead.

How it works:

  • Subdomain routing determines tenant (acme.auth.example.com → acme)
  • Token is issued specifically for acme tenant
  • No organization claim needed
  • Request is automatically scoped via subdomain

Best for:

  • Subdomain-based deployments
  • Tenant-specific domains
  • White-label scenarios
  • Isolated tenant access

Comparison Table ​

MethodToken TypeTenant SelectionUse Case
Organization TokenControl plane with org claimVia org_name/organization_idProduction apps, standard OAuth flow
Token + HeaderControl planeVia X-Tenant-ID headerAdmin tools, backend services
Tenant TokenTenant-specificVia subdomainWhite-label, isolated deployments

Access Control Flow ​

Accessing Control Plane ​

typescript
// User alice has no organization claim - token for control plane access
const token = {
  sub: "alice",
  // No org_id or org_name
};

// ✅ Can access control plane management APIs
const response = await fetch("/management/tenants", {
  headers: {
    Authorization: `Bearer ${accessToken}`,
  },
});

// ✅ Can list all tenants alice has access to
// (based on organization memberships on control plane)

Accessing Child Tenant ​

typescript
// User alice is member of "acme" organization on control plane
const token = {
  sub: "alice",
  org_name: "acme", // or organization_id: "org_xxx"
};

// ✅ Can access acme tenant
const response = await fetch("/api/v2/users", {
  headers: {
    Authorization: `Bearer ${accessToken}`,
  },
});

// ❌ Cannot access widgets tenant (not a member of that organization)
const forbidden = await fetch("/api/v2/users", {
  headers: {
    Authorization: `Bearer ${accessToken}`,
    "X-Tenant-ID": "widgets",
  },
});
// Response: 403 Forbidden

Self-service sign-up: let new users create a tenant ​

By default nobody can create a tenant except users an operator has given create:tenants. A person who signs up on the control plane gets a token with no permissions, so the admin UI can only tell them to ask an administrator. selfServiceSignup closes that gap:

typescript
initMultiTenant({
  dataAdapter,
  controlPlane: { tenantId: "main", clientId: "main_client" },
  selfServiceSignup: true,
  // or pick the role name: selfServiceSignup: { roleName: "Tenant Creator" },
});

Once a user's email is verified, they get a global role (default name Tenant Creator) on the control plane. The role carries three permissions on the Management API and nothing else: create:tenants, read:tenant_operations and retry:tenant_provisioning. Not read:tenants, delete:tenants or admin:organizations. The role is created the first time it is needed, and any of the three that are missing are added to it, and to the Management API resource server's scopes if it does not define them yet. Permissions an operator adds to the role are never removed.

  • Users who arrive with a verified email (social, passwordless) get the role at registration. Password sign-ups get it when they verify their email.
  • Only sign-ups on the control plane get it. Sign-ups on child tenants never do.
  • Existing users are not backfilled. Give them the role yourself if you want them to create tenants.
  • It runs through onExecutePostUserRegistration and onExecutePostUserUpdate, ahead of any hooks you configure. A failure is logged and never fails the sign-up.
  • The control plane's admin client must put permissions in the access token (turn on RBAC and "add permissions to the access token"), or the admin UI will not see the role.

After the user creates a tenant they become admin of the tenant's organization, as for any creator. Creating a tenant provisions real resources, so cap how many one user can create (next section). Without a cap, leave this off unless you accept the cost.

Limit how many tenants a user can create ​

tenantCreationLimits caps tenant creation for callers who are not operators. It applies to every tenant a user creates, whether shared or wfp.

typescript
initMultiTenant({
  dataAdapter,
  controlPlane: { tenantId: "main", clientId: "main_client" },
  selfServiceSignup: true,
  tenantCreationLimits: {
    perUser: 3, // a number, null for unlimited, or (user) => number | null
    // blockWhilePending: true (default)
  },
});
  • Tenants per user. POST /tenants is refused with 403 once the caller owns perUser tenants, that is the tenants whose organization they belong to with the owner role. The message names the limit and the admin's create form shows it. perUser can be a function, so a plan can decide the number per user.
  • One provisioning at a time. While a tenant the user owns is still pending, creating another is refused with 403. Turn it off with blockWhilePending: false.
  • Raise or lift the limit for one user. Set app_metadata.tenant_limit on the user to a number, or to "unlimited". It wins over perUser, takes effect on the next request and needs no deploy. (null does not work: a metadata update treats it as removing the key.)
  • Operators are exempt. A caller whose token carries delete:tenants, admin:organizations, create:tenant_operations or create:rollouts, which includes machine tokens.
  • Fails closed. If the counts cannot be read, the request is refused with 503.
  • Unset means unchanged. Without tenantCreationLimits nothing is checked.

What this does not cover: how fast a user creates tenants (there is no rate limit per time window), per-endpoint rate limiting on the rest of the Management API, plans and billing, and email verification strength or CAPTCHA at sign-up. Deleting a tenant frees a slot, so a user can create and delete repeatedly.

The limit is a check before creation, not an atomic reservation: two requests from the same user sent at the same moment can both pass it and go one over. It bounds steady-state abuse, not a burst. An organization-scoped token is never exempt, whatever scopes it carries, and tenantCreationLimits needs managed tenant roles (accessControl.issuer or provisionRoles; initMultiTenant always has them), because the count is by the owner role.

The two operations permissions are what lets the admin show the new user their provisioning: the steps and the failure reason (read:tenant_operations) and a retry (retry:tenant_provisioning). They are safe to hold globally because the tenant operations routes only answer for tenants the caller is a member of. The exception is operators: a machine token, or a caller holding create:tenant_operations, create:rollouts or admin:organizations, reaches every tenant when its token is not scoped to an organization, so for them read:tenant_operations is not limited to their own tenants. Upgrade authhero and @authhero/multi-tenancy together: an authhero without that check would let any holder of read:tenant_operations read every tenant's operations.

Default settings for new tenants ​

tenantDefaults sets the tenant row's own settings when a tenant is created: MFA, attack protection, flags, sessions and the other fields on the tenant. It is a copy, not inheritance. The tenant owns the values from then on, so a later change to tenantDefaults does not reach existing tenants, and the tenant can change every one of them.

typescript
initMultiTenant({
  dataAdapter,
  controlPlane: { tenantId: "main", clientId: "main_client" },
  tenantDefaults: {
    mfa: { policy: "confidence" },
    flags: { disable_impersonation: true },
  },
});
  • The request wins. A value in the POST /tenants body replaces the default. Nested objects such as flags merge key by key, and arrays are replaced whole.
  • A function works too. tenantDefaults: (params, ctx) => ({ ... }) is called per creation, so a plan can decide the values.
  • Not for identity or sync fields. id, friendly_name, audience, parent_tenant_id and the config_sync fields are not accepted.
  • Login version. A new tenant gets the flag universal_login_version: "2", so its applications log in through /u2. tenantDefaults or the request can set it to "1", but the default application is still created with its own "2" override, so change or remove that override too if the default application should use /u. See Login version.
  • Unset means unchanged. Without tenantDefaults nothing is applied.
  • Tenants with their own database too. A wfp tenant reads its row from its own database, not the control plane's. When it is provisioned, the seed that creates that row copies the tenant's settings from the control plane's copy of its row (where tenantDefaults were applied), so the defaults reach it as well. Only the tenant row's settings travel: identity, deployment and sync fields stay on the control plane, as do default_client_id and the other references to rows elsewhere, and the Twilio auth_token under mfa is never copied. The row is created only if missing, so a later sync never overwrites settings the tenant has changed.

Rows such as connections, resource servers and branding are not set here: they come from the control plane through sync-defaults according to their scope.

The role a tenant's creator gets ​

Creating a tenant makes an organization on the control plane (named after the tenant id), adds the creator to it and gives them a role scoped to that organization. That role is what the creator's token carries when they work in the tenant.

  • Tenant Admin (adminRoleName): every management scope. A creator gets it only if they already hold the operator scopes globally: create:tenants, delete:tenants, read, create and update:rollouts, and read and create:tenant_operations (admin:organizations and access:all_organizations do not count: a creator who holds admin:organizations is not added to the organization at all). That way the role in the tenant's organization never grants more than the creator already had.
  • Tenant Owner (ownerRoleName): every management scope except the operator-only ones: create:tenants, delete:tenants, admin:organizations, access:all_organizations, the rollout scopes and the tenant-operation scopes. Everyone else gets this one, a self-service creator from selfServiceSignup (Tenant Creator) included, and so does a creator who got create:tenants through a direct permission or a custom role without the rest. With the role as provisioning builds it, a customer can run their own tenant but not create or delete tenants, reach other organizations or start fleet rollouts, and they cannot delete their own tenant for now. That holds only while the role has nothing but what provisioning put there (see the note below about existing roles).

initMultiTenant creates and assigns these roles on every tenant creation (provisionRoles). setupMultiTenancy keeps its older rule of only creating roles when accessControl.issuer is set. A role that already exists is kept up to date: scopes it lacks are added to it every time a tenant is created, and permissions an operator put on it are never removed. That also means a scope you took off the Tenant Admin or Tenant Owner role on purpose comes back on the next tenant creation, under whatever name the role has: renaming a role with adminRoleName or ownerRoleName only changes the name. What provisioning adds is fixed in code: it never adds the operator-only scopes to the owner role, and the admin role goes only to a creator who already holds them. It does not take anything away, so an owner role that already carries operator-only scopes (an operator put them there, or a role of that name existed before) keeps them and every owner gets them. The owner scope list is what provisioning adds, not a ceiling: look at an existing role before you rely on it. A creator who already has a role is not moved to another one. Which role a creator gets is decided by what they hold globally when they create the tenant.

A management scope added later reaches tenant owners unless it is listed as operator-only. A test freezes the owner's scope list, so adding a scope to the Management API means deciding which side it belongs on.

Example: Complete Multi-Tenant Setup ​

typescript
import { initMultiTenant } from "@authhero/multi-tenancy";
import createAdapters from "@authhero/drizzle";

const { app } = initMultiTenant({
  dataAdapter: createAdapters(db),

  // The control plane: the tenant that manages all others
  controlPlane: { tenantId: "main", clientId: "main-client" },

  // Sync resource servers and roles to child tenants (this is the default)
  sync: { resourceServers: true, roles: true },

  // Database isolation per tenant — the callbacks are your own code
  databaseIsolation: {
    getAdapters: (tenantId) => getTenantAdapters(tenantId),
    onProvision: (tenantId) => provisionTenantDatabase(tenantId),
    onDeprovision: (tenantId) => deprovisionTenantDatabase(tenantId),
  },
});

initMultiTenant also installs the tenant routes, access control and the protection of synced entities. Subdomain routing is configured separately — see Subdomain Routing.

The /connect/start endpoint mints an RFC 7591 Initial Access Token bound to user consent — a third-party site (e.g. a WordPress publisher) sends the user's browser to AuthHero, the user confirms, and the resulting IAT can be exchanged for a registered client at POST /oidc/register.

When the request resolves to a control plane tenant, the flow gains an extra workspace-picker step so the IAT (and the client it produces) lands on the right child tenant. When the request resolves to a child tenant directly, the picker is skipped.

Detecting the mode ​

The connect screen branches on data.multiTenancyConfig.controlPlaneTenantId, which withRuntimeFallback (and therefore initMultiTenant) sets on the data adapter automatically. No extra wiring is required — if you initialised AuthHero with the multi-tenancy plugin, control-plane mode is already on.

How the picker works ​

Browser → GET /connect/start?…           ← request resolves to control plane
AuthHero → 302 /u2/connect/start?state=<sid>
        → no session: 302 /u2/login/identifier?state=<sid>
        → after login: 302 /u2/connect/select-tenant?state=<sid>
User    → picks workspace (one button per accessible org)
        → state_data.connect.target_tenant_id is persisted
        → 302 /u2/connect/start?state=<sid>
        → consent screen renders, showing the chosen workspace
User    → confirms
AuthHero → mint IAT on the *child* tenant
         → 302 return_to?authhero_iat=<token>
                       &authhero_tenant=<child_tenant_id>
                       &state=<csrf>

The picker enumerates the user's organizations on the control plane via userOrganizations.listUserOrganizations. Each organization name maps 1:1 to a child tenant id (the convention enforced by the provisioning hooks — org.name === tenant.id), and any orgs that don't resolve to an existing tenant are filtered out.

Membership is re-validated when consent is submitted, so a stale or tampered target_tenant_id cannot mint on a workspace the user has lost access to between picker and consent.

Direct-to-child mode ​

If the request resolves to a child tenant — for example via a custom domain like acme.auth.example.com that maps to the acme tenant — the picker step is bypassed entirely. The flow is identical to the single-tenant case: login → consent → IAT minted on the resolved tenant. No authhero_tenant parameter is added to the redirect because the integrator already knows the tenant from the URL it pointed at.

The authhero_tenant callback parameter ​

When the IAT is minted on a tenant different from the request's resolved tenant (i.e. always in control-plane mode, never in direct-to-child mode), the success redirect appends authhero_tenant=<child_tenant_id> alongside authhero_iat. The integrator must use this value as the tenant-id header on POST /oidc/register so the registration call is routed to the correct tenant.

js
// Example: a CMS handling the connect callback
const url = new URL(window.location.href);
const iat = url.searchParams.get("authhero_iat");
const tenant = url.searchParams.get("authhero_tenant"); // present only in control-plane mode

await fetch("https://auth2.example.com/oidc/register", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${iat}`,
    "tenant-id": tenant ?? "", // omit entirely if not present (direct-to-child)
    "content-type": "application/json",
  },
  body: JSON.stringify({
    client_name: "My WordPress Site",
    redirect_uris: ["https://publisher.com/wp-admin/callback"],
    grant_types: ["client_credentials"],
  }),
});

The IAT itself enforces all the constraints captured at consent time (domain, integration_type, grant_types, optional scope) — those are not affected by which tenant minting happens on.

Choosing your entry point ​

Pick the mode that matches the integrator's view of your system:

Entry pointModeWhen to use
Control plane host (auth2.sesamy.com)Control planeA single canonical URL across all integrators. Users without a per-tenant subdomain. The picker is the natural place to disambiguate which workspace owns the connection.
Child tenant host (acme.auth…)Direct-to-childThe integrator already knows which tenant they're connecting to (e.g. white-label deployments, self-service sign-up that bakes the tenant into the install).

Both modes can coexist on the same AuthHero deployment — there is no global setting to flip.

Limitations ​

  • The picker assumes a single shared database or per-tenant databases reachable from the same data adapter. With strict database isolation, control-plane minting needs the runtime to swap adapters before calling mintIat against the chosen child — that wiring is not yet exposed.
  • Users with zero matching organizations see a "no workspaces available" message instead of the picker; they cannot complete the connect flow until invited.

Custom domains: the control plane is authoritative ​

A Cloudflare-for-SaaS custom hostname is an account-global resource in one shared zone. Two things follow, and both of them are impossible on a tenant shard:

  • Registering the hostname needs Cloudflare account credentials (zoneId / authKey / authEmail). By design those live only on the control plane.
  • Claiming the hostname exactly once needs a view across every tenant. Two WFP tenants can't both own login.acme.com, but neither tenant's database can see the other's rows.

So the control plane owns the row and the tenant's database holds a read-cache mirror. A tenant shard writes through the control plane synchronously rather than writing locally and replicating upward.

tenant: POST /api/v2/custom-domains
  → createControlPlaneCustomDomainsAdapter
      → POST {control plane}/api/v2/proxy/control-plane/custom-domains
          1. hostname owned by another tenant? → 409, nothing written anywhere
          2. register the hostname in Cloudflare (account credentials live here)
          3. persist the authoritative row
      → 2xx: mirror the row into the tenant's own database
      → 409: surface the conflict; write nothing locally

Nothing is written locally on a conflict, which is what prevents the half-provisioned, unroutable row this design replaces.

Tenant shard ​

Wrap the shard's own customDomains adapter as the mirror:

typescript
import {
  createControlPlaneClient,
  createControlPlaneCustomDomainsAdapter,
  createServiceBindingFetch,
  createServiceTokenCore,
} from "authhero";

const client = createControlPlaneClient({
  baseUrl: env.CONTROL_PLANE_URL,
  // On Workers for Platforms, route the call over a service binding to the
  // control-plane Worker. A tenant Worker in the dispatch namespace calling the
  // public edge would leave Cloudflare and re-enter through the proxy that
  // dispatched it. Omit it and the call falls back to the public edge.
  fetchImpl: createServiceBindingFetch(env.CONTROL_PLANE),
  // Signed by this shard's own key; the control plane verifies it against the
  // shard's published JWKS. No shared client secret.
  getServiceToken: async (tenantId, scope) => {
    const token = await createServiceTokenCore({
      tenants: adapters.tenants,
      keys: adapters.keys,
      tenantId,
      scope,
      issuer,
    });
    return token.access_token;
  },
});

const dataAdapter = {
  ...adapters,
  customDomains: createControlPlaneCustomDomainsAdapter({
    client,
    mirror: adapters.customDomains,
  }),
};

Read freshness. get/list trust the mirror once a domain is ready. A fresh domain is pending until the customer adds the DV record, and that transition happens at the control plane — so a non-ready row is refreshed upstream on read. getByDomain always reads the mirror: it is on the tenant-resolution path for every request to a custom domain and must never take a network hop.

Control plane ​

Mount the authoritative resource by passing the Cloudflare adapter (wrapping the control-plane database) as proxyControlPlane.customDomains:

typescript
import createCloudflareAdapters from "@authhero/cloudflare-adapter";

export default init({
  dataAdapter,
  proxyControlPlane: {
    resolveHost: createProxyDataAdapter(db).resolveHost,
    customDomains: createCloudflareAdapters({
      zoneId: env.CLOUDFLARE_ZONE_ID,
      authKey: env.CLOUDFLARE_API_KEY,
      authEmail: env.CLOUDFLARE_API_EMAIL,
      customDomainAdapter: dataAdapter.customDomains,
    }).customDomains,
  },
});

Tokens for this resource must carry the controlplane:custom_domains scope; the resource is not mounted when no adapter is configured.

Authorization is bound to the token's tenant. Every shard holds this scope, so the scope says who is calling, not what they may touch. Each operation acts on the tenant_id claim of the verified token: a request naming a different tenant is refused with 403, and a token with no tenant claim is refused outright. The same rule applies to POST /sync — a shard may only replicate its own rows.

Without CONTROL_PLANE_URL, a tenant shard refuses custom-domain writes (501) rather than writing a local row that Cloudflare never hears about. Reads keep working, so any domain already mirrored there still resolves.

Tenant team: self-service member management ​

A tenant's team — the people who administer it — is not the tenant's users. It is an organization on the control-plane tenant whose name equals the tenant id, its members are control-plane users, and their access is an org membership plus an org-scoped role. A tenant shard cannot write those rows. Putting administrators in the tenant's own users table would be a category error, and letting the org-scoped token call the control-plane organizations/{id}/members endpoints directly is unsafe — those routes are permission-gated but not scoped to the caller's own organization, so a tenant admin could edit other tenants' teams by changing the id in the URL.

This is the same shape as custom domains — an authoritative side effect the shard can't perform — but with no read-cache mirror: nothing in the tenant's request path ever reads "who administers me" (authorization already happens against the org_name/org_id claim the control plane put in the token). So it is a pure pass-through delegation, not write-through-plus-cache.

tenant admin → GET/POST/DELETE /api/v2/tenant-members        (on the shard)
  → pin: token org_name must equal the request tenant  ── else 403
  → createControlPlaneTenantMembersAdapter
      → …/api/v2/proxy/control-plane/tenant-members          (on the control plane)
          → pin again: act on the verified token's tenant_id ── else 403
          → resolve org (name == tenant_id), then read/write
            membership · org-scoped roles · invitations

Two independent org pins. The shard's /api/v2/tenant-members resource requires the token's org_name claim to equal the request tenant, so a tenant-A admin cannot manage tenant B by swapping the tenant-id header. The control-plane resource then re-pins to the verified service token's tenant_id claim. A request that names a different tenant is refused with 403 at both hops. Tokens for the control-plane resource carry the controlplane:tenant_members scope.

Tenant shard ​

Enable the resource with tenantMembers.getBackend, returning a control-plane-backed adapter that reuses the same client as custom domains:

typescript
import { createControlPlaneTenantMembersAdapter } from "authhero";

export default init({
  dataAdapter,
  // `client` is the createControlPlaneClient from the custom-domains wiring above.
  tenantMembers: {
    getBackend: () => createControlPlaneTenantMembersAdapter({ client }),
  },
});

Control plane ​

Mount the authoritative resource with proxyControlPlane.tenantMembers. Its backend resolves the org and mutates the control-plane database directly:

typescript
import { createLocalTenantMembersBackend } from "authhero";

export default init({
  dataAdapter,
  proxyControlPlane: {
    resolveHost: createProxyDataAdapter(db).resolveHost,
    tenantMembers: {
      getBackend: (c) =>
        createLocalTenantMembersBackend({
          data: c.env.data, // control-plane adapters
          controlPlaneTenantId: CONTROL_PLANE_TENANT_ID,
          issuer, // builds invitation acceptance links + default avatars
          invitationClientId: env.INVITATION_CLIENT_ID,
          // Email invitations with the built-in template, as the control-plane
          // tenant. Pass `sendInvitationEmail` instead to use your own sender.
          ctx: c,
        }),
    },
  },
});

The resource authenticates shards itself (a controlplane:tenant_members token), so tenantMembers needs no authenticate. With ctx: c, invitations created by a shard are emailed the same way as on a single instance (below). Without ctx or sendInvitationEmail, the invitation is still created and returned; only email delivery is skipped (like Auth0).

Team changes as requests ​

By default a write on the shard (invite, add or remove a member, assign or remove roles, revoke an invitation) is forwarded to the control plane in the same call, so the Team page fails when the control plane is slow or down and the shard keeps no record of what was asked. With tenantMembers.requests the shard registers the change as a request in its own database, tells the control plane, and the control plane carries it out later:

tenant admin → POST /api/v2/tenant-members/invitations         (on the shard)
  → pin: token org_name must equal the request tenant ── else 403
  → store a `tenant_member_requests` row: pending, requested_by = the admin's sub
  → 202 { id, status: "pending" }
  → tell the control plane (request id only, best effort)
      → POST …/proxy-control-plane/tenant-members/requests/notify
          → enqueue a `tenant-members-request` tenant operation (once per request)
              → read the request from the shard, check it, run it, write the outcome back

An invitation made while the control plane is unreachable is accepted, stays pending, and is run when the control plane is back. GET /api/v2/tenant-members/requests lists a tenant's requests with their status (pending, succeeded or failed with a reason); a succeeded invitation carries result.invitation_id. The older synchronous routes keep working for shards that do not set requests.

On the shard, set requests next to getBackend and give the shard the tenantMemberRequests adapter (it ships in the core migrations of @authhero/drizzle, @authhero/kysely-adapter and @authhero/aws-adapter, so apply them before enabling this):

typescript
import {
  createControlPlaneRequestNotifier,
  createControlPlaneTenantMembersAdapter,
} from "authhero";

export default init({
  dataAdapter,
  tenantMembers: {
    getBackend: () => createControlPlaneTenantMembersAdapter({ client }),
    requests: { afterRegister: createControlPlaneRequestNotifier(client) },
  },
});

On the control plane, give initMultiTenant the team backend and hand the notification to it:

typescript
const { app, memberRequests } = initMultiTenant({
  dataAdapter,
  controlPlane: { tenantId: CONTROL_PLANE_TENANT_ID, clientId },
  tenantMemberRequests: {
    getBackend: () =>
      createLocalTenantMembersBackend({
        /* as above, without ctx */
      }),
    // Tenants with their own worker and database are reached over dispatch:
    store: createDispatchTenantMemberRequestStore({
      dispatcher,
      internalSecret,
    }),
  },
  proxyControlPlane: {
    tenantMembers: {
      getBackend,
      requests: {
        onNotify: async (_c, tenantId, requestId) => {
          await memberRequests!.enqueue(tenantId, requestId);
        },
      },
    },
  },
});

A tenant worker cannot run a cron, so a lost notification is found by the control plane: call memberRequests.reconcile({ tenantIds }) from a scheduled handler. It runs pending requests older than five minutes that have no run in flight, retries a run that failed, and after five failed runs reports the request failed.

What the control plane checks. It acts on the tenant of the verified service token, never on a tenant the request names. The shard asserts who asked (requested_by, the admin's sub, verified on the shard); the control plane checks, when it runs the request, that this person still holds a role in the tenant's organization, so a request from someone who has since left the team fails with that reason. Replace the rule with tenantMemberRequests.isRequesterAllowed. The shard remains trusted for its own tenant's team, as before: this adds a check and does not remove one. Running a request twice is safe (an invitation for an address that already has one pending is reused, revoking an invitation that is gone counts as done).

Single-instance deployments ​

When the control plane and the tenants share one database, there is no hop: wire the local backend straight into tenantMembers.getBackend (the same createLocalTenantMembersBackend) and omit proxyControlPlane.tenantMembers. The shard's /api/v2/tenant-members resource then resolves the org against the same database it already holds.

Pass the request context as ctx and invitations are emailed with the built-in user_invitation template, sent as the control-plane tenant: its email provider, branding, default_from_address and locales are used, not the child tenant's. A sendInvitationEmail you pass still takes precedence.

typescript
export default init({
  dataAdapter,
  tenantMembers: {
    getBackend: (ctx) =>
      createLocalTenantMembersBackend({
        data: ctx.env.data,
        controlPlaneTenantId: CONTROL_PLANE_TENANT_ID,
        issuer,
        invitationClientId: env.INVITATION_CLIENT_ID,
        ctx,
      }),
  },
});

Admin UI ​

The per-tenant admin ships a Team page (Settings → Team) that drives this resource: invite colleagues by email, remove administrators, and edit each administrator's roles. The invitation client is resolved server-side, so — unlike the control-plane-only /tenants/:id/members page — it does not depend on a client id being present in local storage. Because members are control-plane users (which a shard can't enumerate), the way to add someone is an email invitation, not a user search; the control-plane page remains the place for global admins to add existing control-plane users directly.

Accepting WFP tenant-subdomain issuers ​

The control-plane resources above verify the caller's service token against the issuer's published JWKS, allowing iss to be either env.ISSUER or the host the request arrived on. A Workers-for-Platforms shard, however, signs with its own key and issuer (https://{tenant}.{host}/), which is neither — so by default such a token is rejected as an issuer mismatch.

Opt those issuers in with proxyControlPlane.isTrustedIssuer, a predicate that widens the accepted issuer set to a deployment's own tenant subdomains:

typescript
export default init({
  proxyControlPlane: {
    // …customDomains / tenantMembers / resolveHost as above.
    isTrustedIssuer: (iss) => isOwnTenantSubdomain(iss), // e.g. *.auth.example.com
  },
});

It is consulted before any JWKS fetch — so it still constrains where verifying keys are fetched from — the signature must still verify against the resolved key, and tenant_id is still pinned. Return true only for issuer hosts you actually serve. The predicate applies to every mounted resource (custom-domains, tenant-members, sync).

Verifying without reaching the shard

Pair isTrustedIssuer with a proxyControlPlane.jwksFetch that resolves each tenant's control-plane-comm public key from a local registry instead of the network, so the control plane never has to fetch keys from — or dispatch to — the shard at verify time. Provisioning the per-tenant credential and registry is deployment wiring; see issue #1139.

Proxy entity sync ​

proxy_routes are tenant-owned data that the control plane needs for host resolution, so they still replicate upward over the outbox. (Custom domains used to travel this way too — that is exactly what left them registered nowhere. They now write through the control plane instead, as described above.)

Wire shape ​

Every successful create/update/delete on a tenant shard enqueues a controlplane.sync.{entity}.{op} outbox event. ControlPlaneSyncDestination POSTs each event to:

http
POST /api/v2/proxy/control-plane/sync
Authorization: Bearer <service token, scope=controlplane:sync>
Idempotency-Key: <event_id>
Content-Type: application/json

{
  "events": [
    {
      "event_id": "...",
      "tenant_id": "acme",
      "entity": "proxy_route",
      "op": "created",                  // or "updated" / "deleted"
      "aggregate_id": "...",
      "payload": { /* full row */ },
      "occurred_at": "2026-06-05T12:34:56.789Z"
    }
  ]
}

The receiver responds 204 No Content on success.

Receiver configuration ​

The control-plane instance opts in to /sync by providing proxyControlPlane.applySyncEvents. createApplySyncEvents wires an idempotent adapter-backed receiver:

typescript
import { init, createApplySyncEvents } from "authhero";
import createAdapters from "@authhero/kysely-adapter";

const proxyAdapters = createAdapters(proxyDb);

export default init({
  dataAdapter: proxyAdapters,
  proxyControlPlane: {
    resolveHost: (host) =>
      proxyAdapters.customDomains.resolveHost?.(host) ?? null,
    jwksUrl: `${env.ISSUER}/.well-known/jwks.json`,
    // jwksFetch: (url) => env.JWKS_SERVICE.fetch(url), // optional, Workers
    applySyncEvents: createApplySyncEvents({
      proxyRoutes: proxyAdapters.proxyRoutes,
    }),
  },
});

The endpoint is cross-tenant. Authhero authenticates the bearer JWT internally: tokens must be signed by a key in jwksUrl, carry an iss matching env.ISSUER, and include the proxy:resolve_host scope. Never issue tenant tokens to the proxy — mint a dedicated M2M client whose grant includes the proxy:resolve_host scope.

Idempotency ​

The outbox retries on network failure, so the receiver MUST be safe to call multiple times. createApplySyncEvents handles the three retry shapes:

  • Duplicate created — falls back to update on the existing row.
  • updated for a row that doesn't exist locally yet — falls back to create (the source-shard id is preserved when the adapter supports it).
  • deleted for a row that's already gone — no-op success.

Adapters that don't preserve the source-shard id will diverge over time; the kysely and drizzle adapters both use input.id when supplied (proxyRouteInsertSchema carries it as optional).

Publishing resolved hosts to Cloudflare KV ​

To take the two-hop HTTP read off the proxy's hot path, the control plane can publish each resolved host blob to a Cloudflare KV namespace that the proxy reads directly. Wrap the customDomains + proxyRoutes adapters once with wrapProxyAdaptersWithKvPublish and pass the wrapped pair to both the dataAdapter (direct management-API writes) and createApplySyncEvents (/sync-replicated writes) — the adapter layer is the single choke-point that sees every write regardless of origin. Recompute-and-publish runs fire-and-forget via ctx.waitUntil, so it never blocks or fails the originating write.

This is the write side of the proxy's KV read replica; the full publish → seed → use guide (including backfillProxyHostsToKv and the proxy-side createKvProxyAdapter) lives in Proxy → Shape 3b.

Tenant shard configuration ​

Each tenant shard opts into replication with the controlPlaneSync block on AuthHeroConfig (requires the outbox to be enabled):

typescript
import { init } from "authhero";

export default init({
  dataAdapter,
  outbox: { enabled: true },
  controlPlaneSync: {
    baseUrl: "https://controlplane.example.com",
  },
});

The same destination is also wired into createDefaultDestinations({ controlPlaneSync }) so cron-drained deliveries don't lose events that missed per-request processing.

Audit-log filtering ​

controlplane.sync.* events are filtered out of LogsDestination and LogStreamDestination by event-type prefix, so replication traffic does not pollute audit logs or downstream log streams.

When to skip it ​

Single-database deployments — where the proxy reads from the same database the management API writes to — leave controlPlaneSync and proxyControlPlane.applySyncEvents unset. No replication is needed.

Best Practices ​

1. Use org_name for Tenant Access ​

Enable allow_organization_name_in_authentication_api on your applications:

typescript
await adapters.clients.update("main", clientId, {
  allow_organization_name_in_authentication_api: true,
});

This ensures tokens contain org_name which directly maps to tenant IDs, avoiding the need to lookup organization IDs.

2. Protect System Entities ​

Always run the protect synced middleware. initMultiTenant does this when sync is enabled. With a manual setup, pass it to init() (not app.use() afterwards, see Protected Entities Middleware):

typescript
import { createProtectSyncedMiddleware } from "@authhero/multi-tenancy";

const { app } = init({
  dataAdapter,
  managementApiMiddleware: [createProtectSyncedMiddleware()],
});

3. Centralize Entity Management ​

Create all shared resource servers and roles on the control plane:

typescript
// ✅ Create on control plane - syncs to all tenants
await createResourceServer("main", config);

// ❌ Don't create individually on each tenant
// await createResourceServer("acme", config);
// await createResourceServer("widgets", config);

4. Separate Admin and End Users ​

  • Control plane users: Tenant administrators, manage via organizations
  • Child tenant users: End customers, authenticate to their specific tenant

5. Use Tenant Headers for Admin Operations ​

For administrative scripts and backend services, use the control plane token with tenant headers rather than switching organizations:

typescript
// ✅ Simple admin script
const adminToken = await getControlPlaneToken();

for (const tenant of tenants) {
  await fetch(`/api/v2/users`, {
    headers: {
      Authorization: `Bearer ${adminToken}`,
      "X-Tenant-ID": tenant.id,
    },
  });
}

Next Steps ​

Within the multi-tenancy package:

How the control plane connects to the proxy, custom domains, and WFP tenants:

Dual-licensed: AGPL-3.0-only or commercial license.