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
memberstable. It says an account belongs to an organization with the roleowner,adminormember. 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 ofgetOrgContext(). 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
organizationIdcolumn. In the core that’sMemberandInvitation; 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:
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 thesessions 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
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 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
organizationId from the same context:
src/features/users/services/commands/invite-user-command.ts
Runtime guard
The sharedprisma 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:
organizationIdat the top level ofwherewith 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 asorganizationId_userId: { organizationId, userId }; - an element of
ANDthat satisfies the above; - an
ORwhere every branch satisfies the above.
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 inwithoutTenantScope(reason, fn):
src/features/api-keys/services/authenticate-api-key.ts
reasonmust be a non-empty string; an empty one throws beforefnruns.- The bypass lives in
AsyncLocalStorage, applies only insidefn(including nested calls) and ends whenfnsettles, even on error. - Every unfiltered query inside
fnwrites alogger.debugentry with the model, operation and reason.
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
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.
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 roleuserlose the Members page and access to management endpoints.
MULTI_ORG combines with AUTH_PUBLIC_SIGNUP and the full access matrix, see Auth and roles.