> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Multi-tenant SaaS on CockroachDB (Next.js)

> A multi-tenant SaaS backend on CockroachDB: Next.js route handlers, Prisma, and row-level security (RLS) that keeps every tenant's rows away from every other tenant, enforced by the database rather than by WHERE clauses you might forget.

> [!NOTE]
>
> **Blueprint** · **Works on:** Cockroach Continuum, CockroachDB Cloud, self-hosted · **Tested:** weekly in CI against the latest CockroachDB · **Stack:** Next.js 16, Prisma 6, TypeScript · **Code:** [`blueprints/multi-tenant-saas-nextjs`](https://github.com/cockroachlabs/cockroach-cookbook/tree/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs) v1.1.1

A multi-tenant SaaS backend on CockroachDB: Next.js route handlers, Prisma, and
row-level security (RLS) that keeps every tenant's rows away from every other tenant,
enforced by the database rather than by `WHERE` clauses you might forget.

* **Stack:** Next.js 16 (App Router route handlers), Prisma 6 with the `cockroachdb` provider, TypeScript, Vitest
* **Database:** CockroachDB v26.1 or later: a local single node, a CockroachDB Basic or Standard cluster, or a
  multi-region cluster ([Grow it to multi-region](#grow-it-to-multi-region))
* **Time:** about 15 minutes to run locally; the companion course takes about an hour
* **Cost:** nothing locally. A CockroachDB Basic cluster includes a free monthly allowance for pay-as-you-go
  organizations ([Plan a Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/plan-your-cluster-basic.md))

## What it builds

| Table | Scope | Notes |
| - | - | - |
| `tenants`, `users`, `api_keys` | global | looked up before the tenant is known (sign-up, authentication) |
| `memberships`, `projects`, `tasks` | per tenant | `tenant_id` leads every primary key; RLS on all three |

The API:

| Route | Does |
| - | - |
| `POST /api/signup` `{orgName, email}` | creates a tenant, its owner and an API key (shown once) |
| `GET/POST /api/projects` | lists or creates the caller's projects |
| `GET/POST /api/projects/:projectId/tasks` | lists or creates tasks in one of the caller's projects |
| `PATCH /api/tasks/:taskId` `{status}` | moves a task to `todo`, `doing` or `done` |

Every route but sign-up needs `Authorization: Bearer <api key>`.

## How tenant isolation works

1. Each request runs in one transaction that starts with
   `SELECT set_config('application_name', 'tenant:<uuid>', true)`. The `true` makes the
   setting last for that transaction only, so a pooled connection never carries it into the next request
   ([`lib/db.ts`](https://github.com/cockroachlabs/cockroach-cookbook/blob/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs/lib/db.ts)).
2. `current_tenant_id()` reads it back, returning `NULL` for anything that isn't a well-formed tenant setting
   ([`db/security.sql`](https://github.com/cockroachlabs/cockroach-cookbook/blob/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs/db/security.sql)).
3. A policy on each tenant-owned table, `USING (tenant_id = current_tenant_id()) WITH CHECK (...)`, hides
   other tenants' rows on reads and rejects writes for another tenant. No tenant set means no rows.
4. The app connects as `saas_app`, which owns no tables, and every table has `FORCE ROW LEVEL SECURITY`.

Two things RLS doesn't cover, and how this schema handles them
([Row-level security limitations](https://docs.cockroachlabs.com/docs/stable/row-level-security.md#limitations)):

* **Foreign key checks bypass RLS.** Each child table's foreign key includes `tenant_id`
  (`(tenant_id, project_id) REFERENCES projects (tenant_id, id)`), so a row can only point at a parent in its own tenant.
* **Unique constraints bypass RLS.** Each one includes `tenant_id` (`UNIQUE (tenant_id, name)`), so one tenant
  can't learn that another already used a name.

Because `tenant_id` leads the primary key, the policy turns into a scan of that tenant's key span, not a full table scan.

## Get the code

The code is in the [Cockroach Cookbook](https://github.com/cockroachlabs/cockroach-cookbook) repository. To fetch only this project at the version this page describes:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
git clone --filter=blob:none --sparse https://github.com/cockroachlabs/cockroach-cookbook.git
cd cockroach-cookbook
git sparse-checkout set blueprints/multi-tenant-saas-nextjs
git checkout blueprints/multi-tenant-saas-nextjs/v1.1.1
cd blueprints/multi-tenant-saas-nextjs
```

## Run it locally

Needs Node 20+ and the [`cockroach` binary](https://docs.cockroachlabs.com/docs/stable/install-cockroachdb).

```sh theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
npm install
npm run db:local        # starts an insecure single node on :26257 and creates the databases
cp .env.example .env    # the URLs db:local printed
npm run db:migrate      # Prisma migrations, then db/security.sql
npm test                # 12 integration tests against the local node
npm run dev             # http://localhost:3000
```

Try it:

```sh theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
KEY=$(curl -s -X POST localhost:3000/api/signup -H 'content-type: application/json' \
  -d '{"orgName":"Acme","email":"owner@example.com"}' | jq -r .apiKey)
curl -s -X POST localhost:3000/api/projects -H "authorization: Bearer $KEY" \
  -H 'content-type: application/json' -d '{"name":"Roadmap"}'
```

## Run it on CockroachDB Basic

> [!NOTE]
>
> These steps use a CockroachDB Basic cluster, which existing CockroachDB Cloud organizations can create. New organizations are on Cockroach Continuum: create a cluster with the [Continuum quickstart](https://docs.cockroachlabs.com/docs/continuum/tutorial-quickstart.md) and use its connection string in the same steps. Continuum pricing differs from the Basic prices on this page; see [Continuum pricing](https://docs.cockroachlabs.com/docs/continuum/pricing.md).

1. [Create a Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/create-a-basic-cluster.md) and a SQL user,
   then copy its connection string from **Connect** ([Connect to your cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/connect-to-your-cluster.md)).
2. Create the database: `CREATE DATABASE saas;`
3. Set `DIRECT_DATABASE_URL` to your SQL user's connection string for `saas`, and run `npm run db:migrate`.
4. Give the app role a password as that user: `ALTER ROLE saas_app WITH PASSWORD '<a strong password>';`
5. Set `DATABASE_URL` to the same host with `saas_app` and that password, then deploy the app.

This path follows the CockroachDB Cloud docs; the automated tests in the Cookbook repository run against a local single node.

## Two things to know about Prisma on CockroachDB v26.1+

* **Tables are created schema-locked by default** (`create_table_with_schema_locked`), and `ADD CONSTRAINT`,
  which Prisma emits for every foreign key, can't unlock them automatically. The migration starts with
  `SET create_table_with_schema_locked = false;` ([online schema changes](https://docs.cockroachlabs.com/docs/stable/online-schema-changes.md#improve-changefeed-performance-with-schema_locked)).
* **`prisma migrate deploy` can't apply RLS statements** (`ALTER TABLE ... ROW LEVEL SECURITY`, `CREATE POLICY`):
  it fails with "only implemented in the declarative schema changer". [`scripts/apply-security.mjs`](https://github.com/cockroachlabs/cockroach-cookbook/blob/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs/scripts/apply-security.mjs)
  sends them one at a time, which works. `npm run db:migrate` runs both steps.

## Transactions and retries

CockroachDB runs transactions at `SERIALIZABLE` by default. When two transactions conflict, one is aborted with
SQLSTATE `40001` and must be retried ([transaction retry errors](https://docs.cockroachlabs.com/docs/stable/transaction-retry-error-reference.md)).
`transaction()` in [`lib/db.ts`](https://github.com/cockroachlabs/cockroach-cookbook/blob/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs/lib/db.ts) retries the whole transaction with exponential backoff and jitter; Prisma reports the abort as `P2034`.
The test suite runs 20 concurrent read-modify-write transactions on one row and checks that all 20 land.

## Start small, grow without switching

* The same code runs on a laptop node and on a CockroachDB Basic cluster that scales to zero when idle. If the app
  later needs more throughput, more regions or to survive a region failure, the database you started on
  already does that, behind the same PostgreSQL wire protocol, Prisma and driver. The next section shows that path.
* If your app uses a PostgreSQL extension, check [PostgreSQL compatibility](https://docs.cockroachlabs.com/docs/stable/postgresql-compatibility.md) before you start.

## Grow it to multi-region

The same app grows in three stages. Each is a tag in the Cookbook repository, and the companion course walks through them.

| Tag | The cluster | What changes in this project |
| - | - | - |
| `blueprints/multi-tenant-saas-nextjs/stage-1-basic` | CockroachDB Basic, one region | (the app as above) |
| `blueprints/multi-tenant-saas-nextjs/stage-2-standard` | the same cluster on CockroachDB Standard | nothing: the same commit as stage 1 |
| `blueprints/multi-tenant-saas-nextjs/stage-3-multi-region` | three regions, surviving the loss of any one | SQL and scripts only; no app code |

`git diff blueprints/multi-tenant-saas-nextjs/stage-1-basic blueprints/multi-tenant-saas-nextjs/stage-3-multi-region -- .`
shows the whole change.

**Basic to Standard.** A Basic cluster changes plan to Standard in place, from the Cloud Console, the Cloud API or
Terraform; the change takes up to five minutes and the cluster stays up on its current plan meanwhile
([Change a cluster's plan between Basic and Standard](https://docs.cockroachlabs.com/docs/cockroachcloud/change-plan-between-basic-and-standard.md)).
Nothing in the project changes for it. The docs don't say whether the connection string changes, so check
**Connect** afterwards.

**Add regions.** Add the regions to the cluster first (Cloud Console, cluster **Settings**, **Regions**), then, as the owner:

```sh theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
DB_PRIMARY_REGION=<region> DB_REGIONS=<region>,<region> npm run db:multi-region
node scripts/check-placement.mjs --wait   # replicas move in the background; wait before you rely on it
```

[`scripts/apply-multi-region.mjs`](https://github.com/cockroachlabs/cockroach-cookbook/blob/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs/scripts/apply-multi-region.mjs) runs, idempotently:

1. `ALTER DATABASE ... SET PRIMARY REGION`, `ADD REGION` and `SURVIVE REGION FAILURE` (or `ZONE` with `DB_SURVIVE=zone`).
   Surviving a region failure needs at least three regions
   ([survival goals](https://docs.cockroachlabs.com/docs/stable/multiregion-survival-goals.md)).
2. [`db/multi-region.sql`](https://github.com/cockroachlabs/cockroach-cookbook/blob/blueprints/multi-tenant-saas-nextjs/v1.1.1/blueprints/multi-tenant-saas-nextjs/db/multi-region.sql): `tenants`, `users`, `memberships` and `api_keys` become `GLOBAL`
   (read on almost every request, written only at sign-up), and `projects` and `tasks` stay `REGIONAL BY TABLE`
   in the primary region ([table localities](https://docs.cockroachlabs.com/docs/stable/table-localities.md)).
3. A lease preference that keeps the `system` database's leaseholders in the primary region, which the
   [multi-region overview](https://docs.cockroachlabs.com/docs/stable/multiregion-overview.md) recommends. It matters
   here because each query on an RLS table, inside a transaction, reads the system table that records which roles
   may bypass RLS. On the local demo cluster below, that read cost a cross-region round trip (66 ms) per query
   until the leaseholders moved to the app's region (1 ms). Whether a CockroachDB Cloud cluster accepts this zone
   configuration wasn't tested; if it refuses, the script says so and goes on.

**What it costs, measured.** Median of 9 requests through `node scripts/measure-latency.mjs`, with one copy of the app in
each region, on the local 9-node demo cluster (`cockroach demo --global`, which simulates the latency between its three
regions; real clusters differ). Before: the database in us-east1 only. After: stage 3 with `SURVIVE REGION FAILURE`.

| App server in | Sign up | Create project | List projects | Update task |
| - | - | - | - | - |
| us-east1, before → after | 12 → 829 ms | 4 → 70 ms | 3 → 3 ms | 5 → 130 ms |
| us-west1, before → after | 607 → 1,244 ms | 337 → 202 ms | 204 → 71 ms | 337 → 329 ms |
| europe-west1, before → after | 589 → 1,245 ms | 327 → 199 ms | 198 → 70 ms | 327 → 324 ms |

* Reads from the other regions are about three times faster, mostly because authentication now reads a local copy
  of `api_keys`; the tenant's projects and tasks still come from us-east1.
* Every write pays for surviving a region: at least the round trip to the nearest other region. With
  `DB_SURVIVE=zone`, writes in us-east1 stay about as fast as before (8 ms to create a project), but every table's
  voting replicas are then in us-east1, so losing it stops the app.
* Sign-up writes four `GLOBAL` tables, and writes to `GLOBAL` tables are slow by design: about 0.8 s here.
* Cost: on Basic, cross-region writes consume more Request Units and each extra replica adds storage
  ([Plan a Basic cluster](https://docs.cockroachlabs.com/docs/cockroachcloud/plan-your-cluster-basic.md)); on Standard,
  compute is priced at the most expensive region, cross-region transfer is billed at the cloud provider's price, and
  replicas beyond three are billed ([costs](https://docs.cockroachlabs.com/docs/cockroachcloud/costs.md)).
  `SURVIVE REGION FAILURE` keeps five replicas.

**See it locally.**

```sh theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
npm run db:local-multi-region          # 9 nodes in 3 regions, simulated latency (cockroach demo --global)
sh scripts/local-regions.sh            # 9 real nodes in 3 regions, no simulated latency: for failures
sh scripts/local-regions.sh stop-region us-east1   # kill a region's nodes
```

With `SURVIVE REGION FAILURE` and every region passing `check-placement.mjs`, killing all three us-east1 nodes left the
app working through us-west1: the first write took 6 s while leases moved, then reads took about 5 ms and sign-ups
0.8 s. With `DB_SURVIVE=zone`, the same outage stopped writes and reads on `projects`. Test a failure only after
`check-placement.mjs` passes: until then a region can still hold a majority of some range's replicas.

## Checks

| Command | What it proves |
| - | - |
| `npm test` | tenant isolation, cross-tenant writes refused, constraints, retries, the HTTP routes |
| `npm run typecheck` | the TypeScript compiles |
| `npm run db:check` | `schema.prisma` matches the migrations |
| `npm run build` | the production build succeeds |
| `npm test` on a multi-region database | also checks the regions, survival goal, table localities and RLS of stage 3 |
| `node scripts/check-placement.mjs` | every region can be lost without losing a majority of any range |

Verified on CockroachDB v26.1.4 and Node 24, October 2026.

## License

The code is Apache-2.0 licensed.
