We are designing a multi-tenant Next.js App Router application that balances:
Static ISR (Incremental Static Regeneration) for content that can be static but updated periodically.
Streaming SSR (Server-Side Rendering) for dynamic content that changes per request and requires up-to-date data.
Edge Caching for caching responses at the edge (e.g., Vercel Edge Network) to improve performance.
Considerations for multi-tenant:
Each tenant might have its own domain or subdomain.
We need to isolate data and configuration per tenant.
We might have shared components and pages but with tenant-specific data.
Proposed architecture:
Tenant Identification:
Use middleware to identify the tenant from the request (hostname, path, or headers).
Store tenant context in a way that can be accessed by server components and API routes.
Data Fetching Strategies:
For static content that is the same for all tenants (or tenant-agnostic) but can be regenerated periodically: use generateStaticParams and revalidate in page components (ISR).
For content that is tenant-specific and static for a period: use ISR per tenant? But note that ISR generates static pages per set of parameters. We can have tenant as a parameter.
For dynamic content that changes per request (e.g., user session, real-time data): use streaming SSR with loading and error boundaries, and fetch data in server components without caching (or with cache control set to no-cache).
Edge Caching:
Use the cache option in fetch (available in Next.js 13.4+ with the App Router) to control caching at the edge.
We can set cache: 'force-cache' for ISR (which uses the edge cache and revalidates based on the revalidate option) and cache: 'no-store' for no caching.
Alternatively, we can set cache control headers in API routes or server components.
Middleware:
We'll use middleware to set the tenant context and possibly rewrite URLs if needed (e.g., for shared static assets).
We can also use middleware to set headers for edge caching (like Cache-Control).
Configuration:
Store tenant-specific configuration (like theme, feature flags) in a database and fetch it in a server component that wraps the application (e.g., a layout that fetches tenant config and provides it via context).
Caching Strategy per Tenant:
For pages that are static for a tenant but change infrequently: use ISR with tenant as a dynamic route segment. Example: [tenant]/page.tsx and in generateStaticParams we generate for all known tenants. Then each tenant's page is static and revalidated independently.
However, note that ISR in the App Router is per page and per set of dynamic parameters. So if we have 1000 tenants, we would have 1000 static pages? That might be too many. Alternatively, we can use a single static page that fetches tenant-specific data and revalidates at a set interval, but then the page is the same for all tenants? No, because we have tenant context.
Alternative for many tenants:
Use streaming SSR for tenant-specific pages that are not highly cacheable, and use edge caching with a short TTL for some parts? But note that edge caching by default in Next.js for static pages is long-term (until revalidate). For dynamic pages, we don't want to cache at the edge by default.
Hybrid Approach:
Break down the page into sections: some parts are static (ISR) and some are dynamic (SSR). We can use React Suspense to stream the dynamic parts while the static parts are already cached.
Implementation Steps:
Step 1: Tenant Middleware
In middleware.ts:
Identify tenant from request (hostname, path, etc.)
Attach tenant to request headers (e.g., x-tenant-id) so that server components and API routes can access it.
Optionally, rewrite the URL to include the tenant in the path if your app uses a single domain with tenant as a path segment.
Step 2: Tenant Layout
Create a layout that fetches tenant configuration (if needed) and provides it to the children. This layout can be a server component that uses fetch with cache: 'force-cache' and next: { revalidate: 3600 } for example, to revalidate every hour.
Step 3: Page with Mixed Caching
Example page: app/[tenant]/page.tsx
Use generateStaticParams to generate for a set of tenants (if the number of tenants is manageable). Otherwise, we might rely on dynamic rendering (SSR) for the entire page and then use edge caching with a short TTL? But that would be SSR for every request.
Step 4: Dynamic Parts
For parts of the page that are user-specific or change per request, we can have separate server components that fetch without caching (or with cache: 'no-store').
Step 5: API Routes
For data that is fetched by the client (if any), create API routes that are also tenant-aware (using the x-tenant-id header) and set appropriate cache control.
Example Code Structure:
code
app/
[tenant]/
layout.tsx (fetches tenant config, provides via context)
page.tsx (the main page, could be ISR or SSR)
components/
StaticPart.tsx (ISR component, uses fetch with `cache: 'force-cache'` and `revalidate`)
DynamicPart.tsx (SSR component, uses fetch with `cache: 'no-store'`)
middleware.ts
lib/
tenant.ts (tenant identification and utilities)
Example Middleware:
typescript
// middleware.ts
import { NextRequest, NextFetchEvent } from 'next/server'
export function middleware(request: NextRequest, event: NextFetchEvent) {
const tenant = identifyTenant(request) // your logic, e.g., subdomain
request.headers.set('x-tenant-id', tenant.id)
// Optionally, rewrite to include tenant in the path if needed
// const url = request.nextUrl.clone()
// url.pathname = `/${tenant.slug}${url.pathname}`
// return NextResponse.rewrite(url)
}
export const config = {
matcher: [
// Skip all internal paths (_next, api, etc.) and static files
'/((?!_next|api|favicon.ico|.*\\..*).*)',
],
}
// lib/tenant.ts
export async function getTenantConfig(tenantId: string) {
const res = await fetch(`${process.env.DATABASE_URL}/tenants/${tenantId}`, {
cache: 'force-cache',
next: { revalidate: 3600 }, // revalidate every hour
})
return res.json()
}
Example Page with ISR:
If we want to use ISR for the entire page (but note that the layout already fetched tenant config and the page might be static for the tenant):
typescript
// app/[tenant]/page.tsx
import { getTenantData } from '@/lib/tenantData'
export async function generateStaticParams() {
// Only if the number of tenants is small, otherwise we might not use ISR for the whole page.
const tenants = await getAllTenantIds() // from your DB
return tenants.map((tenant) => ({
tenant,
}))
}
export default async function Page({ params }: { params: { tenant: string } }) {
const data = await getTenantData(params.tenant)
return <div>{data.content}</div>
}
// In getTenantData, we can set:
export async function getTenantData(tenantId: string) {
const res = await fetch(`${process.env.DATABASE_URL}/tenants/${tenantId}/data`, {
next: { revalidate: 60 }, // revalidate every 60 seconds
})
return res.json()
}
But note: the layout and the page are both server components and both fetch data. The layout's data is cached for 1 hour and the page's for 60 seconds. This is acceptable.
Example Page with Streaming SSR:
If we cannot use ISR because the data changes too frequently or we don't want to generate static pages for every tenant (too many), then we don't use generateStaticParams and the page will be rendered on every request (SSR). Then we can break the page into parts:
typescript
// app/[tenant]/page.tsx
import StaticPart from './components/StaticPart'
import DynamicPart from './components/DynamicPart'
export default function Page() {
return (
<>
<StaticPart /> {/* This component uses ISR (cached at edge) */}
<DynamicPart /> {/* This component uses SSR (no cache) */}
</>
)
}
In StaticPart:
typescript
// app/[tenant]/components/StaticPart.tsx
import { getStaticData } from '@/lib/staticData'
export default async function StaticPart() {
const data = await getStaticData()
return <div>{data}</div>
}
In DynamicPart:
typescript
// app/[tenant]/components/DynamicPart.tsx
import { getDynamicData } from '@/lib/dynamicData'
export default async function DynamicPart() {
const data = await getDynamicData()
return <div>{data}</div>
}
export async function getDynamicData() {
const res = await fetch(..., {
cache: 'no-store',
})
...
}
Edge Caching Headers:
We can also set cache control headers in the response for the entire page or for specific parts. However, using the fetch cache options is the recommended way in Next.js.
Caveats:
The middleware runs on the edge and can set the tenant context. But note that the headers we set in the middleware are only available in the server components and API routes (not in client components). We can pass the tenant context via a provider as shown.
If we have a large number of tenants, generating static pages for every tenant might not be feasible. In that case, we rely on SSR for the entire page and then use edge caching with a short TTL? But note that SSR pages are not cached by default. We can use the Cache-Control header to cache the entire page at the edge for a short time (e.g., 10 seconds) if the data is not highly dynamic. However, note that Next.js does not cache SSR responses by default. We have to set the header in the response. But then we are caching the entire HTML per tenant and per request? That might be too many variations.
Another approach: use a hybrid where the static parts are cached at the edge (as separate components) and the dynamic parts are not. This is the streaming approach.
Summary:
We will:
Use middleware for tenant identification and set a header for downstream.
Use a layout that fetches tenant configuration with ISR (revalidate every hour).
For the main page:
Option A (if few tenants): use ISR with generateStaticParams for all tenants and then per-page ISR with a revalidate time.
Option B (many tenants): use SSR (no static params) and break the page into static (ISR) and dynamic (SSR) components.
The choice between Option A and Option B depends on the number of tenants and the nature of the content.
Additional Considerations:
We must ensure that the tenant context is available in API routes. We can read the x-tenant-id header in API routes.
For static assets (like images, CSS, JS) we want to cache them at the edge for a long time. Next.js does this by default.
We might want to use a custom cache for tenant configuration (like Redis) and then in the layout we can check the cache first? But the fetch with cache: 'force-cache' and next: { revalidate } will use the edge cache and the Next.js cache. It should be fine.
Conclusion:
The architecture is flexible and can be adjusted based on the number of tenants and the data volatility.
Let me know if you have any questions or need further details on a specific part.
Here's a comprehensive multi-tenant Next.js App Router architecture that balances ISR, streaming SSR, and edge caching:
Architecture Overview
mermaid
graph TB
subgraph "Edge Layer"
CDN[Edge Cache/CDN]
MW[Middleware<br/>Tenant Resolution]
end
subgraph "Next.js App Router"
ISR[ISR Pages<br/>generateStaticParams]
SSR[Streaming SSR<br/>Suspense Boundaries]
API[API Routes<br/>with Edge Caching]
EDGE[Edge Functions<br/>for Dynamic Logic]
end
subgraph "Data Layer"
DB[Primary Database]
CACHE[Redis/Memcached]
SEARCH[Search Index]
end
CDN --> MW
MW --> ISR
MW --> SSR
MW --> API
API --> CACHE
API --> DB
SSR --> DB
ISR --> CACHE
EDGE --> CACHE