13. Multi-Tenant Architecture & Organizations
Building SaaS Apps with Teams & Organizations
Most production SaaS apps need to support organizations, teams, and multi-user accounts where data is isolated per organization. This is the hardest architectural challenge in Supabase — getting it wrong means data leaks between tenants. This module covers the canonical multi-tenant pattern used in production Supabase apps.
Multi-tenant architecture is the foundation of most B2B SaaS applications. The core pattern uses three tables: organizations (tenants), memberships (junction between users and organizations), and roles (permissions within an organization). All data tables include an org_id column for tenant isolation. RLS policies enforce that users can only see data from their organizations. The policies use helper functions like auth.user_org_ids() to check membership. Performance is critical — caching org IDs in JWT claims prevents per-row database queries. Invitations and onboarding are handled with an invitation system. This architecture scales to millions of tenants and users while maintaining strict data isolation.
Core Schema: orgs, memberships, roles
The core schema has three main tables. Organizations represents each tenant. Memberships links users to organizations with a role. All other data tables include an org_id foreign key. This pattern ensures data isolation at the database level. The CHECK constraint on role ensures only valid roles are used. The UNIQUE constraint on (user_id, org_id) prevents duplicate memberships. ON DELETE CASCADE ensures data is cleaned up when organizations or users are deleted. This schema is the foundation of any multi-tenant SaaS application. It's flexible enough to handle various permission models — owners, admins, members, and viewers. The role column can be extended to support more granular permissions.
-- Organizations (tenants) CREATE TABLE organizations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name TEXT NOT NULL, slug TEXT UNIQUE NOT NULL, plan TEXT DEFAULT 'free', created_at TIMESTAMPTZ DEFAULT NOW() ); -- Membership junction table (user organization with role) CREATE TABLE memberships ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE, org_id UUID REFERENCES organizations(id) ON DELETE CASCADE, role TEXT DEFAULT 'member', created_at TIMESTAMPTZ DEFAULT NOW(), UNIQUE(user_id, org_id) );
RLS Policies for Multi-Tenancy
RLS is the enforcement mechanism for multi-tenant isolation. The auth.user_org_ids() helper returns all org IDs the user belongs to. This is used in the members_see_org_projects policy — users can see projects where the org_id is in their list of orgs. For insert and delete operations, you can check the user's role in the organization. The auth.user_org_role() helper returns the user's role for a specific org. This enables admins-only operations. For performance, cache org memberships in the JWT using the custom_access_token_hook. This avoids per-row database queries for membership checks. The policies are simple but powerful — they enforce strict data isolation while enabling collaboration within organizations.
-- Helper: get all org IDs the current user belongs to CREATE OR REPLACE FUNCTION auth.user_org_ids() RETURNS UUID[] AS $$ SELECT ARRAY( SELECT org_id FROM memberships WHERE user_id = auth.uid() ); $$ LANGUAGE sql STABLE SECURITY DEFINER; -- RLS on projects: users see only their orgs' projects CREATE POLICY "members_see_org_projects" ON projects FOR SELECT USING (org_id = ANY(auth.user_org_ids()));
auth.user_org_ids() on every row can be slow on large membership tables. Add the user's org IDs as a custom JWT claim using the token hook so the policy reads from memory instead of querying the database.Invitations & Onboarding
Invitations are how users join organizations. The invitation system stores an email, role, and unique token. The token is generated from random bytes and has a 7-day expiration. When a user accepts an invitation, the function validates the token, creates a membership, and marks the invitation as accepted. The SECURITY DEFINER attribute ensures the function can insert into memberships regardless of RLS. This pattern works for both existing users (who are already authenticated) and new users (who sign up first). After accepting the invitation, the user can access the organization's data. This is the standard onboarding flow for multi-tenant SaaS applications. It's secure, scalable, and user-friendly.
-- Invitation system CREATE TABLE invitations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), org_id UUID REFERENCES organizations(id) ON DELETE CASCADE, email TEXT NOT NULL, role TEXT DEFAULT 'member', token TEXT UNIQUE DEFAULT encode(gen_random_bytes(32), 'hex'), expires_at TIMESTAMPTZ DEFAULT NOW() + INTERVAL '7 days', accepted_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW() );
Knowledge Check
Ready to test your understanding of 13. Multi-Tenant Architecture & Organizations?