> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Organizations and multi-tenancy

> How GatoJS isolates tenant data: the core data model, getOrgContext(), the mandatory organizationId filter, the runtime tenant-scope guard and MULTI_ORG modes.

An organization is a company or team that users and data belong to. Every organization in a GatoJS app shares **one database and one set of tables**. The only thing that separates one organization's rows from another's is the `organizationId` column.

That makes the filter on `organizationId` the most important line in every query you write. A query without it returns every organization's rows, and a user of one company sees another company's data. GatoJS defends against that in three layers:

> [card] One source of truth
>
> `getOrgContext()` is the only place `organizationId` comes from. It never returns a context without an organization.

> [card] Runtime guard
>
> A Prisma extension rejects any query on org-owned data that has no `organizationId` filter, before it reaches the database.

> [card] Isolation tests
>
> An integration test with two organizations on a real Postgres proves that one never sees the other.

## Key terms

* **Membership**: a row in the `members` table. It says an account belongs to an organization with the role `owner`, `admin` or `member`. One account can be a member of many organizations.
* **Active organization**: the organization the user is working in during a given login session. It's stored on the session row (`Session.activeOrganizationId`), so two sessions of the same account (laptop and phone) can have different active organizations.
* **Organization context** (`OrgContext`): the result of `getOrgContext()`. Who is signed in, which organization they're working in and with which roles.
* **Domain data**: records that belong to one organization and carry an `organizationId` column. In the core that's `Member` and `Invitation`; modules and your own features add their own tables. Accounts (`User`), sessions and organizations themselves are not domain data.

## Core data model

```mermaid theme={null}
erDiagram
    User ||--o{ Session : "userId"
    User ||--o{ Account : "userId"
    User ||--o{ Member : "userId"
    User ||--o{ Invitation : "inviterId"
    Organization ||--o{ Member : "organizationId"
    Organization ||--o{ Invitation : "organizationId"
    Organization |o..o{ Session : "activeOrganizationId (no FK)"

    User {
        String id PK
        String email UK
        String role "user, admin or superadmin"
    }
    Session {
        String id PK
        String token UK
        String userId FK
        String activeOrganizationId "nullable"
    }
    Organization {
        String id PK
        String slug UK
        DateTime createdAt "defines the oldest organization"
    }
    Member {
        String id PK
        String organizationId FK "unique with userId"
        String userId FK
        String role "owner, admin or member"
    }
    Invitation {
        String id PK
        String organizationId FK
        String inviterId FK
        String role
        String status "pending, accepted, canceled, rejected"
    }
```

