TL;DR: Serve every tenant from one Next.js deployment and one shared PostgreSQL database. A
proxy.tsfile (calledmiddleware.tsin Next.js 15 and earlier) reads the request host and rewrites it to an internal[tenant]route. Server code then resolves the host against a domains table, checks that the signed-in user belongs to that tenant, and runs every query through a database role that is subject to PostgreSQL Row-Level Security (RLS). Cache keys, cache tags, and cookies are scoped per tenant so nothing leaks between customers.
Key Takeaways
- In Next.js 16 the
middlewarefile convention is deprecated and renamed toproxy. Createproxy.tsand export a function namedproxy. Proxy runs on the Node.js runtime and the runtime cannot be configured; if you need the Edge runtime, keepmiddleware.ts. - The
Hostheader only tells you which tenant the request is for. It never proves who the user is. Resolve the host against your own domains table, return 404 for unknown hosts, and authorize the user's membership in that tenant on every request and in every Server Action. - RLS policies must be permissive (the default). A table with only
AS RESTRICTIVEpolicies returns no rows at all. - Superusers and roles with
BYPASSRLSalways bypass RLS, even withFORCE ROW LEVEL SECURITY. Your application must connect as an ordinary role. - Set the tenant with
set_config('app.current_tenant', id, true)inside the same transaction as the query, so it is cleared on commit and safe behind a transaction-mode connection pooler. - In Next.js 15 and later,
params,cookies()andheaders()are asynchronous; Next.js 16 removed the synchronous compatibility path entirely. Alwaysawaitthem. - Include the tenant ID in every cache key and cache tag, and issue session cookies without a
Domainattribute sotenant-a.example.comcannot read or overwrite cookies fortenant-b.example.com.
You are building a B2B SaaS. The first customers are onboarded and the product works. Then enterprise requests arrive: workspaces at company.yoursaas.com, and in some cases fully custom domains such as app.theircompany.com.
At that point, two problems appear together. Routing turns into conditional logic scattered across layouts. And data isolation depends entirely on every developer remembering WHERE tenant_id = ? in every query. One missed filter in one endpoint is enough to show Customer A the invoices of Customer B.
The common alternative, a separate database or schema per tenant, solves isolation but multiplies migrations, connection pools, and operational work with every new customer. For most B2B products in their first few years, a shared database with engine-level isolation is the better trade.
This guide builds that architecture on the Next.js App Router (tested against Next.js 16.1), PostgreSQL 18 (RLS behaves the same on all supported versions), and Prisma ORM 7. It covers DNS, host-based routing with proxy.ts, tenant resolution and authorization, RLS policies and database roles, tenant-scoped data access, custom domain provisioning, caching, cookies, testing, and the trade-offs you should know before committing to the design. If you are designing the API layer that sits beside this app, read the companion post on secure multi-tenant API isolation, authorization, and audit.
Terminology and the Request Flow
A few terms used throughout:
| Term | Meaning in this guide |
|---|---|
| Tenant | One customer organization. Owns users, data, settings, and optionally a custom domain. |
| Tenant host | The hostname a request arrived on, such as acme.saascraft.com or app.acme.com. |
| Pool model | All tenants share the same database and tables, separated by a tenant_id column. |
| Silo model | Each tenant gets its own database (or schema). Strong isolation, high operational cost. |
| RLS | PostgreSQL Row-Level Security: per-row filters the database enforces on every query. |
| Proxy | The Next.js 16 name for the request interceptor formerly called Middleware (proxy.ts). |
| Tenant resolution | Turning a tenant host into a tenant record, using a lookup table you control. |
| Tenant authorization | Checking that the signed-in user is a member of the resolved tenant, with the right permissions. |
The request flow, step by step:
- DNS sends
acme.saascraft.com(or a verified custom domain) to your deployment. proxy.tsnormalizes the host and rewrites/dashboardto the internal path/app/acme.saascraft.com/dashboard. The browser URL does not change.- The
app/(saas)/app/[tenant]/layout.tsxserver component looks up the host in thetenant_domainstable. Unknown host: 404. - The layout loads the session (from a host-only cookie) and checks that the user is a member of that tenant. Not a member: redirect to sign-in or 403.
- Pages and Server Actions get a tenant-scoped database client. Every query runs in a transaction that first sets
app.current_tenant, and PostgreSQL RLS filters rows to that tenant.
Steps 3 and 4 are what keep the architecture safe. Proxy is a routing convenience, not a security boundary.
Foundation: Wildcard DNS and Local Testing
Before writing any Next.js code, arbitrary subdomains must reach your application. If your base domain is saascraft.com, then *.saascraft.com must resolve to your host.
On a self-managed server or most DNS providers, that means a wildcard record:
; Generic wildcard setup for a self-hosted deployment
; Type Name Target TTL
A @ 203.0.113.10 300 ; apex -> your load balancer
CNAME * lb.saascraft-infra.net. 300 ; every subdomain -> same target
On Vercel, wildcard domains have an extra requirement: Vercel must be able to answer DNS challenges to issue and renew the wildcard TLS certificate. Its docs ask you to either move the apex domain to Vercel's nameservers (ns1.vercel-dns.com, ns2.vercel-dns.com) and add *.saascraft.com to the project, or keep your DNS provider and delegate _acme-challenge to Vercel. Vercel then issues one wildcard certificate for *.saascraft.com. A wildcard certificate covers only one level, so docs.acme.saascraft.com would need its own *.acme.saascraft.com entry.
Production note: A wildcard certificate covers your own subdomains only. Custom domains such as
app.clientdomain.comeach get their own certificate, issued after the domain is added to your project and its DNS points at your platform. The provisioning section below covers this.
To test locally, you do not need to edit your hosts file. Most modern browsers resolve *.localhost to the loopback address, and with curl you can always force a Host header:
# Next.js 16 dev server on port 3000
npm run dev
# Simulate a tenant subdomain
curl -i -H "Host: acme.localhost:3000" http://localhost:3000/dashboard
# Simulate a custom domain mapped to a tenant in your local database
curl -i -H "Host: app.acme-corp.test" http://localhost:3000/dashboard
# An unknown host should return 404, not a default tenant
curl -i -H "Host: does-not-exist.localhost:3000" http://localhost:3000/
Keep the last command in your test suite. A platform that silently falls back to a default tenant for unknown hosts is a platform that will eventually serve the wrong data.
Routing Tenant Hosts with proxy.ts in Next.js 16
The App Router maps folders to URLs. To serve many tenants without a folder per tenant, intercept each request, read the host, and rewrite it to a dynamic segment.
In Next.js 16 this file is proxy.ts at the project root (or inside src/, next to app). The file exports one function, either as a default export or named proxy. On Next.js 15 and earlier, use the same code in middleware.ts and name the function middleware; Next.js ships a codemod (npx @next/codemod@canary middleware-to-proxy .) that does the rename.
// proxy.ts (Next.js 16+). On Next.js 15 and earlier: middleware.ts, export function middleware
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const ROOT_DOMAIN = process.env.ROOT_DOMAIN ?? 'saascraft.com'; // e.g. "saascraft.com"
const DEV_ROOT_DOMAIN = 'localhost';
const RESERVED_SUBDOMAINS = new Set(['www', 'app', 'api', 'admin', 'mail']);
// One DNS label for subdomains, or a full hostname for custom domains.
const HOSTNAME_PATTERN =
/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/;
export const config = {
matcher: [
// Skip API routes, Next.js internals, and files with an extension (public assets).
'/((?!api/|_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|.*\\..*).*)',
],
};
function normalizeHost(rawHost: string | null): string | null {
if (!rawHost) return null;
const host = rawHost.trim().toLowerCase().replace(/:\d+$/, ''); // strip port
return HOSTNAME_PATTERN.test(host) ? host : null;
}
export function proxy(request: NextRequest) {
const host = normalizeHost(request.headers.get('host'));
if (!host) {
return new NextResponse('Bad Request', { status: 400 });
}
const { pathname, search } = request.nextUrl;
const isRootHost =
host === ROOT_DOMAIN || host === `www.${ROOT_DOMAIN}` || host === DEV_ROOT_DOMAIN;
if (isRootHost) {
return NextResponse.rewrite(new URL(`/home${pathname}${search}`, request.url));
}
const subdomain = host.endsWith(`.${ROOT_DOMAIN}`)
? host.slice(0, -(ROOT_DOMAIN.length + 1))
: host.endsWith(`.${DEV_ROOT_DOMAIN}`)
? host.slice(0, -(DEV_ROOT_DOMAIN.length + 1))
: null;
if (subdomain !== null && (subdomain.includes('.') || RESERVED_SUBDOMAINS.has(subdomain))) {
return new NextResponse('Not Found', { status: 404 });
}
// Pass the full host. The [tenant] layout resolves it against the database,
// so subdomains and custom domains share one lookup path.
return NextResponse.rewrite(
new URL(`/app/${encodeURIComponent(host)}${pathname}${search}`, request.url),
);
}
Decisions worth calling out:
- The host is validated, not trusted. It is lowercased, the port is stripped, and anything that is not a syntactically valid hostname gets a 400. That keeps arbitrary strings out of your route params and database lookups.
- Proxy does not decide which tenant exists. It only forwards the host. The database lookup happens in the tenant layout, which runs in your normal server runtime with your normal data access code. This also means custom domains need no special handling in proxy.
- Reserved subdomains are blocked so nobody can register
adminorapias a tenant slug and impersonate your own surfaces. Enforce the same list when tenants pick slugs. - Query strings are preserved by appending
searchto the rewrite target. - The rewrite keeps the browser URL unchanged. Users see
acme.saascraft.com/dashboard, while Next.js rendersapp/(saas)/app/[tenant]/dashboard/page.tsx.
The matcher excludes /api/. Route Handlers under app/api therefore receive no tenant rewrite and must resolve the tenant themselves (by reading (await headers()).get('host') and calling the same resolver shown below). Proxy also is not a reliable place for authorization: the Next.js docs point out that Server Functions are handled as POST requests to the route they are used on, so a matcher change can silently remove proxy coverage. Check authorization inside each Server Action and Route Handler.
Self-hosting note: Behind your own load balancer, only accept requests whose
Hostis your root domain, a subdomain of it, or a custom domain you have provisioned, and do not let clients setX-Forwarded-Hostunless your proxy overwrites it. On managed platforms such as Vercel, a request only reaches your project if its host is a domain attached to that project.
This split between a marketing zone and a tenant application zone in one codebase is a pattern we use in our full-stack web development services, because it avoids maintaining two repositories that share design tokens, auth, and billing code.
Structuring the App Router for Multi-Tenancy
Because proxy rewrites URLs, the app directory must match the rewritten paths. Route groups (folders in parentheses) do not affect URLs, so they are a clean way to give the marketing site and the tenant app their own root layouts:
app/
├── (public)/ # Marketing site, root layout with marketing chrome
│ ├── layout.tsx
│ └── home/
│ ├── page.tsx # saascraft.com
│ └── pricing/page.tsx # saascraft.com/pricing
│
└── (saas)/ # Multi-tenant app, root layout with app chrome
├── layout.tsx
└── app/
└── [tenant]/
├── layout.tsx # Resolves tenant, authorizes user
├── page.tsx # acme.saascraft.com
├── invoices/
│ └── page.tsx # acme.saascraft.com/invoices
└── settings/
└── page.tsx # acme.saascraft.com/settings
A request to saascraft.com/app/other-tenant is rewritten to /home/app/other-tenant, which does not exist, so the internal tenant paths cannot be reached directly from the root domain. A request to acme.saascraft.com/app/x becomes /app/acme.saascraft.com/app/x, still scoped to the Acme host.
Tenant resolution lives in one small module. It uses React's cache() so the layout and the page share one lookup per request:
// lib/tenant.ts
import 'server-only';
import { cache } from 'react';
import { notFound, redirect } from 'next/navigation';
import { prisma } from '@/lib/db/prisma';
import { getSession } from '@/lib/auth'; // your session helper; reads a host-only cookie
export const resolveTenantByHost = cache(async (host: string) => {
// tenant_domains is a lookup table without RLS, readable by the app role.
const mapping = await prisma.tenantDomain.findUnique({
where: { domain: host.toLowerCase() },
select: { status: true, tenant: { select: { id: true, name: true, slug: true } } },
});
if (!mapping || mapping.status !== 'active') return null;
return mapping.tenant;
});
export async function requireTenantMember(host: string) {
const tenant = await resolveTenantByHost(host);
if (!tenant) notFound();
const session = await getSession();
if (!session) redirect('/login');
const membership = await prisma.membership.findUnique({
where: { tenantId_userId: { tenantId: tenant.id, userId: session.userId } },
select: { role: true },
});
if (!membership) notFound(); // do not reveal that the tenant exists
return { tenant, userId: session.userId, role: membership.role };
}
The layout and page then use it. Note that params is a Promise in Next.js 15 and 16 and must be awaited:
// app/(saas)/app/[tenant]/page.tsx (Next.js 15+: params is async)
import { requireTenantMember } from '@/lib/tenant';
export default async function TenantDashboard({
params,
}: {
params: Promise<{ tenant: string }>;
}) {
const { tenant: encodedHost } = await params;
const { tenant } = await requireTenantMember(decodeURIComponent(encodedHost));
return (
<main className="p-8">
<h1 className="text-2xl font-bold">Welcome to {tenant.name}</h1>
</main>
);
}
If you prefer generated types, npx next typegen (Next.js 15.5+) creates a global PageProps<'/app/[tenant]'> helper. Either way, never read params.tenant synchronously; in Next.js 16 that access path no longer exists. The same applies to cookies() and headers() from next/headers: const store = await cookies(). For a broader look at the async API changes, see the Next.js 16 migration guide.
Data Isolation with PostgreSQL Row-Level Security
Routing is half the job. The other half is making sure a query in Acme's context can only touch Acme's rows.
In the pool model all tenants share tables, separated by a tenant_id column:
CREATE TABLE tenants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
slug TEXT NOT NULL UNIQUE
);
CREATE TABLE invoices (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id),
amount NUMERIC(12, 2) NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Every RLS predicate filters on tenant_id, so index it (usually as a leading column).
CREATE INDEX invoices_tenant_created_idx ON invoices (tenant_id, created_at DESC);
Relying only on the ORM to add where: { tenantId } works until someone forgets it. RLS moves the filter into PostgreSQL itself:
-- 1. Turn RLS on. With no policies, PostgreSQL denies all rows by default.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
-- 2. Apply RLS to the table owner as well (owners bypass RLS otherwise).
-- Note: superusers and BYPASSRLS roles still bypass RLS. Do not connect as them.
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
-- 3. A PERMISSIVE policy (the default) that covers SELECT, INSERT, UPDATE, DELETE.
-- Do not mark it AS RESTRICTIVE: with only restrictive policies, no rows are accessible.
CREATE POLICY tenant_isolation ON invoices
FOR ALL
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid);
-- 4. The application connects as an ordinary role: not a superuser, not BYPASSRLS,
-- and not the table owner. Credentials come from your secret store.
CREATE ROLE app_runtime LOGIN NOSUPERUSER NOBYPASSRLS;
GRANT SELECT, INSERT, UPDATE, DELETE ON invoices TO app_runtime;
GRANT SELECT ON tenants, memberships TO app_runtime;
GRANT SELECT, INSERT, UPDATE ON tenant_domains TO app_runtime;
Two details matter:
current_setting('app.current_tenant', true)returnsNULLinstead of raising an error when the setting does not exist. After a transaction-local setting has been used once on a connection, the variable can read back as an empty string, which is whyNULLIF(..., '')is there. In both cases the comparison is not true and no rows match. A query without a tenant context returns zero rows instead of all rows.- The
WITH CHECKclause stops inserts and updates that would write a row into another tenant, even if application code passes the wrongtenant_id.
CREATE POLICY documentation states it directly: "If only restrictive policies exist, then no records will be accessible." Restrictive policies are useful for narrowing access further (for example, an additional deleted_at IS NULL rule), but they must sit on top of at least one permissive policy.
Tenant-Scoped Data Access with Prisma ORM 7
Connection poolers such as PgBouncer (in transaction mode), Supabase Supavisor, or Prisma's own pool hand the same physical connection to different requests. A session-level SET app.current_tenant = ... would survive on that connection and leak into the next request. The fix is a transaction-local setting: set_config(name, value, true) (equivalent to SET LOCAL) lasts only until the current transaction commits or rolls back.
So every tenant query must run in a transaction whose first statement sets the tenant. Prisma's official RLS client extension example does this with a batch transaction. The version below follows that example, updated for Prisma ORM 7, where the client is generated into your project and requires a driver adapter:
// lib/db/prisma.ts (Prisma ORM 7 with @prisma/adapter-pg)
import 'server-only';
import { PrismaPg } from '@prisma/adapter-pg';
import { Prisma, PrismaClient } from '@/generated/prisma/client';
const connectionString = process.env.DATABASE_URL;
if (!connectionString) throw new Error('DATABASE_URL is not set');
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma =
globalForPrisma.prisma ?? new PrismaClient({ adapter: new PrismaPg({ connectionString }) });
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
function forTenant(tenantId: string) {
return Prisma.defineExtension((client) =>
client.$extends({
query: {
$allModels: {
async $allOperations({ args, query }) {
// Batch transaction: both statements run on the same connection, in order,
// and the setting is discarded when the transaction ends.
const [, result] = await client.$transaction([
client.$executeRaw`SELECT set_config('app.current_tenant', ${tenantId}, true)`,
query(args),
]);
return result;
},
},
},
}),
);
}
export function getTenantDb(tenantId: string) {
return prisma.$extends(forTenant(tenantId));
}
Why a batch transaction and not an interactive prisma.$transaction(async (tx) => ...) callback? Inside an interactive transaction callback, the query(args) function handed to a query extension is not guaranteed to run on tx, so the model query can end up on a different connection that never saw set_config. With RLS in place that fails closed (zero rows), but it is still a bug. The batch form guarantees ordering on one connection.
Prisma's README for this example lists two caveats worth repeating: each operation is wrapped in its own batch transaction, so explicit $transaction() calls on the extended client may not behave as intended, and the example is described as a reference rather than production-ready code. For multi-statement writes, open your own transaction, call set_config as its first statement, and run the rest of the work on that transaction client.
Using it from a page:
// app/(saas)/app/[tenant]/invoices/page.tsx
import { requireTenantMember } from '@/lib/tenant';
import { getTenantDb } from '@/lib/db/prisma';
export default async function InvoicesPage({ params }: { params: Promise<{ tenant: string }> }) {
const { tenant: encodedHost } = await params;
const { tenant } = await requireTenantMember(decodeURIComponent(encodedHost));
const db = getTenantDb(tenant.id);
// RLS limits this to the current tenant. Keeping an explicit filter as well
// is cheap defense in depth and helps the planner use the tenant index.
const invoices = await db.invoice.findMany({
where: { tenantId: tenant.id },
orderBy: { createdAt: 'desc' },
take: 50,
});
return (
<ul className="space-y-4">
{invoices.map((invoice) => (
<li key={invoice.id}>
Invoice {invoice.id}: {invoice.amount.toString()}
</li>
))}
</ul>
);
}
The tenant ID passed to getTenantDb must come from requireTenantMember, never from a form field, query string, or client-supplied header. RLS guarantees the query matches the tenant in app.current_tenant; it cannot know whether that tenant was the right one for this user. That is why the membership check exists.
If your SaaS also has user-level permissions inside each tenant (admins, billing managers, viewers), layer them on top of this. Our guide to role-based access control from scratch in Node.js covers that model.
Cookies, Sessions, and Subdomain Boundaries
Cookies are where subdomain-based multi-tenancy most often goes wrong.
A cookie set with Domain=saascraft.com is sent to saascraft.com and every subdomain. If acme.saascraft.com can set such a cookie, it is also sent to globex.saascraft.com. Without a Domain attribute, the cookie is host-only and is sent only to the exact host that set it.
| Cookie setting | Sent to | Use for |
|---|---|---|
No Domain attribute | Exact host only | Tenant session cookies (recommended) |
__Host- prefix, Secure, Path=/, no Domain | Exact host only, enforced by the browser | Session cookies where supported (strongest) |
Domain=saascraft.com | Apex and all subdomains | Avoid for sessions; only non-sensitive prefs |
A session cookie set from a Server Action or Route Handler:
// lib/auth/session-cookie.ts (Next.js 15+: cookies() is async)
import 'server-only';
import { cookies } from 'next/headers';
const SESSION_COOKIE = '__Host-session';
export async function setSessionCookie(sessionToken: string, expiresAt: Date) {
const cookieStore = await cookies();
cookieStore.set(SESSION_COOKIE, sessionToken, {
httpOnly: true,
secure: true, // required for the __Host- prefix; use HTTPS locally or a different name in dev
sameSite: 'lax',
path: '/',
expires: expiresAt,
// No `domain`: the cookie stays on the exact tenant host.
});
}
Consequences of host-only sessions:
- A user who belongs to two tenants signs in once per tenant host. If you want single sign-in across tenants, run authentication on one central host (for example
auth.saascraft.comor a separate apex domain) and hand each tenant host a short-lived, single-use code that it exchanges for its own host-only session. - Vercel's multi-tenant docs recommend submitting your shared tenant domain to the Public Suffix List when tenants can publish content or run code on subdomains. Browsers then treat each tenant subdomain as a separate site and refuse cookies scoped to the shared parent. Until that lands, keep your dashboard and auth on a different apex domain where possible, use
__Host-cookies, and validate theOriginheader or use CSRF tokens on mutations.
For deeper background on token storage, see secure JWT authentication with HttpOnly cookies. Enterprise tenants will also ask for single sign-on; the SAML SSO and automated provisioning guide covers how that plugs into per-tenant identity providers.
Automating Custom Domain Provisioning
Enterprise tenants often want white-labeled domains such as dashboard.client.com. Adding them by hand in a hosting dashboard does not scale, so wire it into the product.
On Vercel, the REST endpoint is POST /v10/projects/{idOrName}/domains with a JSON body containing name. The response includes verified and, when the domain is already in use elsewhere on Vercel, a verification array of challenges (for example a TXT record) the tenant must add before Vercel will serve and issue a certificate for it.
The Server Action below is deliberately strict. Server Actions are reachable by direct POST requests, so the action derives the tenant from the request host and the session, never from an argument the client sends:
// app/(saas)/app/[tenant]/settings/domains/actions.ts
'use server';
import { headers } from 'next/headers';
import { requireTenantMember } from '@/lib/tenant';
import { prisma } from '@/lib/db/prisma';
const CUSTOM_DOMAIN_PATTERN = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
export async function addCustomDomain(formData: FormData) {
const host = (await headers()).get('host') ?? '';
const { tenant, role } = await requireTenantMember(host.replace(/:\d+$/, ''));
if (role !== 'owner' && role !== 'admin') throw new Error('Forbidden');
const domain = String(formData.get('domain') ?? '')
.trim()
.toLowerCase();
if (!CUSTOM_DOMAIN_PATTERN.test(domain) || domain.endsWith(`.${process.env.ROOT_DOMAIN}`)) {
throw new Error('Enter a valid domain you own, such as app.example.com');
}
const projectId = process.env.VERCEL_PROJECT_ID;
const teamId = process.env.VERCEL_TEAM_ID;
const token = process.env.VERCEL_API_TOKEN;
if (!projectId || !teamId || !token) throw new Error('Vercel domain API is not configured');
const response = await fetch(
`https://api.vercel.com/v10/projects/${projectId}/domains?teamId=${teamId}`,
{
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ name: domain }),
cache: 'no-store',
},
);
const data = await response.json();
if (!response.ok) {
throw new Error(data?.error?.message ?? `Vercel returned ${response.status}`);
}
// Stays 'pending' until DNS points at the platform and any verification challenge passes.
await prisma.tenantDomain.create({
data: { domain, tenantId: tenant.id, status: 'pending' },
});
return { verified: data.verified as boolean, verification: data.verification ?? [] };
}
What happens next:
- Show the tenant the DNS records to add: usually a
CNAMEfor a subdomain such asapp.client.com, or anArecord for an apex domain, plus any TXT record fromverification. - A background job calls Vercel's verify endpoint (
POST /projects/:idOrName/domains/:domain/verify, exposed asprojectsVerifyProjectDomainin the Vercel SDK) until the domain verifies, then flipstenant_domains.statustoactive. - Only
activedomains resolve inresolveTenantByHost, so a domain someone added but does not control never serves tenant content. - When a tenant removes a domain or churns, remove it from the project and delete or deactivate the mapping. A dangling mapping on a domain that someone else later points at your platform is a takeover risk.
On other platforms the shape is the same: Cloudflare for SaaS custom hostnames, or a reverse proxy with on-demand TLS such as Caddy. Gate certificate issuance on your own domains table so attackers cannot make you request certificates for arbitrary hostnames.
Tenant-Safe Caching in Next.js 16
Caching is the quiet way multi-tenant apps leak data. A cached sidebar rendered for Acme and reused for Globex is a breach, even though RLS was never bypassed.
Rules that hold across Next.js caching mechanisms:
- Every cached function takes the tenant ID as an argument. With the
'use cache'directive (stable in Next.js 16 behind thecacheComponentsoption), serializable arguments and captured variables become part of the cache key automatically. - Never read
cookies()orheaders()inside a cached scope. Next.js forbids it in'use cache'and throws. Read them outside and pass plain values in. - Tag per tenant, so invalidation stays scoped.
- Next.js 16 changed
revalidateTag: it now takes a second argument with a cache life profile, such asrevalidateTag(tag, 'max'). For read-your-own-writes in a Server Action, useupdateTag(tag).
// lib/data/invoices.ts (Next.js 16 with cacheComponents: true)
import 'server-only';
import { cacheLife, cacheTag } from 'next/cache';
import { getTenantDb } from '@/lib/db/prisma';
export function invoicesTag(tenantId: string) {
return `tenant:${tenantId}:invoices`;
}
export async function getInvoiceSummary(tenantId: string) {
'use cache';
cacheLife('minutes');
cacheTag(invoicesTag(tenantId)); // tenantId is also part of the cache key
const db = getTenantDb(tenantId);
const [count, totals] = await Promise.all([
db.invoice.count({ where: { tenantId } }),
db.invoice.aggregate({ where: { tenantId }, _sum: { amount: true } }),
]);
return { count, total: totals._sum.amount?.toString() ?? '0' };
}
// In a Server Action, after the membership check and the write:
// import { updateTag } from 'next/cache';
// updateTag(invoicesTag(tenant.id));
Only call getInvoiceSummary after requireTenantMember has succeeded for that tenant. The cache does not know who is asking; it only knows the key. If you use a shared remote cache handler (Redis or a platform KV), the same rule applies to its keys. Our deep dive on taming the App Router cache covers the wider caching model.
Architecture Options Compared
There is no single right isolation model. The table compares the common options:
| Model | Isolation strength | Operational cost | Good fit |
|---|---|---|---|
| Shared tables, app-level filter | Depends on every query being correct | Lowest | Prototypes, internal tools |
| Shared tables + RLS (this post) | Enforced by PostgreSQL per row | Low; one schema, one migration path | Most B2B SaaS from first customer to large scale |
| Schema per tenant | Separate namespaces, shared server | Migrations run N times; catalog bloat at high counts | Moderate tenant counts with per-tenant customization |
| Database per tenant | Strongest; separate storage and limits | Highest; N pools, N backups, N migrations | Regulated or data-residency customers, often enterprise tier |
A hybrid is common: everyone starts in the pooled RLS database, and a few enterprise tenants move to a dedicated database when contracts require it. If you keep tenant resolution behind one function and data access behind getTenantDb, that move becomes a configuration change rather than a rewrite. For cost-driven consolidation from silo to pool, see optimizing SaaS database costs by migrating multi-tenant PostgreSQL.
Testing Tenant Isolation
Isolation needs automated tests, not just code review. A minimal set:
// tests/rls.test.ts (Vitest, against a real PostgreSQL test database)
import { describe, expect, it, beforeAll } from 'vitest';
import { prisma, getTenantDb } from '@/lib/db/prisma';
let acmeId: string;
let globexId: string;
beforeAll(async () => {
// Seed with a separate admin connection or migration script; omitted here.
acmeId = process.env.TEST_ACME_TENANT_ID!;
globexId = process.env.TEST_GLOBEX_TENANT_ID!;
});
describe('row-level security', () => {
it('returns no invoices without a tenant context', async () => {
expect(await prisma.invoice.count()).toBe(0);
});
it('only returns rows for the current tenant', async () => {
const rows = await getTenantDb(acmeId).invoice.findMany();
expect(rows.length).toBeGreaterThan(0);
expect(rows.every((row) => row.tenantId === acmeId)).toBe(true);
});
it('rejects writes into another tenant', async () => {
await expect(
getTenantDb(acmeId).invoice.create({
data: { tenantId: globexId, amount: '10.00', status: 'draft' },
}),
).rejects.toThrow(); // violates the WITH CHECK clause
});
});
These tests only mean something if the test connection uses the same non-superuser role as production. A test suite running as postgres will bypass RLS and pass for the wrong reason. Add a CI check that runs SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user and fails if either is true.
On the routing side, Next.js includes experimental helpers in next/experimental/testing/server (since 15.1; on Next.js 16 they include unstable_doesProxyMatch, isRewrite, and getRewrittenUrl) for unit testing the proxy function: assert that root hosts rewrite to /home, tenant hosts rewrite to /app/<host>, reserved subdomains return 404, and malformed hosts return 400.
Operational Trade-offs and Considerations
The shared database with RLS is a strong default, but it comes with operational realities:
- Connection pooling. Serverless and autoscaled Node.js instances open many connections. Put a pooler in front of PostgreSQL. Transaction-local settings work in transaction pooling mode; session-level
SETdoes not. See database connection pooling under traffic spikes. - Per-query overhead. Each tenant query is a small transaction with an extra
set_configstatement. Measure it in your environment. The policy itself is a simple equality on an indexed column, so plans stay efficient whentenant_idleads your indexes. - Cross-tenant work. Billing rollups, analytics, and support tooling need to read across tenants. Use a separate role and a separate code path (ideally a separate service or job runner) for that. Do not give the web app's role
BYPASSRLS, and log every use of the privileged path. - Noisy neighbors. One tenant's heavy report can slow everyone. Add statement timeouts, per-tenant rate limits, and move heavy reporting to replicas.
- Migrations. Every new tenant-owned table needs
ENABLE,FORCE, and a policy. Add a CI query that lists tables with atenant_idcolumn whererelrowsecurityorrelforcerowsecurityis false inpg_class, and fail the build if any appear. - Proxy runtime. Proxy in Next.js 16 always runs on Node.js. Keep it fast and free of database calls; heavy logic there adds latency to every request, including prefetches.
Common Mistakes and Failure Modes
| Mistake | What goes wrong | Fix |
|---|---|---|
Only AS RESTRICTIVE policies on a table | Every query returns zero rows | Use a permissive policy; add restrictive ones only on top |
App connects as postgres or the table owner without FORCE | RLS silently does nothing | Dedicated NOSUPERUSER NOBYPASSRLS role, FORCE ROW LEVEL SECURITY |
Session-level SET app.current_tenant with a pooler | Next request on that connection inherits another tenant | set_config(..., true) inside the same transaction |
query(args) called inside an interactive transaction callback | Query may run on another connection without the setting | Batch $transaction([setConfig, query(args)]) |
Trusting an x-tenant-id header or form field | Any client can claim any tenant | Resolve from host, then check membership server-side |
| Falling back to a default tenant for unknown hosts | Unknown or hijacked domains serve real data | 404 for unmapped or inactive domains |
Domain=apex session cookies | Sibling tenant subdomains can read or overwrite sessions | Host-only __Host- cookies |
| Cache keys or tags without tenant ID | One tenant sees another's cached UI | Pass tenant ID into every cached function and tag |
Synchronous params.tenant or cookies().get() | Type errors or runtime errors on Next.js 16 | await params, await cookies(), await headers() |
Keeping middleware.ts with Edge-only code after upgrading | Renaming to proxy.ts changes the runtime to Node.js | Rename deliberately; stay on middleware.ts if you need Edge |
Production Readiness Checklist
- Wildcard DNS and wildcard certificate configured; deeper subdomain levels handled if you use them.
-
proxy.ts(ormiddleware.tson Next.js 15 and earlier) normalizes and validates the host, blocks reserved subdomains, and preserves query strings. - Unknown and inactive hosts return 404; there is no default tenant.
- Every tenant layout, page, Server Action, and Route Handler calls
requireTenantMember(or the equivalent) before touching data. - All
params,cookies(), andheaders()access is awaited. - Every tenant-owned table has RLS enabled and forced, with a permissive policy using both
USINGandWITH CHECK. - The runtime database role is not a superuser, has no
BYPASSRLS, and does not own the tables; CI verifies this. - Tenant context is set with
set_config(..., true)in the same transaction as the queries. -
tenant_idleads the relevant indexes. - Session cookies are host-only (
__Host-prefix,Secure,HttpOnly,Path=/, noDomain), and mutations checkOriginor a CSRF token. - Cached functions take tenant ID as an argument and use tenant-scoped tags;
revalidateTagcalls use the Next.js 16 two-argument form. - Custom domains are only activated after verification, and removed domains are cleaned up.
- Isolation tests run in CI against a real PostgreSQL instance using the production role.
- Logs and traces include tenant ID (not tenant data) so incidents can be scoped quickly.
Scaling to Enterprise Readiness
Moving from a single-customer app to a multi-tenant B2B platform changes how you think about routing, identity, data, and caching all at once. The design in this guide keeps each concern in one place: proxy.ts maps hosts to routes, one resolver maps hosts to tenants, one membership check maps users to tenants, PostgreSQL RLS enforces the data boundary, and tenant-aware cache keys and host-only cookies keep the edges tight. None of these layers is enough alone. Together, a single mistake in one layer no longer becomes a cross-tenant incident.
Natural next steps are per-tenant SSO, audit logging of cross-tenant administrative access, per-tenant rate limits, and a documented path for moving a large tenant to a dedicated database.
If you are moving a product from B2C to B2B, or untangling a multi-database setup that has become expensive to run, book a free architecture review to talk to our backend engineers about consolidating infrastructure, automating tenant provisioning, and tightening data isolation.
Sources
- Next.js Docs: proxy.js file convention
- Next.js Docs: Upgrading to version 16
- Next.js Docs: use cache directive
- PostgreSQL Docs: Row Security Policies and CREATE POLICY
- Prisma client extensions: row-level security example and Upgrading to Prisma ORM 7
- Vercel Docs: Configuring custom domains for multi-tenant platforms, Add a domain to a project (REST API), and MDN: Set-Cookie
Frequently Asked Questions
How do subdomains and custom domains route to the right tenant in Next.js?
A proxy.ts file (named middleware.ts before Next.js 16) reads the Host header, validates it, and rewrites the request to an internal route such as /app/[tenant]/.... The tenant layout then looks up that host in a domains table you control, returns 404 if it is unknown, and checks that the signed-in user is a member of the tenant before loading any data.
Is middleware.ts still supported in Next.js 16?
It is deprecated but still works. Next.js 16 renamed the convention to proxy.ts with an exported proxy function, and proxy always runs on the Node.js runtime. If you depend on the Edge runtime, the upgrade guide says to keep using middleware.ts for now. Otherwise run the middleware-to-proxy codemod.
Why use PostgreSQL row-level security for tenant isolation?
With RLS, the database filters rows by the current tenant on every query, so a forgotten WHERE tenant_id = ... cannot return another customer's data. It only works if the application connects as a role that is not a superuser and does not have BYPASSRLS, and if the policies are permissive. A table with only restrictive policies returns no rows.
Can I trust a tenant ID sent from the client?
No. Treat any tenant identifier from headers, query strings, or form fields as untrusted input. Derive the tenant from the request host, resolve it server-side, and verify the user's membership. RLS then enforces that the queries match the tenant you resolved.
How do you add customer custom domains automatically?
Add the domain to your hosting project through its API (on Vercel, POST /v10/projects/{idOrName}/domains), store it as pending, show the tenant the DNS and verification records to add, and activate the mapping only after verification succeeds. The platform then issues a certificate for that domain.
Should each tenant get its own database instead?
A shared database with RLS is simpler and cheaper for most B2B SaaS products. Separate databases make sense for customers with strict data residency, performance isolation, or contractual requirements, and many platforms offer them as an enterprise tier while keeping everyone else in the pooled database.
