DEV Community

Usama Habib
Usama Habib

Posted on • Originally published at osamahabib.com

Multi-Tenant SaaS with Next.js, Prisma & PostgreSQL (Practical Guide)

Multi-tenancy quietly decides whether your SaaS scales cleanly or becomes a security incident. Get it right early - you barely think about it again. Get it wrong — you're rewriting your data layer at the worst time.

👉 Full architecture guide here

The 3 isolation strategies

1. Shared schema + tenant_id column ← recommended default One database, every table has orgId. Simplest to build, works for 100–10,000 tenants comfortably.

2. Schema-per-tenant

Separate PostgreSQL schema per tenant. Good for mid-market with customization needs, but pooling gets complicated.

3. Database-per-tenant

Maximum isolation. Enterprise only - operationally the heaviest.

Start with shared schema. Graduate specific tenants later.

The rule you never break

Every Prisma query must include the tenant filter — no exceptions:

const projects = await prisma.project.findMany({
  where: { orgId: currentOrgId }, // always
  orderBy: { createdAt: "desc" },
});
Enter fullscreen mode Exit fullscreen mode

One forgotten where clause leaks another tenant's data.

Add RLS as a safety net

Row-Level Security makes PostgreSQL itself enforce isolation:

ALTER TABLE "Project" ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON "Project"
  USING (org_id = current_setting('app.current_tenant_id'));
Enter fullscreen mode Exit fullscreen mode

Now even if app code forgets a filter, the database won't hand over wrong tenant's rows.


The production gotcha nobody warns about

PgBouncer in transaction mode resets session variables between transactions - your SET app.current_tenant_id disappears before the query runs.

Fix: use session mode, or set tenant context inside the same prisma.$transaction as your query.


Full guide with Prisma schema, middleware tenant resolver, RLS setup, and FAQ:

👉 osamahabib.com — Multi-Tenant SaaS Guide

Top comments (0)