X Enterprises
nuxt-x-tenancy

useTenant

Tenant bridge composable for nuxt-x-tenancy — current tenant, tenant list, CRUD cache scope, and switch/resolve actions on top of the better-auth active organization.

useTenant

The tenant bridge composable for nuxt-x-tenancy. Maps the better-auth active organization (from useOrganization(), nuxt-x-auth-better) into the tenant vocabulary and adds the CRUD cache scope and switch/resolve actions. Tenant = { id, name, slug, logo? } — a pure field mapping; tenant id === organization id.

Usage

const {
  tenant,        // current tenant (better-auth active org, mapped)
  tenants,       // all organizations the user belongs to
  isResolving,   // true while switching/resolving or org data loads
  scope,         // tenant id for useXCrud's scope option ('global' when none)
  switchTenant,  // (id: string) => Promise<void>
  resolveBySlug, // (slug: string) => Promise<boolean>
} = useTenant()
<script setup lang="ts">
const { scope } = useTenant()

// Ref scope: this list refetches by itself when the tenant switches,
// into a fresh per-tenant cache entry.
const tasks = useXCrud<Task>('/api/tasks', { scope }).all()
</script>

Returns

KeyTypeDescription
tenantComputedRef<Tenant | null>Current tenant (better-auth active org, mapped).
tenantsComputedRef<Tenant[]>All organizations the user belongs to.
isResolvingComputedRef<boolean>true while switching/resolving or org data loads.
scopeComputedRef<string>Tenant id for useXCrud's scope option ('global' when none).
switchTenant(id)(id: string) => Promise<void>Sets the active org, then useXCrud.clearScope(oldScope).
resolveBySlug(slug)(slug: string) => Promise<boolean>Resolve (from the organizations list) + activate by slug; used by the middleware.

Notes

  • scope is a shared ComputedRef, not a config hook. useXCrud has no global-scope option — pass scope per call. A Ref scope means live .all() instances refetch on switch by themselves; switchTenant() additionally clears the old scope's useState entries. Caveat (upstream useXCrud): read() instances don't watch Ref scopes — refresh them manually after a switch.
  • resolveBySlug resolves against the organizations list, not get-full-organization?organizationSlug= — better-auth's client (≤1.6.5) silently drops those GET params, so slug lookup via that endpoint always returns the active org. See Resolution chain.
  • toTenant(org) (exported from the layer's utils) maps any better-auth-shaped organization to a Tenant.

AI Context

composable: useTenant
package: "@xenterprises/nuxt-x-tenancy"
use-when: >
  Any page that needs the active tenant, a tenant switcher, or a
  tenant-scoped useXCrud cache. Pass scope to useXCrud; call
  switchTenant(id) to change tenants (flushes the old tenant's cache).
Copyright © 2026