
Building Multi-Tenant SaaS with Next.js
Building a Production-Grade Multi-Tenant SaaS with Next.js
A multi-tenant SaaS application is not simply a single application with an organizationId column. It is a distributed security boundary. Every request, database query, cache key, background job, file object, webhook, and administrative workflow must preserve the relationship between an authenticated principal and the tenant whose resources that principal is allowed to access.
The most dangerous production failure is not an unavailable page. It is a cross-tenant data leak caused by a missing filter, an incorrectly scoped cache key, a stale session, or an asynchronous job that lost tenant context. These defects often pass unit tests because the application works correctly for one organization. They appear only when multiple customers exercise the same code paths concurrently.
A robust Next.js multi tenant architecture therefore starts with invariants rather than routes:
- A request has exactly one resolved tenant context, or it is rejected.
- Authentication identifies a principal; authorization decides what that principal may do within a tenant.
- Database access is tenant-scoped by default and preferably enforced below the application layer.
- Cache keys, queues, object storage paths, and audit events contain tenant identity.
- Tenant context is immutable after resolution and is never accepted blindly from client input.
- Every privileged operation is observable and attributable to both a user and a tenant.
Next.js 15 is well suited to this model because Server Components, Route Handlers, Server Actions, and middleware allow security and data access to be placed close to the operation. However, these primitives do not automatically provide isolation. The architecture must define where identity is established, how it flows through the system, and which layer is authoritative for access control.
Tenant Resolution and Request Boundaries
There are three common tenant addressing models: subdomains such as acme.example.com, path prefixes such as example.com/acme, and tenant selection inside an authenticated session. Subdomains provide a clean customer-facing URL and work well for B2B SaaS. Path prefixes are easier in local development and can simplify wildcard DNS. Session-only selection is useful when users belong to many organizations, but it must not be treated as the only security control because a user can manipulate client-visible state.
Resolve the tenant at the edge of the request pipeline, then pass a canonical tenant identifier to the application. A hostname is not itself a database key. Map it through a trusted lookup, normalize casing, and verify that the tenant is active and has not been suspended.
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const hostname = request.headers.get('host')?.split(':')[0].toLowerCase();
const rootDomain = process.env.ROOT_DOMAIN!;
if (!hostname || hostname === rootDomain || hostname === `www.${rootDomain}`) {
return NextResponse.next();
}
const subdomain = hostname.endsWith(`.${rootDomain}`)
? hostname.slice(0, -(rootDomain.length + 1))
: null;
if (!subdomain || subdomain.includes('.')) {
return NextResponse.redirect(new URL('/invalid-tenant', request.url));
}
const response = NextResponse.next();
response.headers.set('x-tenant-slug', subdomain);
return response;
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
This example is intentionally incomplete: middleware should not be the sole place where tenant validity is checked. Middleware executes before the route, but it does not replace authorization and may run in an Edge runtime where database drivers or internal network access are unavailable. Use it for inexpensive routing, authentication redirects, and request metadata. Resolve the authoritative tenant record inside a trusted server-side function before querying business data.
For authenticated users, the server should verify that the principal is a member of the resolved tenant. Never accept a request body field such as tenantId as authority. At most, it is a selection hint that must be checked against the membership relation.
A practical request context contains:
type TenantContext = {
tenantId: string;
tenantSlug: string;
userId: string;
membershipId: string;
roles: string[];
permissions: string[];
requestId: string;
};
Create this context once per request. Pass it into repositories and services explicitly rather than relying on mutable global state. Explicit context makes security review easier and prevents accidental reuse across concurrent requests.
Authentication Is Not Authorization
Next.js middleware authentication is useful for rejecting anonymous traffic early, but a valid session proves only who the user is. It does not prove which tenant the user is accessing or whether the user can perform a specific operation.
A secure authorization chain is:
- Verify the session signature and expiration.
- Resolve the tenant from the trusted host or route.
- Load the user membership for the user and tenant.
- Check account state, tenant state, and any required MFA or session assurance level.
- Evaluate the permission required by the operation.
- Execute a tenant-scoped query inside a transaction where necessary.
For Role Based Access Control RBAC Next.js implementations, keep roles and permissions server-side. Roles are convenient bundles such as owner, admin, billing, and member; permissions are stable capabilities such as invoice.read or member.invite. Do not scatter role checks across JSX because a hidden button is not an authorization control.
const rolePermissions: Record<string, string[]> = {
owner: ['*'],
admin: ['member.read', 'member.invite', 'project.read', 'project.write'],
billing: ['invoice.read', 'invoice.manage'],
member: ['project.read'],
};
export function can(permissions: string[], required: string) {
return permissions.includes('*') || permissions.includes(required);
}
export async function requirePermission(
ctx: TenantContext,
permission: string,
) {
if (!can(ctx.permissions, permission)) {
throw new Response('Forbidden', { status: 403 });
}
}
Compute effective permissions from the database or a short-lived authorization cache, but invalidate that cache when membership, role, tenant status, or security policy changes. Long-lived JWT claims are operationally convenient but create a revocation window. For high-risk systems, keep identity in the session token and resolve authorization from a centralized store.
The authorization check must live in the server-side service boundary as well as in the UI. A Server Action that updates a project should call requirePermission before the mutation. A Route Handler should do the same. A background worker must revalidate authorization assumptions when it starts a sensitive job because the membership may have been revoked after enqueueing.
Multi-Tenant Database Isolation Strategies
There are three primary Multi-tenant database isolation strategies.
Shared database and shared schema
All tenants use the same tables and every tenant-owned row contains tenant_id. This model has the lowest infrastructure cost and is usually the best starting point for SaaS products with many small tenants. It simplifies migrations, analytics, and connection management.
Its weakness is human error. One missing predicate can expose another tenant's data. Treat tenant_id as a mandatory part of primary and unique keys where appropriate. For example, a project slug should usually be unique per tenant, not globally:
CREATE TABLE projects (
id uuid PRIMARY KEY,
tenant_id uuid NOT NULL REFERENCES tenants(id),
slug text NOT NULL,
name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (tenant_id, slug)
);
CREATE INDEX projects_tenant_id_created_at_idx
ON projects (tenant_id, created_at DESC);
Repositories should require tenant context in their method signatures:
export async function getProject(ctx: TenantContext, projectId: string) {
return db.project.findFirst({
where: {
id: projectId,
tenantId: ctx.tenantId,
},
});
}
Prefer findFirst with both identifiers over findUnique({ id }) when an object ID is not globally trusted. A globally unique UUID is not a substitute for tenant filtering.
Shared database with schema-level row-level security
PostgreSQL Row-Level Security adds a database-enforced boundary. The application sets a transaction-local tenant variable, and policies restrict rows to that value. This is substantially safer than relying on every developer to remember a predicate.
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;
CREATE POLICY projects_tenant_policy ON projects
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);
Set the variable using a transaction, not a pooled connection that might leak state to the next request:
await db.$transaction(async (tx) => {
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${ctx.tenantId}, true)`;
await tx.project.update({
where: { id: projectId },
data: { name },
});
});
The database role used by the application must not bypass RLS. Administrative migrations should use a separate role and should never be exposed to request code. RLS introduces complexity around connection pooling, raw SQL, joins, and operational tooling, but it provides a valuable last line of defense.
Database or schema per tenant
A dedicated database or schema provides stronger blast-radius control, independent backups, and easier compliance isolation. It also creates connection-pool, migration, provisioning, and observability challenges. Thousands of databases can overwhelm connection limits and complicate failover.
Use this model selectively for large, regulated, or noisy tenants. A hybrid architecture is often more practical: shared-schema storage for ordinary tenants and dedicated databases for contractual or scale-driven requirements. The application should hide this routing behind a tenant-aware data access layer so business services do not know where the tenant is physically stored.
State, Caching, and Asynchronous Work
Tenant isolation must survive beyond the synchronous HTTP request. Cache keys are a frequent source of leaks because the cached value may be correct while the key is incomplete.
Bad key:
`project:${projectId}`
Safer key:
`tenant:${ctx.tenantId}:project:${projectId}:v${schemaVersion}`
Include tenant identity in Redis keys, CDN tags, React cache arguments, and revalidation paths. Avoid caching personalized or permission-sensitive responses at a shared CDN unless the cache varies on a securely derived tenant and user dimension. In Next.js 15, explicitly decide whether a route is dynamic, publicly cacheable, or private. Accidental static caching is an architectural bug when output contains tenant data.
Server Components reduce client-side state duplication, but they do not remove consistency problems. After a Server Action mutates tenant data, revalidate the relevant tenant-scoped path or tag. Use versioned tags such as tenant:${tenantId}:projects rather than a global projects tag.
Background jobs must carry a complete execution envelope:
type JobEnvelope<T> = {
jobId: string;
tenantId: string;
actorUserId?: string;
requestId?: string;
type: string;
payload: T;
schemaVersion: number;
};
Workers should validate that the referenced tenant exists, is active, and owns the target resource. Make jobs idempotent using a tenant-scoped idempotency key. For example, billing webhooks should record the provider event ID per tenant before applying side effects. Retries are expected behavior, not exceptional behavior.
Files require the same discipline. Store objects under a path such as tenants/{tenantId}/uploads/{objectId} and issue signed URLs only after an authorization check. Do not expose sequential object identifiers or rely on obscurity of storage paths.
Production Protocols and Implementation Workflow
Adopt the following workflow before exposing a tenant-aware feature to production:
- Define the tenant boundary for every table, event, cache entry, file, and external API call.
- Add
tenant_idto every tenant-owned table and index it according to real query patterns. - Make tenant context mandatory in repository and service APIs.
- Add database constraints for tenant-local uniqueness and foreign-key relationships.
- Implement membership checks independently from route-level authentication.
- Add authorization tests for same-tenant allow, cross-tenant deny, revoked membership, suspended tenant, and missing context.
- Test cache isolation by issuing identical resource requests under two tenants.
- Test retries and duplicate delivery for every asynchronous operation.
- Log
request_id,tenant_id,user_id, operation, authorization result, latency, and database outcome. - Run automated queries or static analysis to detect tenant tables and repository methods that lack tenant predicates.
A minimal protected Route Handler might look like this:
export async function GET(request: Request) {
const ctx = await getTenantContext(request);
await requirePermission(ctx, 'project.read');
const projects = await projectRepository.list(ctx, {
limit: 100,
});
return Response.json({ data: projects });
}
Do not return raw database errors to clients. Classify failures into authentication, authorization, validation, dependency, and internal categories. Preserve enough diagnostic detail in structured logs to reconstruct the event without exposing tenant data.
Monitor metrics by tenant and globally:
- p50, p95, and p99 API latency by route and tenant tier.
- Authorization denial rate and membership lookup latency.
- Database query latency, connection-pool saturation, and lock waits.
- Cache hit ratio segmented by tenant-aware key space.
- Queue age, retry count, dead-letter volume, and idempotency conflicts.
- RLS policy failures and cross-tenant access test failures.
- Error budgets for high-value tenants and noisy-neighbor resource consumption.
Rate limits should usually be keyed by tenant and principal, not only by IP. Apply concurrency limits to expensive exports, imports, and report generation. A single tenant must not be able to exhaust the shared database pool or worker fleet.
Conclusion
A production-grade Next.js multi tenant architecture is built around explicit invariants: resolve one trusted tenant context, authenticate the principal, authorize every operation within that tenant, and enforce isolation at the database and infrastructure layers. Shared-schema storage is efficient, but row-level security and tenant-aware repository contracts reduce the risk of application mistakes. Dedicated storage is valuable for selected tenants, not automatically superior for every customer.
Next.js middleware authentication should handle early request gating, not serve as the complete security model. RBAC should be enforced in server-side services and backed by revocable membership state. Caches, queues, files, and webhooks must carry tenant identity just as carefully as SQL queries do.
The architecture is healthy when cross-tenant access tests fail closed, authorization changes propagate within a defined revocation window, p99 latency remains stable under tenant concurrency, and operational dashboards can attribute every expensive or suspicious action to a tenant and actor. Those are the signals that turn multi-tenancy from a routing feature into a dependable production boundary.