Subdomain and Path-Based Tenant Resolution
Resolve tenants from subdomains or path prefixes using middleware rewrites and headers.
What Is Tenant Resolution?
In a multi-tenant SaaS application, every incoming request must be mapped to a specific tenant before any business logic runs. This process is called tenant resolution.
There are two dominant strategies:
- Subdomain-based:
acme.app.com,globex.app.com— each tenant owns a subdomain. - Path-based:
app.com/acme/dashboard,app.com/globex/dashboard— the tenant slug appears as the first path segment.
Next.js 15 middleware runs on the Edge Runtime before any page or API route is processed, making it the ideal place to extract, validate, and forward tenant context to the rest of the application.
Next.js Middleware Basics
Middleware in Next.js 15 lives in middleware.ts at the project root. It exports a default middleware function and an optional config object with a matcher array.
Key points:
- Runs on every matched request before the route handler.
- Can read request headers, cookies, and the URL.
- Can rewrite the request URL (invisible to the browser) or redirect it.
- Can attach custom request headers that page components and API routes can later read.
The middleware function receives a NextRequest and must return a NextResponse.
// middleware.ts — minimal skeleton
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest): NextResponse {
// Inspect request.nextUrl, request.headers, request.cookies …
return NextResponse.next();
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};All lessons in this course
- Subdomain and Path-Based Tenant Resolution
- Row-Level Tenant Data Isolation Patterns
- Per-Tenant Theming and Feature Flags
- Usage Metering and Subscription Enforcement