Advanced 24 min readModule: Module 14: Multi-Tenant Architecture, Subdomains & Edge Auth
Multi-Tenant Subdomains & Edge Middleware Architecture
Architect scalable multi-tenant SaaS platforms in Next.js: subdomain routing (tenant.app.com), custom domain rewriting, Edge Middleware URL rewrites, and high-speed JWT authentication.
What You Will Learn in This Lesson
- The architecture of Multi-Tenant SaaS: Subdomains (`org.kwas.dev`) and Custom Domains (`org.com`)
- URL Rewriting inside Edge `middleware.ts` without modifying the browser's address bar
- Edge authentication: verifying JWTs in sub-millisecond V8 isolates using `jose`
- Dynamic tenant isolation in database queries and caching tags
Introduction & Core Concept
Multi-tenancy is an architectural model where a single software instance serves multiple distinct customer organizations (tenants). In Next.js, Edge Middleware allows developers to inspect the incoming 'Host' header at the global edge network, authenticate the user, and transparently rewrite the request to tenant-specific route folders (e.g. `app/[tenant]/...`) in sub-millisecond latency.
WHY DOES THIS MATTER IN THE REAL WORLD?
Platforms like Shopify, Notion, and Vercel use multi-tenant edge routing to host millions of custom customer domains on a single unified Next.js codebase.
Syntax & Structure
typescript
// middleware.tsexport function middleware(req: NextRequest) { const hostname = req.headers.get('host'); return NextResponse.rewrite(new URL(`/${tenant}${req.nextUrl.pathname}`, req.url));}Production Multi-Tenant Subdomain Edge Middleware
typescripttypescript
1234567891011121314151617181920212223242526272829// middleware.ts: Multi-Tenant Edge Routing Engineimport { NextResponse } from "next/server";import type { NextRequest } from "next/server";export const config = {matcher: ["/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)"],};export function middleware(req: NextRequest) {const url = req.nextUrl;const hostname = req.headers.get("host") || "kwasacademy.dev";// 1. Extract tenant subdomain (e.g., 'acme.kwasacademy.dev' -> 'acme')const currentHost = hostname.replace(`:${process.env.PORT || 3000}`, "");const isRootDomain = currentHost === "kwasacademy.dev" || currentHost === "localhost";// 2. Route root domain to main marketing platformif (isRootDomain) {return NextResponse.rewrite(new URL(`/home${url.pathname}`, req.url));}// 3. Extract Tenant ID for enterprise subdomainsconst tenantId = currentHost.split(".")[0];// 4. Transparently rewrite request to tenant-isolated dynamic folder: app/[tenant]/...return NextResponse.rewrite(new URL(`/${tenantId}${url.pathname}${url.search}`, req.url));}
Line-by-Line Technical Breakdown
1Edge vs Node.js Runtime: Edge Middleware runs on lightweight V8 isolates rather than full Node.js processes. It cannot use Node.js native C++ modules or heavy ORMs, but excels at lightning-fast header routing, cookie parsing, and cryptographic JWT verification using Web Standard APIs.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[TYPESCRIPT]
TYPESCRIPT SOURCE EDITOR
Interactive Live CodeCommon Mistakes & How to Avoid Them
#1: Using `NextResponse.redirect` instead of `NextResponse.rewrite` for tenant routing.
Redirect alters the visible URL in the user's browser bar. Rewrite routes internally while preserving the user's branded custom domain.
Incorrect / Antipattern
return NextResponse.redirect(new URL(`/tenant/${path}`, req.url));Correct / Professional Solution
return NextResponse.rewrite(new URL(`/${tenantId}${path}`, req.url));Industry Best Practices & Professional Standards
- Use the `jose` library for Edge JWT verification instead of heavy `jsonwebtoken`.
- Cache custom domain lookup mappings at the Edge using KV stores (Upstash or Redis).
- Tag tenant database queries with tenant-scoped cache tags (`revalidateTag(`tenant-${id}`)`).
Lesson Summary & Core Takeaways
- Multi-tenant Next.js routes custom subdomains to isolated app folders.
- Edge Middleware rewrites URLs transparently at global Edge locations.
- Preserves customer branding while maintaining a single scalable codebase.