| Model | File | Notes |
| - | - | - |
| `User`, `Session`, `Account`, `Verification` | `prisma/schema/auth.prisma` | better-auth models. `User.role` is the [global role](https://docs.gatojs.com/concepts/auth-and-roles.md#two-levels-of-roles). Accounts are global: one account can belong to many organizations. |
| `Organization`, `Member`, `Invitation` | `prisma/schema/organizations.prisma` | Models of the better-auth `organization` plugin. `(organizationId, userId)` on `Member` is unique, so an account has at most one membership per organization. |

Deleting an account or an organization cascades (`onDelete: Cascade`) to its sessions, sign-in methods, memberships and invitations. `Session.activeOrganizationId` has no foreign key, so it can point at an organization the account no longer belongs to. `getOrgContext()` catches that case (see below).

Organizations are **one level deep**. There are no sub-organizations or nested teams in the core.

> [!NOTE]
>
> Every domain table a module or feature adds follows `Member` and `Invitation`: a required `organizationId` with an index and a relation to `Organization` (with `onDelete: Cascade`). No test reads the schema for this, so code review is what enforces it. See [Database and migrations](https://docs.gatojs.com/guides/database-and-migrations.md) for where these files live.

## Organization context: `getOrgContext()`

`getOrgContext()` from `src/shared/lib/auth/org-context.ts` is the **only** source of `organizationId` for domain queries. Feature code never reads `activeOrganizationId` from the session on its own.

```ts src/shared/lib/auth/org-context.ts theme={null}
export interface OrgContext {
  userId: string;
  organizationId: string;
  orgRole: OrgRole;
  userRole: UserRole;
  serviceMode: boolean;
}
```

| Field | Source | Meaning |
| - | - | - |
| `userId` | `session.user.id` | The signed-in account. During impersonation, the impersonated account. |
| `organizationId` | `session.session.activeOrganizationId` | The active organization. Always a non-empty string. |
| `orgRole` | `members.role` in the active organization | Role in the organization. Always `owner` for a superadmin without membership. |
| `userRole` | `session.user.role` | Global role. |
| `serviceMode` | computed | `true` only for a superadmin without membership in the active organization. See [Service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md#service-mode). |

### How it resolves

```mermaid theme={null}
flowchart TD
    start["getOrgContext()"] --> read["Read session and user from the database"]
    read --> hasUser{"Signed in?"}
    hasUser -->|"no"| signIn["redirect to /sign-in"]
    hasUser -->|"yes"| hasOrg{"activeOrganizationId set?"}
    hasOrg -->|"no"| noOrg1["throw NoOrganizationError"]
    hasOrg -->|"yes"| member{"Membership in the active org?"}
    member -->|"yes"| memberCtx["Context with orgRole from membership,<br/>serviceMode: false"]
    member -->|"no"| superadmin{"Global role superadmin<br/>and organization exists?"}
    superadmin -->|"yes"| serviceCtx["Context with orgRole: owner,<br/>serviceMode: true"]
    superadmin -->|"no"| noOrg2["throw NoOrganizationError"]
```

`getOrgContext()` never returns a context without an organization. A missing organization ends in an exception, not in an empty filter that would match every organization's rows. The global `admin` role doesn't grant access to an organization you're not a member of; only `superadmin` does, and only in [service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md#service-mode).

Who handles `NoOrganizationError`:

| Where | What happens |
| - | - |
| The `(app)` layout | Redirects to `/no-organization`. |
| `requireModuleAccess(key)` | Redirects to `/no-organization` in the current locale. |
| A command using `handleCommandError` | `NoOrganizationError` isn't a `DomainError`, so it's logged as an error and the command returns its default message. |

### Session read from the database, not the cookie cache

better-auth keeps a signed copy of the session in a cookie for 5 minutes. The active organization, however, is switched server-side by writing to the `sessions` table. If `getOrgContext()` read the cookie copy, a user who just switched organizations would keep querying the previous one for up to 5 minutes. So it reads the session from the database:

```ts src/shared/lib/auth/org-context.ts theme={null}
async function readSession() {
  const requestHeaders = await headers();
  const { auth } = await import("@/shared/lib/auth");
  // WHY: the active org is switched server-side, so the 5-minute cookie cache can hold a stale one.
  return auth.api.getSession({
    headers: requestHeaders,
    query: { disableCookieCache: true },
  });
}
```

Some helpers in `src/shared/lib/auth/helpers.ts` (`getCurrentUser`, `requireUser`, `getAdminUserOrNull`) do read the cookie cache, so their view of the global role can be up to 5 minutes old. For domain data, take `organizationId` only from `getOrgContext()` or `requireModuleAccess()`, which calls it.

### Call it in every entry point

The result isn't memoized per request. Rendering `/users` calls `getOrgContext()` from the layout, from `requireModuleAccess("users")` on the page, and again from the query. That's intentional: the layout doesn't protect a page or a server action, and a query must not trust an `organizationId` handed in by the caller. Call `getOrgContext()` (or `requireModuleAccess()`) in every new query and command, even if the page already did. Never accept `organizationId` as a form field or URL parameter.

> [!TIP]
>
> The [server entry-point architecture test](https://docs.gatojs.com/guides/code-patterns.md#the-architecture-test) fails the build if an exported query or server action touches Prisma before a session guard. It accepts a bare `auth.api.getSession` as a guard, but that gives you neither `organizationId` nor a membership check, so it's not enough for domain data.

## The `organizationId` filter

**Rule:** every Prisma call on domain data includes `organizationId` from the organization context. For reads, updates and deletes it goes in `where`; for creates it goes in `data`.

A record `id` from the input is not enough, because an id sent by the browser can belong to another organization's record. With `where: { id, organizationId }` such a record simply isn't found.

```ts src/features/organizations/services/queries/organization-queries.ts theme={null}
export async function getOrganizationMembersQuery(): Promise<OrganizationMembersData> {
  const { userId, organizationId, orgRole } = await getOrgContext();

  const organization = await prisma.organization.findUniqueOrThrow({
    where: { id: organizationId },
    select: {
      name: true,
      members: {
        orderBy: { createdAt: "asc" },
        select: {
          id: true,
          role: true,
          user: { select: { id: true, name: true, email: true } },
        },
      },
      // …
```

Writes take `organizationId` from the same context:

```ts src/features/users/services/commands/invite-user-command.ts theme={null}
const context = await getOrgContext();
assertServiceModeConfirmed(context, confirmation);
// …
const invitation = await prisma.invitation.create({
  data: {
    organizationId: context.organizationId,
    email,
    role,
    inviterId: admin.id,
    expiresAt: new Date(Date.now() + INVITATION_TTL_MS),
  },
  select: { id: true },
});
```

## Runtime guard

The shared `prisma` client from `src/shared/lib/prisma.ts` is extended with `tenantScopeExtension` (`src/shared/lib/tenant-scope/`). It inspects every query on a guarded model. A query without an organization filter throws `TenantScopeError` (with `model` and `operation` fields) and **never reaches the database**. The behavior is identical in development, tests and production; there is no warn-only mode.

**Guarded models.** Every model with a scalar `organizationId` field, except `Member` and `Invitation`. The list is computed at startup from the generated Prisma client, so a new model with `organizationId` (from a module or your own feature) is guarded automatically. In the kit's modules that's `ApiKey`, `AuditLog` and `Upload`. `Member` and `Invitation` are excluded because better-auth reads them by `id`, `userId` and email, and the core legitimately reads one account's memberships across organizations.

**What counts as a filter:**

* `organizationId` at the top level of `where` with a pinning value: a non-empty string, `{ equals: "<id>" }` or `{ in: ["<id>", …] }` with at least one non-empty string;
* a compound unique selector containing `organizationId`, such as `organizationId_userId: { organizationId, userId }`;
* an element of `AND` that satisfies the above;
* an `OR` where every branch satisfies the above.

**What doesn't count:** `NOT`, relation filters (`organization: { id }`), `{ not }`, `{ notIn }`, `{ in: [] }`, `undefined`, `null` and empty strings.

| Operation | Requirement |
| - | - |
| `findUnique`, `findFirst`, `findMany`, `update`, `updateMany`, `delete`, `deleteMany`, `count`, `aggregate`, `groupBy` (and `…OrThrow` / `…AndReturn` variants) | Filter in `where`. No `where` means no filter. |
| `create` | `data.organizationId` |
| `createMany`, `createManyAndReturn` | `organizationId` in every row |
| `upsert` | Filter in `where` **and** `create.organizationId` |
| `organization: { connect }` | Not enough |
| Any unknown operation | Rejected |

### Deliberate cross-organization reads

When the organization isn't known before the read (for example, looking up an API key by its hash), wrap the query in `withoutTenantScope(reason, fn)`:

```ts src/features/api-keys/services/authenticate-api-key.ts theme={null}
import { withoutTenantScope } from "@/shared/lib/tenant-scope";

const record = await withoutTenantScope("api key lookup by hash", () =>
  prisma.apiKey.findUnique({
    where: { hashedKey },
    // …
  }),
);
```

* `reason` must be a non-empty string; an empty one throws before `fn` runs.
* The bypass lives in `AsyncLocalStorage`, applies only inside `fn` (including nested calls) and ends when `fn` settles, even on error.
* Every unfiltered query inside `fn` writes a `logger.debug` entry with the model, operation and reason.

Use it sparingly and always resolve the organization from the record before trusting it.

> [!WARNING]
>
> **Limits of the guard.** It doesn't see `$queryRaw` / `$executeRaw` or queries through nested relations (`include`, relation `select`, nested writes from a parent model such as `organization.findUnique({ include: { apiKeys: true } })`). It also checks only that *some* filter is present, not that it points at the active organization. A filter built from form input passes the guard, which is why the isolation test below is still mandatory. See [Known limitations](https://docs.gatojs.com/known-limitations.md).

## Organization isolation test

Isolation is proven by an integration test on a real Postgres: `src/features/organizations/services/__tests__/organization-isolation.integration.test.ts`. Prisma, the database and the query, command and guard code are real. Only the framework inputs (`headers()`, `getLocale()`, `redirect`, `notFound`, `auth.api.getSession`) are replaced. The `getSession` stand-in mimics the cookie cache: without `disableCookieCache` it returns an in-memory copy, with it it reads `activeOrganizationId` from the `sessions` table.

Before each test the database is reset and two organizations with members and invitations are created. Use the same pattern for every new query: sign in as a user in one organization, call your code, and assert that nothing from the other organization comes back.

```ts src/features/organizations/services/__tests__/organization-isolation.integration.test.ts theme={null}
it("organization B's member list sees nothing from organization A", async () => {
  await signInAs(world.bob, world.orgB);

  const data = await getOrganizationMembersQuery();

  expect(data.members.map((member) => member.email)).toEqual([
    "bob@b.example",
  ]);
  expect(data.invitations.map((invitation) => invitation.email)).toEqual([
    "new-b@example.com",
  ]);
});
```

For a command, call it in one organization's context and assert that the other organization's records didn't change. Keep expected values as literals, not computed by production code. Integration tests run with `npm run test:integration` against a database whose name ends in `_test`. See [Testing](https://docs.gatojs.com/guides/testing.md).

## Active organization

The active organization is stored on the session, not on the account.

| Event | New active organization |
| - | - |
| Session created (sign-in, impersonation) | The organization of the oldest membership. A superadmin without memberships gets the oldest organization in the database; other accounts without memberships get `null`. |
| Sign-up | Sign-up doesn't create a session (`autoSignIn: false`); the first sign-in sets it. |
| Accepting an invitation while signed in (`/accept-invitation/<id>`) | The invitation's organization, then a redirect to `/dashboard`. |
| Creating an organization (`MULTI_ORG=true`) | The new organization. |
| Choosing one in the organization switcher or on `/no-organization` | The chosen organization, if allowed: a superadmin can enter any existing organization; others only organizations they're members of. |

After signing in again, a user lands in their oldest membership's organization, not the last one they picked.

Switching goes through `enterOrganizationCommand(organizationId)`. It reads the session from the database, checks `canEnterOrganization`, and updates only the **current** session; other sessions of the same account keep their organization. On invalid input, no session, no permission or a write error it returns `{ success: false }` and changes nothing. The switcher then calls `router.refresh()`, and the next `getOrgContext()` returns the new organization.

> [!NOTE]
>
> The kit uses its own command instead of better-auth's `/organization/set-active` endpoint, because that endpoint requires membership and would block a superadmin entering an organization in service mode.

### The `/no-organization` page

`src/app/[locale]/no-organization/page.tsx` lives outside the `(app)` route group (otherwise the `(app)` layout would redirect it to itself forever). It calls `getOrgContext()` itself:

* working context (including service mode): redirect to `/dashboard`;
* no session: redirect to `/sign-in`;
* `NoOrganizationError`: render the "No organization" page.

The page shows a mode-dependent description, an **Enter an organization** list when the account has access to at least one organization, a **Create organization** form when `MULTI_ORG=true`, and a **Sign out** button.

## `MULTI_ORG` modes

`MULTI_ORG` doesn't change the data model. The database always allows many organizations; the flag changes flows and permissions. It defaults to `false`.

| Area | `MULTI_ORG=false` (default) | `MULTI_ORG=true` |
| - | - | - |
| Sign-up without invitation (only with `AUTH_PUBLIC_SIGNUP=true`) | The account joins the **oldest** organization as `member`. If no organization exists, sign-up fails and asks you to run `npm run admin:create`. | A new organization is created with the new account as `owner`. |
| Sign-up with an invitation | Joins the invitation's organization with the invitation's role. | Same. |
| Inviting people | Only global `admin` / `superadmin`, via **Invite user** on the Users page. | Same, plus organization `owner` and `admin` via **Invite someone** on the Members page. |
| Creating organizations | Blocked for every browser call. No UI for it. | Any signed-in user. Creator becomes `owner`. A **+** button and the `/no-organization` form appear. |
| Organization management endpoints (invite, remove member, change role, update/delete organization) | A guard first requires global `admin` or `superadmin`, then better-auth checks membership and org role. | Governed by membership and org role (better-auth `organization` plugin permissions). |
| `/users` for global `admin` / `superadmin` | **Users**: all accounts in the app. | Same. |
| `/users` for org `owner` / `admin` with global role `user` | No access (404). | **Members**: members and pending invitations of the active organization, role changes, removal, invitations. |
| Organization switcher | Shown when the account has access to more than one organization. | Same. |

In both modes the following stay the same: the data model, `getOrgContext()`, the `organizationId` rule and isolation tests, the default active organization on sign-in, the superadmin's ability to enter any organization, and `npm run admin:create`, which creates an organization only on an empty database and otherwise adds the account to the oldest one.

### Changing the mode in a running app

No migration is needed; restart the server after changing the flag.

* **`false` → `true`**: existing organizations and memberships stay. Sign-up without invitation starts creating organizations, anyone can create one, and organization owners and admins get the Members page.
* **`true` → `false`**: all organizations and memberships stay, and accounts with several memberships still see the switcher. Sign-up without invitation joins the oldest organization. Organization owners and admins with global role `user` lose the Members page and access to management endpoints.

For how `MULTI_ORG` combines with `AUTH_PUBLIC_SIGNUP` and the full access matrix, see [Auth and roles](https://docs.gatojs.com/concepts/auth-and-roles.md#access-matrix).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.