SaaS Architecture Pillars
SaaS applications rely on three major systems: multi-tenant database routing, subscription billing configurations, and custom domains maps. Integrating these elements with Next.js is streamlined via middleware-level subdomain routing and edge-computed header lookups.
Middleware Subdomain Routing
Using Next.js Middleware, we intercept the incoming request, read the Host header, and rewrite the URL internally. This allows 'customer.mysaas.com' to seamlessly route to 'app/[tenantId]/dashboard' without changing the URL in the browser.
export default function middleware(req) {
const url = req.nextUrl.clone();
const hostname = req.headers.get('host');
const tenant = hostname.split('.')[0];
url.pathname = `/_tenant/${tenant}${url.pathname}`;
return NextResponse.rewrite(url);
}Vercel Infrastructure Integration
By deploying on Vercel, we utilize Edge Config for instant feature flagging across our multi-tenant base, and Image Optimization to dynamically resize tenant logos on the fly. This architecture allows a small team to run a globally distributed SaaS.