Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 31 ยท Data Modeling and Patterns

Multi-Tenant and Team Apps

Build team apps where each organization's data is isolated: memberships, roles per org, invitations, billing seats, Firestore rules and Postgres RLS.

Many apps are not about one user, they are about a team: a company in a project tracker, a school in a gradebook, a shop in an ecommerce dashboard. Such a product is multi-tenant: one deployment serves many customers (tenants, usually called organizations), and each customer must see only its own data.

The big danger is a leak: one customer reading another's data. On a BaaS the browser talks to the database directly, so the isolation must be enforced by security rules (Firebase) or Row Level Security (Supabase), not by your UI. In this lesson you will model organizations, memberships and roles, see the read-only rules and policies for both platforms, and run a stand-in isolation check in JavaScript. If rules are new to you, read Firestore Security Rules and Row Level Security Policies first.

The tenant model

Organization The customer. Owns all the data.
Membership Links a user to an org with a role.
Org data Every row or document carries an org id.

Rules check membership, never the client.

1 / 2

Memberships, not a single org id on the user

It is tempting to store orgId on the user. That breaks as soon as a person belongs to two teams (a freelancer, a consultant, an admin). Use a membership that connects user, organization and role.

SQL
-- Supabase (read-only)
create table organizations (
  id   uuid primary key default gen_random_uuid(),
  name text not null
);

create table memberships (
  org_id  uuid not null references organizations(id) on delete cascade,
  user_id uuid not null references auth.users(id) on delete cascade,
  role    text not null check (role in ('owner', 'admin', 'member', 'viewer')),
  primary key (org_id, user_id)
);

create table projects (
  id     uuid primary key default gen_random_uuid(),
  org_id uuid not null references organizations(id) on delete cascade,
  name   text not null
);

In Firestore the same idea is a subcollection or a map on the organization document:

JavaScript
// Firebase (read-only)
// orgs/{orgId}                       { name: "Acme" }
// orgs/{orgId}/members/{userId}      { role: "admin" }
// orgs/{orgId}/projects/{projectId}  { name: "Website" }

Putting projects under the organization document makes the path itself carry the tenant. That is convenient for rules, because orgId is in the URL path.

Isolation in Firestore rules

A rule can look up the caller's membership with get() and exists():

Text
// firestore.rules (read-only)
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function isMember(orgId) {
      return request.auth != null
        && exists(/databases/$(database)/documents/orgs/$(orgId)/members/$(request.auth.uid));
    }

    function roleIn(orgId) {
      return get(/databases/$(database)/documents/orgs/$(orgId)/members/$(request.auth.uid)).data.role;
    }

    match /orgs/{orgId}/projects/{projectId} {
      allow read: if isMember(orgId);
      allow create, update: if roleIn(orgId) in ['owner', 'admin', 'member'];
      allow delete: if roleIn(orgId) in ['owner', 'admin'];
    }

    match /orgs/{orgId}/members/{userId} {
      allow read: if isMember(orgId);
      allow write: if roleIn(orgId) in ['owner', 'admin'];
    }
  }
}

Each get() or exists() counts as a document read in billing and has a limit per request, so keep rules lean. An alternative is to place the user's orgs and roles in custom claims on their ID token (see Users, Roles and Custom Claims), which costs no reads but only changes when the token refreshes.

Remember the most important Firestore fact: rules are not filters. A query for orgs/{orgId}/projects fails entirely if the rule cannot prove every possible result is readable. Query inside the org path, never across all orgs.

Isolation in Postgres with RLS

In Supabase every tenant table gets an org_id column and policies that ask "is this user a member of that org?". Put the check in a helper function so every policy stays short:

SQL
-- Supabase (read-only)
alter table projects enable row level security;

create function is_member(target_org uuid) returns boolean
language sql stable security definer set search_path = public as $$
  select exists (
    select 1 from memberships
    where org_id = target_org and user_id = auth.uid()
  );
$$;

create function org_role(target_org uuid) returns text
language sql stable security definer set search_path = public as $$
  select role from memberships
  where org_id = target_org and user_id = auth.uid();
$$;

create policy "members read projects" on projects
  for select to authenticated
  using ( is_member(org_id) );

create policy "editors insert projects" on projects
  for insert to authenticated
  with check ( org_role(org_id) in ('owner', 'admin', 'member') );

create policy "admins delete projects" on projects
  for delete to authenticated
  using ( org_role(org_id) in ('owner', 'admin') );

The helper uses security definer so it can read memberships even though that table has its own policies. That also makes it powerful: set search_path as shown, and never expose a helper that takes arbitrary user IDs. An update policy needs both using (which existing rows) and with check (what the row may become), so a member cannot move a project into another organization by editing org_id.

A stand-in isolation check

Real rules cannot run here, so the stand-in below implements the same logic in JavaScript: memberships, a policy function and a leak test that tries every user against every organization. The test is the valuable idea. Write one for your real rules using the Firebase emulator or pgTAP-style SQL tests.

JS Stand-in tenant isolation check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Ben shows why roles must be per organization: he is a member in Acme and only a viewer in Globex. The leak test passes, but the point is that you can check it automatically. Change can.read to always return true and run it again to watch the leaks appear.

Invitations

New members usually arrive by invitation. A safe flow:

  1. An admin creates an invitation record: { orgId, email, role, token, expiresAt }. The token is long and random.
  2. A Cloud Function or Edge Function emails the link. Email sending needs a secret key, so it never runs in the browser.
  3. The invitee signs in (or signs up) and calls a server-side function with the token. The function checks that the token exists, has not expired, has not been used and matches the signed-in user's verified email, then creates the membership and marks the invitation used.

The key point is that the browser never writes a membership itself. If your rules allowed create on members for anyone, a user could add themselves to any organization. Only admins, or trusted server code, may create memberships.

Roles and ownership

Keep the role list short (owner, admin, member, viewer) and enforce one rule everywhere: there is always at least one owner. Changing the last owner's role or removing them should fail. Do this in a function or with a database constraint or trigger, because a client-side check is just a suggestion.

Billing seats

If you charge per seat, a membership count drives the bill. Two cautions:

  • Count active memberships plus pending invitations according to your own policy, and decide it once.
  • Enforce the seat limit on the server (in the invitation function), not in the UI. Webhooks from your payment provider update the plan and limit; see Project: SaaS Starter with Teams.

Common mistakes

  • Putting org_id on rows but forgetting to turn on RLS, which exposes every row.
  • A policy that checks "any membership exists" instead of membership in that row's org.
  • Letting an update change org_id (missing with check).
  • Using the service role key in the browser, which bypasses all policies.
  • Letting users write their own role into a profile document that rules trust.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a memberships table instead of one orgId on the user?

    Membership rows link user, organization and role, so roles are per org and people can join several teams.
  2. 2. What does a missing with check on an update policy allow?

    using filters which existing rows may be updated. with check validates the new values, such as an unchanged org_id.
  3. 3. Who should create a membership when someone accepts an invitation?

    If browsers could write memberships, anyone could join any organization. A function validates the invitation first.
  4. 4. A Firestore query for all projects across every organization fails. Why?

    Firestore checks the query against the rule before running it. Query within one org path instead.

Summary

  • Multi-tenant apps share one deployment; isolation is enforced by rules or RLS, not by the UI.
  • Model organizations, memberships with roles, and tenant data that carries an org id (or lives under the org path).
  • Firestore rules use get() and exists() on member documents, or custom claims; Postgres uses RLS policies with helper functions.
  • Write an automatic leak test that tries every user against every organization.
  • Create memberships and enforce seat limits on the server through an invitation flow.

Next: Search, Aggregations and Analytics