The user wants a design for a multi-tenant Next.js application using the App Router.
The key requirements are:
- Multi-tenancy: Handling multiple clients/domains/paths from a single codebase.
- App Router: Using Next.js 13/14+ features (Server Components, Layouts, etc.).
- Performance Strategy: Balancing three specific rendering/caching techniques:
- Static ISR (Incremental Static Regeneration)
- Streaming SSR (Server-Side Rendering with Suspense)
- Edge Caching (CDN level)
1. Conceptualizing the Multi-tenancy:
- How to identify the tenant?
- Subdomains (tenant1.app.com) - cleaner, requires wildcard DNS.
- Pathnames (app.com/tenant1) - easier for local dev/Nginx, but messier URLs.
- Headers (rarely used for public routing, good for enterprise white-labeling behind a gateway).
- Middleware is key. I need to intercept the request to extract the tenant ID and perhaps rewrite the URL internally so Next.js generates paths correctly.
2. Routing Architecture (App Router specifics):
middleware.ts: The entry point for tenant detection.
app/[tenantId]/...: Dynamic routes to handle specific tenant content.
app/(public)/...: Shared routes (auth, legal).
3. Balancing the Rendering Strategies:
- Static ISR: Good for content that doesn't change often or can tolerate slight staleness (e.g., Landing pages, Blog posts, Documentation).
- Multi-tenant twist:
generateStaticParams is crucial here to pre-render common tenants at build time. On-demand revalidation is needed when a tenant updates data.
- Streaming SSR: Good for personalized or highly dynamic data (e.g., Dashboards, User profiles, Real-time analytics).
- Next.js feature:
loading.tsx and Suspense.
- Edge Caching: The glue layer.
- Caching the output of the rendering.
next.cache control.
stale-while-revalidate headers.
4. Designing the Solution - Step-by-Step:
-
Step 1: Middleware & Tenancy Detection
- Map host -> tenantId.
- Rewrite to internal structure.
-
Step 2: Data Layer (The "Brain")
- Need a database schema concept (tenants, users).
- Need a data fetching pattern. Single queries vs. batching.
- Crucial: Cache invalidation logic.
-
Step 3: ISR Implementation (Static parts)
layout.tsx (Tenant Branding).
page.tsx (Landing page).
- Use
generateStaticParams for top 50 tenants, fallback to "ISR on demand" for others.
- Revalidation tags (Next.js 14 feature
unstable_cache or fetch tags) are vital for multi-tenant invalidation (e.g., revalidateTag('tenant-${id}')).
-
Step 4: Streaming SSR Implementation (Dynamic parts)
- Dashboard components.
- Wrap heavy queries in Suspense.
- Use
loading.tsx for route segments.
-
Step 5: Edge Caching Configuration
next.config.js headers.
- Vercel/Cloudflare specific headers (Cache-Control).
5. Drafting the Code Structure & Examples:
- Middleware: Parse host, set header
x-tenant-id, rewrite.
- Page Component:
- Fetch data using
fetch (extended in Next.js).
- Set
next: { tags: [...] }.
- Streaming: Use standard async Server Components.
- ISR Config: Export
generateStaticParams.
6. Refinement & "Gotchas":
- Security: Ensure Tenant A cannot fetch Tenant B's data via API routes. The middleware must pass context securely.
- Cache stampede: If a tenant updates, don't kill the server.
- Environment variables: How to handle tenant-specific ENVs? (Usually better to store in DB).
7. Structuring the Answer:
- High-Level Overview: The "Triangle" of performance.
- Routing Strategy: Middleware based multi-tenancy.
- Data Strategy: Fetching with caching tags.
- Rendering Modes:
- ISR for Marketing/Public pages.
- Streaming SSR for Dashboards/App pages.
- Edge/CDN Strategy: Headers and revalidation.
- Code Examples: Practical snippets for each section.
(Self-Correction during drafting):
- Initial thought: Use subdomains.
- Refinement: Subdomains are standard. I should mention that Middleware rewrites to a dynamic route
[tenant] so the file system remains clean.
- ISR Detail: Don't just say "use ISR". Explain how to scope it per tenant. Using
generateStaticParams creates the files. Using revalidateTag updates them.
- Streaming: Make sure to emphasize that parts of the page can be static while others stream.
8. Final Polish:
- Ensure terminology is up to date (Next.js 14/15).
- Mention
unstable_cache if standard fetch isn't used, though fetch is preferred.
- Highlight the "Cache-Control" headers for the Edge.
Let's build the response based on this structure.
- Phase 1: Tenant Resolution (Middleware).
- Phase 2: The "Shell" (ISR Layouts).
- Phase 3: The "Core" (Streaming SSR).
- Phase 4: The Cache Strategy (Tags & Edge).
(Drafting the code snippets mentally)
middleware.ts -> NextResponse.rewrite(new URL('/tenant/${id}', ...))
app/tenant/[id]/page.tsx -> fetch(..., { next: { tags: ['tenant-${id}'] } })
Okay, looks solid. I will generate the response now.
This architecture requires a sophisticated orchestration of Next.js middleware, server components, and cache headers. The goal is to serve a "dynamic shell" (streaming SSR) for user-specific data while serving "cached fragments" (ISR) for public content, all scoped to specific tenants.
Here is a comprehensive design for a Multi-Tenant Next.js App Router Architecture.
1. The High-Level Strategy
We will separate the rendering strategy based on the nature of the content, not just the page.
- The Tenant Shell (ISR): The navigation, branding, and static landing pages are generated once and cached (ISR).
- The User Data (Streaming SSR): User dashboards and personalized feeds are rendered on-demand via streaming to maintain low TTFB (Time To First Byte).
- The Edge (Middleware): Handles tenant resolution and geo-routing before the request hits the origin.
2. Project Structure
We use the App Router’s file-system routing to separate concerns.
/app
/(tenant) # Route Group: Handles tenant-specific pages
/layout.tsx # The Tenant Root Layout (Branding/Nav)
/page.tsx # Tenant Homepage (ISR)
/dashboard
/page.tsx # User Dashboard (Streaming SSR)
/api
/revalidate # Webhook handler for On-Demand ISR
/layout.tsx # Root Layout (Fonts, Global Providers)
/middleware.ts # Tenant Resolution & Edge Logic
3. Tenant Resolution (The Edge Layer)
We use middleware.ts to resolve the tenant before the render begins. This is crucial for performance and security.
Strategy:
- Identify tenant via subdomain (e.g.,
acme.app.com) or path (e.g., app.com/acme).
- Fetch tenant config (theme, logo) from an Edge-Config store (like Vercel Edge Config or Upstash) to avoid DB round-trips.
- Rewrite the URL internally and pass tenant context via headers.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export async function middleware(request: NextRequest) {
const host = request.headers.get('host') || '';
// 1. Extract Tenant ID (Logic depends on your domain strategy)
// Example: acme.myapp.com -> 'acme'
const subdomain = host.split('.')[0];
const tenantId = subdomain;
if (!tenantId) {
return new Response('Tenant not found', { status: 404 });
}
// 2. Rewrite URL to the generic tenant route group
// The user sees: acme.myapp.com/dashboard
// Next.js sees: / (tenant)/dashboard
const url = request.nextUrl.clone();
// 3. Pass Tenant ID to Server Components via Headers
const response = NextResponse.rewrite(url);
response.headers.set('x-tenant-id', tenantId);
return response;
}
export const config = {
// Match all pathnames except for static files, api, etc.
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
4. Implementing ISR (Static Content)
For pages that look the same for all users of a tenant (e.g., Landing Page, About Us), we use ISR. This offloads traffic from your origin server to the Edge CDN.
app/(tenant)/page.tsx
import { headers } from 'next/headers';
// 1. Define caching strategy
export const revalidate = 3600; // Revalidate every hour
async function getTenantContent(tenantId: string) {
const res = await fetch(`https://api.cms.io/content/${tenantId}`, {
// 'force-cache' is default, but explicit here
cache: 'force-cache',
// Tagging allows us to manually purge cache later
next: { tags: [`tenant-content-${tenantId}`] }
});
return res.json();
}
export default async function TenantLanding() {
const headersList = headers();
const tenantId = headersList.get('x-tenant-id');
// This data is cached at the Edge
const content = await getTenantContent(tenantId);
return (
<div>
<h1>{content.title}</h1>
<p>{content.description}</p>
</div>
);
}
5. Implementing Streaming SSR (Dynamic Content)
For personalized pages (Dashboards), we cannot cache the HTML. However, we don't want the whole page to hang while waiting for the database. We use React Suspense to stream the UI.
app/(tenant)/dashboard/page.tsx
import { headers } from 'next/headers';
import { Suspense } from 'react';
// Disable caching completely for this page
export const dynamic = 'force-dynamic';
// Skeleton Component
function DashboardSkeleton() {
return <div className="pulse">Loading user stats...</div>;
}
// Async Component fetching heavy data
async function UserStats({ tenantId }: { tenantId: string }) {
// This fetch is specific to the user, so no caching
// Simulating a delay
await new Promise(resolve => setTimeout(resolve, 2000));
const stats = await fetch(`https://api.db.io/stats/${tenantId}`).then(r => r.json());
return <div>Active Users: {stats.count}</div>;
}
export default function DashboardPage() {
const headersList = headers();
const tenantId = headersList.get('x-tenant-id');
return (
<main>
<nav>Dashboard Nav</nav>
{/* The shell renders immediately. Stats stream in later. */}
<Suspense fallback={<DashboardSkeleton />}>
<UserStats tenantId={tenantId} />
</Suspense>
</main>
);
}
6. Cache Invalidation & Webhooks
Since we are caching ISR heavily, we need a way to update content immediately when a tenant updates their branding in the CMS. We use On-Demand Revalidation.
app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
// 1. Verify Secret (Security check)
const secret = request.nextUrl.searchParams.get('secret');
if (secret !== process.env.MY_SECRET) {
return NextResponse.json({ message: 'Invalid token' }, { status: 401 });
}
// 2. Get Tenant ID from Payload
const { tenantId } = await request.json();
// 3. Purge the cache for this specific tenant
// This matches the tag defined in step 4
revalidateTag(`tenant-content-${tenantId}`);
return NextResponse.json({ revalidated: true, now: Date.now() });
}
7. Hybrid Architecture: Putting it Together
Here is the flow of a request in this architecture:
- User Request:
GET acme.app.com/dashboard
- Edge (Middleware):
- Matches subdomain
acme.
- Checks Edge Config (Redis) for
acme settings.
- Sets header
x-tenant-id: acme.
- Next.js Origin (Server):
- Route Match: Hits
app/(tenant)/dashboard/page.tsx.
- Layout (Cached): Fetches the layout menu items using
fetch(..., { next: { revalidate: 3600 } }).
- Page (Dynamic): Detects
dynamic = 'force-dynamic'.
- Streaming: Starts sending HTML to the browser immediately. The
<Suspense> boundary shows a skeleton.
- Client (Browser):
- Renders the Nav and Skeleton instantly.
- The
UserStats promise resolves on the server.
- Server streams the final HTML chunk to the client, which swaps the skeleton for the real content.
8. Optimization Checklist
To ensure this scales effectively:
- Shared Component Cache: Ensure your
fetch calls inside Server Components utilize the next: { tags: [...] } feature efficiently. Even inside a dynamic page, you might have sub-components (like a "Recent Orders" list) that are static for 5 minutes.
- Vercel Edge Config: Store tenant config (Theme colors, feature flags) in Edge Config, not a standard DB. Middleware needs this to be sub-10ms.
- Cache-Control Headers: By default, Next.js handles this, but if you have a CDN in front of Vercel (like Cloudflare), ensure it respects the
Vary header on x-tenant-id (though Vercel handles this abstraction automatically).
- Isolation: Use Route Groups
(tenant) to ensure tenant-specific layouts don't bleed into public routes like /login or /terms.