Multi-Tenancy Models Available in Supabase
Supabase runs on PostgreSQL and gives developers three established models for multi-tenancy: separate projects per tenant, separate schemas inside one database, and a single shared schema protected by row level security policies. Each model presents different trade-offs in isolation strength, operational complexity, query performance, and cost.
Separate Supabase projects deliver the strongest isolation because each tenant lives in its own PostgreSQL instance with its own connection string, storage, and compute allocation. This approach eliminates any possibility of accidental cross-tenant queries but multiplies billing and management overhead. Every new tenant requires provisioning another project through the Supabase dashboard or management API, and you must handle cross-project data aggregation manually if needed.
The separate-schema model creates a new PostgreSQL schema for each tenant using CREATE SCHEMA tenant_abc123; and sets the search_path at connection time. Tables with the same name can exist in each schema. This keeps everything inside one Supabase project while maintaining logical separation. The main drawback appears at scale: PostgreSQL performance degrades when the number of schemas exceeds several hundred because the catalog tables grow and permission checks become more expensive.
Most production startups adopt the shared-schema model enforced by row level security. All tenants share the same table definitions, and every row carries a tenant_id UUID column. RLS policies attached to each table ensure users can only read or write rows that belong to their tenant. This model minimizes operational work and keeps costs predictable but demands rigorous policy authoring and continuous testing to prevent data leaks.
Core Schema Design for Shared Multi-Tenancy
Start with three foundational tables: tenants, tenant_members, and data tables that reference tenant_id. The tenants table holds organization-level settings while tenant_members creates the many-to-many relationship between users and tenants, supporting users who belong to multiple organizations.
CREATE TABLE tenants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW(),
settings JSONB DEFAULT '{}'
);
CREATE TABLE tenant_members (
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
role TEXT CHECK (role IN ('owner', 'admin', 'member')),
PRIMARY KEY (tenant_id, user_id)
);
CREATE TABLE projects (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
name TEXT NOT NULL,
status TEXT DEFAULT 'active',
created_at TIMESTAMPTZ DEFAULT NOW()
);
Every table that holds tenant-specific data must include the tenant_id column with a foreign key to the tenants table and an index on (tenant_id, id) or (tenant_id, created_at) depending on access patterns. These composite indexes become critical once RLS policies filter on tenant_id for every query.
Avoid storing sensitive tenant configuration inside JWT claims beyond the minimum required identifiers. Instead, keep rich settings in the tenants table and load them on demand through RLS-protected queries. This keeps JWT tokens small and reduces the attack surface if a token is ever compromised.
Enabling and Writing Effective RLS Policies
RLS must be explicitly enabled on every table that contains tenant data:
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenant_members ENABLE ROW LEVEL SECURITY;
A basic policy that works for many use cases references the auth.uid() function provided by Supabase Auth:
CREATE POLICY "tenant_isolation_projects" ON projects
FOR ALL
USING (
tenant_id IN (
SELECT tenant_id
FROM tenant_members
WHERE user_id = auth.uid()
)
)
WITH CHECK (
tenant_id IN (
SELECT tenant_id
FROM tenant_members
WHERE user_id = auth.uid()
)
);
This policy uses a correlated subquery on every row. While correct, it can cause noticeable latency on tables larger than a few hundred thousand rows because the subquery executes repeatedly. A more performant pattern extracts the tenant list once using a security definer function.
Security Definer Functions for Performance
Create a function that returns the list of tenants a user can access. Mark it SECURITY DEFINER so it runs with elevated privileges and can read the membership table without being subject to its own RLS policies.
CREATE OR REPLACE FUNCTION get_user_tenants()
RETURNS UUID[] AS $$
BEGIN
RETURN ARRAY(
SELECT tenant_id
FROM tenant_members
WHERE user_id = auth.uid()
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public;
Then rewrite the policy to use the function:
CREATE POLICY "tenant_isolation_projects_fast" ON projects
FOR ALL
USING (tenant_id = ANY(get_user_tenants()))
WITH CHECK (tenant_id = ANY(get_user_tenants()));
Because the function is marked SECURITY DEFINER, PostgreSQL can cache its result within a single statement. Add STABLE to the function declaration if the membership rarely changes inside a transaction. In benchmarks published by the PostgreSQL community on similar patterns, this approach reduces query times by 40-70% on tables with millions of rows compared to repeated subqueries.
Always restrict the function so only authenticated users can call it by adding an RLS policy on the function itself or by checking auth.role() = 'authenticated' inside the function body.
Custom JWT Claims for Tenant Context
Supabase allows adding custom claims to the access token through a database trigger on the auth.users table or by using the supabase.auth.setAuth mechanism on the client. For multi-tenancy, the most reliable approach is a trigger that runs after a user signs in and populates an app_metadata field with the user's primary tenant.
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS TRIGGER AS $$
DECLARE
first_tenant UUID;
BEGIN
SELECT tenant_id INTO first_tenant
FROM tenant_members
WHERE user_id = NEW.id
LIMIT 1;
IF first_tenant IS NOT NULL THEN
UPDATE auth.users
SET raw_app_meta_data = raw_app_meta_data ||
jsonb_build_object('tenant_id', first_tenant)
WHERE id = NEW.id;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE PROCEDURE public.handle_new_user();
With the tenant inside the JWT, policies can read it directly without a join:
CREATE POLICY "jwt_tenant_isolation" ON projects
FOR ALL USING (
tenant_id = (auth.jwt() ->> 'tenant_id')::UUID
);
This approach trades flexibility (users with multiple tenants must switch context explicitly) for simplicity and speed. When a user needs to switch tenants, call supabase.auth.setSession() with an updated token containing the new tenant claim after verifying membership server-side.
Next.js App Router Integration Patterns
Use the official @supabase/ssr package (version 0.5.0 or later) to create type-safe server clients that forward cookies correctly. Create a helper in lib/supabase.ts:
import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';
export function createClient() {
const cookieStore = cookies();
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return cookieStore.getAll();
},
setAll(cookiesToSet) {
try {
cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options)
);
} catch {
// Ignore cookie errors in middleware
}
},
},
}
);
}
In server components, always create a fresh client and let RLS enforce tenant boundaries. Never use the service_role key in server components that render user-facing pages.
// app/dashboard/projects/page.tsx
import { createClient } from '@/lib/supabase';
import { redirect } from 'next/navigation';
export default async function ProjectsPage() {
const supabase = createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) redirect('/login');
const { data: projects } = await supabase
.from('projects')
.select('*')
.order('created_at', { ascending: false });
return (
<ul>
{projects?.map(project => (
<li key={project.id}>{project.name}</li>
))}
</ul>
);
}
The RLS policy attached to the projects table guarantees that only the authenticated user's tenant rows are returned. This pattern scales cleanly because the database does the filtering.
Middleware for Tenant-Aware Routing
Next.js middleware can inspect the JWT and redirect users without a tenant or enforce tenant-specific subdomains. Use the @supabase/ssr middleware helper:
import { createMiddlewareClient } from '@supabase/ssr';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
const res = NextResponse.next();
const supabase = createMiddlewareClient({ req: request, res });
const { data: { session } } = await supabase.auth.getSession();
if (!session && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Optional: enforce tenant selection if user has multiple tenants
const tenantId = session?.user?.app_metadata?.tenant_id;
if (!tenantId && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/select-tenant', request.url));
}
return res;
}
export const config = {
matcher: ['/dashboard/:path*', '/api/tenant/:path*']
};
This middleware runs on every request to protected routes and ensures invalid sessions never reach your page components, reducing the chance of leaking data through unhandled error states.
Using Supabase Edge Functions for Tenant Logic
Edge Functions run on Deno and can reuse the same RLS context when you pass the user's access token. Deploy them with the Supabase CLI:
supabase functions new process-invoice
Inside the function, initialize the client with the Authorization header:
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
serve(async (req) => {
const authHeader = req.headers.get('Authorization')!;
const supabase = createClient(
Deno.env.get('SUPABASE_URL')!,
Deno.env.get('SUPABASE_ANON_KEY')!,
{ global: { headers: { Authorization: authHeader } } }
);
const { data } = await supabase
.from('invoices')
.select('*')
.eq('status', 'pending');
// RLS automatically filters to the caller's tenant
return new Response(JSON.stringify({ invoices: data }), {
headers: { 'Content-Type': 'application/json' },
});
});
Edge Functions are ideal for webhooks, background jobs that need tenant isolation, or heavy compute that exceeds Edge runtime limits when done inside Postgres functions. The free tier gives 500ms CPU time per invocation and 2 million invocations per month. Plan to move long-running work to background workers or Supabase's pg_cron for anything exceeding these limits.
Separate Schemas as a Hybrid Strategy
When regulatory requirements demand stronger isolation for specific high-value tenants, combine both approaches. Keep the majority of tenants in the shared RLS schema while creating dedicated schemas for enterprise customers. Use PostgreSQL's CREATE SCHEMA and dynamic search_path inside a connection pooler middleware.
Supabase does not automatically route to different schemas based on JWT claims, so implement a small proxy layer or use different Supabase clients initialized with different options.db.schema values. This hybrid approach adds complexity to your application code but satisfies compliance needs without forcing every tenant into a separate project.
Common Policy Pitfalls and Fixes
One frequent mistake is writing policies that only use USING without a matching WITH CHECK. This allows users to insert rows belonging to other tenants if they guess the UUID. Always pair them or use a single policy that covers both.
Another pitfall is using service_role keys in API routes without manually filtering by tenant_id. The service role bypasses all RLS. Create dedicated server-only functions marked SECURITY DEFINER that enforce tenant checks inside PL/pgSQL before returning data.
Testing policies requires care. The Supabase SQL editor runs as the postgres role and bypasses RLS. Use the Supabase client with a real user's JWT or the supabase.auth.admin API to impersonate users during tests. The command-line tool supabase test combined with seeded test users helps catch policy gaps before production.
Observability and Monitoring in Production
Enable the pg_stat_statements extension to identify slow policies. Query it regularly to find statements where RLS adds the highest overhead. Supabase's built-in query performance dashboard shows average latency per table and highlights queries that scan many rows before the policy filter eliminates them.
Log tenant activity by creating an audit_logs table that uses a trigger on key data tables. The trigger can capture the auth.uid() and tenant_id automatically. Because the audit table itself uses RLS, each tenant can only see their own audit trail unless you provide an admin override policy.
Implement rate limiting per tenant using PostgreSQL advisory locks or by integrating with Redis. Supabase does not provide built-in per-tenant rate limiting, so application-level checks or Edge Function middleware become necessary for public APIs.
Migration Strategies for Existing Single-Tenant Apps
Adding multi-tenancy to an existing Supabase application follows a safe sequence. First add a tenant_id column to every table with a default value that matches the current single tenant. Backfill existing rows. Then add indexes, enable RLS with permissive policies that allow everything for the current tenant, and gradually tighten the policies while testing.
Use Supabase's schema diff feature and the CLI command supabase db diff to generate migration files. Version control all schema changes in the supabase/migrations folder and apply them with supabase migration up in CI/CD pipelines. This prevents drift between local development, staging, and production environments.
After migration, update your TypeScript types by running:
npx supabase gen types typescript --local > supabase/types.ts
The generated types include RLS-aware column visibility and help catch policy-related bugs at compile time when using the Supabase JavaScript client with strict typing.
Cost and Scaling Considerations
RLS itself adds negligible compute cost inside Supabase's managed Postgres. The dominant costs come from compute instance size and storage. A single db.small instance (2 CPU, 4 GB RAM) comfortably supports several thousand active tenants when policies are optimized. Monitor CPU utilization through the Supabase dashboard and scale to db.medium when sustained load exceeds 60%.
Connection pooling becomes important once you have many concurrent users across tenants. Supabase provides a built-in pooler using Supavisor in transaction mode. Configure your Next.js application to use the pooler connection string for server-side queries to avoid exhausting connection limits.
Read replicas are available on paid plans and can offload analytical queries that do not require real-time data. However, RLS policies are evaluated on the replica exactly as on the primary, so no additional configuration is needed.
Full Worked Example: Multi-Tenant Todo Application
Consider a simple todo application. The complete SQL schema consists of the three core tables plus a todos table. Policies are written using the security definer pattern shown earlier. The Next.js frontend uses server actions for mutations to keep writes close to the database.
Server action example:
'use server';
import { createClient } from '@/lib/supabase';
import { revalidatePath } from 'next/cache';
export async function createTodo(formData: FormData) {
const supabase = createClient();
const title = formData.get('title') as string;
const { error } = await supabase
.from('todos')
.insert({ title, completed: false });
if (error) throw error;
revalidatePath('/dashboard');
return { success: true };
}
Because the Supabase client is created with the user's cookies, the JWT travels with the request and RLS enforces that the inserted row receives the correct tenant_id through a trigger or by including it in the insert payload after reading from the JWT. A BEFORE INSERT trigger that sets NEW.tenant_id = (auth.jwt() ->> 'tenant_id')::UUID removes the burden from application code and guarantees consistency.
This example, when fully implemented, results in zero tenant filtering logic in the application layer. All isolation lives in the database where it cannot be bypassed by future developers or API consumers.
The combination of well-designed schemas, optimized security definer functions, custom JWT claims, and tight integration with Next.js SSR creates a maintainable foundation that scales from dozens to thousands of tenants without changing the fundamental architecture. Each decision carries measurable trade-offs in development speed, runtime performance, and operational overhead that teams must weigh against their specific compliance and growth requirements.
