Skip to main content
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:

One source of truth

getOrgContext() is the only place organizationId comes from. It never returns a context without an organization.

Runtime guard

A Prisma extension rejects any query on org-owned data that has no organizationId filter, before it reaches the database.

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

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.
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 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.
src/shared/lib/auth/org-context.ts

How it resolves

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. Who handles NoOrganizationError: 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:
src/shared/lib/auth/org-context.ts
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.
The server entry-point 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.
src/features/organizations/services/queries/organization-queries.ts
Writes take organizationId from the same context:
src/features/users/services/commands/invite-user-command.ts

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.

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):
src/features/api-keys/services/authenticate-api-key.ts
  • 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.
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.

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.
src/features/organizations/services/__tests__/organization-isolation.integration.test.ts
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.

Active organization

The active organization is stored on the session, not on the account. 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.
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. 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.