Designing a multi-tenant frontend where each customer sees their own branded experience — themes, feature flags, auth methods — all from a single codebase. Subdomain vs subpath routing, white-label theming, per-tenant config, and the monolith vs micro-frontend tradeoff.
System DesignArchitectureSaaSFrontend
0. What Are We Building?
A multi-tenant frontend serves multiple customers (tenants) from a single application deployment. Each tenant lands on their own URL, sees their own brand, uses their own login flow, and gets a curated set of features — but the underlying code is shared.
Think of how Shopify stores work: acme.shopify.com looks completely different from beta.shopify.com, but they run the same software. Or Zendesk: acme.zendesk.com and beta.zendesk.com. Each tenant gets isolation, branding, and configuration without a separate deployment.
Key Insight
The defining challenge of multi-tenant frontends: the code is shared but the experience must feel custom. Every tenant is a snowflake that thinks they have their own app. Your architecture must deliver that illusion without duplicating code for every customer.
This article draws on real experience building a white-label neo-banking portal at Razorpay — serving four banks (KVB, Canara, Equitas, Axis) from a single React SPA — plus patterns from Google Workspace, Shopify, Zendesk, and Atlassian. We will cover the architecture from edge router to CSS variable, and every tradeoff along the way.
1. Requirements & Scoping
Multi-tenant systems have requirements that single-tenant apps do not. The most important one is also the hardest: tenant isolation. Tenant A must never see Tenant B's data, theme, or config — and vice versa.
Functional
Tenant identification from URL (subdomain or subpath)
Tenant isolation — strict data and config boundaries
Bundle size independent of tenant count — O(1) not O(n)
Page loads under 2s even with config fetch on first load
SEO for tenant-specific landing pages (if public)
New tenant onboarding without redeployment
Tip
Scope trick: multi-tenant is about serving N customers with one codebase. Do NOT build per-tenant databases of CSS or per-tenant branches. If you need to customize something for a tenant, put it in their config object. If the customization cannot be expressed as config, it is probably a product feature, not a tenant concern.
2. Architecture & High-Level Design
Multi-tenant frontend architecture is defined by three big RADIO decisions. Each has real tradeoffs that affect your team, your infrastructure, and your customers. Let us walk through them.
RADIO 1: Subdomain vs Subpath Tenant Routing
The very first decision: how does the system know which tenant is accessing it? Two dominant patterns exist.
Subdomain vs subpath routing — the first architectural decision in any multi-tenant system
Subdomain routing (tenant.example.com) is the choice for enterprise SaaS where each tenant expects their own URL. Shopify, Zendesk, and Atlassian all use this. The edge router reads theHost header and maps it to a tenant ID. Wildcard DNS (*.example.com) makes this manageable — you do not need a DNS record per tenant.
Subpath routing (example.com/tenant) is common when tenants are workspaces or teams within a single organization's domain. Notion, GitHub, and Slack use this. The path prefix identifies the tenant, making it trivial to set up but harder to isolate cookies and SSL.
example.ts
// ── Subdomain: read from Host header ──────────────
function identifyTenant(request: Request): string {
const host = request.headers.get("Host"); // "acme.example.com"
const subdomain = host.split(".")[0]; // "acme"
return tenantMap[subdomain] ?? "default";
}
// ── Subpath: read from path prefix ──────────────────
function identifyTenant(url: URL): string {
const segments = url.pathname.split("/").filter(Boolean);
return segments[0] ?? "default"; // first segment is tenant slug
}
Warning
Subdomain routing has a subtle gotcha: browser SameSite cookie defaults. If your auth cookie has SameSite=Lax (the browser default), it is not sent on cross-subdomain requests. Set SameSite=None; Secure for cross-subdomain cookies, or use a shared auth domain.
RADIO 2: Micro-Frontend vs Monolith
Should each tenant get its own micro-frontend deployment, or should all tenants share one monolithic app? This is less about technology and more about team topology.
example.text
┌─────────────────────────┬──────────────────────┬────────────────────────┐
│ │ Monolith │ Micro-Frontend │
│ │ (shared deploy) │ (per-tenant deploy) │
├─────────────────────────┼──────────────────────┼────────────────────────┤
│ Tenant onboarding │ Instant — config │ Requires CI/CD per │
│ │ change only │ tenant or channel │
│ Deployment risk │ One deploy affects │ Isolated — Tenant A │
│ │ all tenants │ can roll independently│
│ Code sharing │ Trivial — same │ Via packages/libs — │
│ │ node_modules │ versioning overhead │
│ Per-tenant │ Harder — must be │ Natural — each MF has │
│ customization │ config-driven │ own code │
│ Bundle size │ O(1) — shared │ O(n) — each deploy │
│ │ regardless of │ has its own bundle │
│ │ tenant count │ │
│ Team autonomy │ Shared codebase │ Full autonomy per MF │
│ Testing │ Test once │ Test per tenant │
└─────────────────────────┴──────────────────────┴────────────────────────┘
For most teams, a monolith with config-driven tenant customization is the right starting point. Micro-frontends make sense only when you have multiple teams owning different tenant verticals, or when tenants need radically different technology stacks. Razorpay's neo-banking portal used a monolith with per-tenant config — four banks, one React SPA, one team.
Key Insight
The micro-frontend vs monolith debate often misses the real point: with config-driven customization, a monolith can serve hundreds of tenants without code duplication. Micro-frontends solve team autonomy, not tenancy. If you have one team, start with a monolith.
RADIO 3: SSG per Tenant vs Dynamic Serving
Should you pre-build an SSG bundle for each tenant, or serve all tenants dynamically from one runtime? This has major implications for build time, cache efficiency, and deployment complexity.
example.text
┌─────────────────────────┬──────────────────────┬────────────────────────┐
│ │ SSG per Tenant │ Dynamic Serving │
│ │ (pre-build) │ (one runtime) │
├─────────────────────────┼──────────────────────┼────────────────────────┤
│ Build time │ O(tenants) — 100 │ O(1) — one build │
│ │ tenants = 100× cost │ │
│ Cold start │ None — static files │ First request may be │
│ │ on CDN │ slower (SSR) │
│ Freshness │ Requires rebuild │ Always up-to-date │
│ │ per change │ │
│ CDN cache efficiency │ Per-tenant cache │ Shared cache per │
│ │ partition │ page (tenant header) │
│ Per-tenant landing page │ Natural — each │ Must SSR or ISR per │
│ SEO │ tenant gets HTML │ request │
│ Deployment │ Tenants deploy │ One deploy for all │
│ │ independently │ │
└─────────────────────────┴──────────────────────┴────────────────────────┘
A hybrid approach works best: use ISR with per-tenant cache keys. The CDN caches rendered HTML keyed by Host header (or tenant ID cookie). When the cache misses, the server renders dynamically. When tenant config changes, you invalidate only that tenant's cache. This gives you the speed of static with the flexibility of dynamic — without the build-time explosion of SSG per tenant.
Multi-tenant architecture — edge router maps host to tenant, shared app shell injects tenant config, rendering layer picks SSG/dynamic per tenant, backend isolates data
Note
Shopify uses a hybrid: storefronts are rendered on demand but cached aggressively at the CDN layer. A theme change invalidates the cache for that store. The store owner gets instant updates without a rebuild, and shoppers get near-static response times. This is the sweet spot.
3. Tenant Configuration Model
Tenant configuration is the backbone of any multi-tenant system. Every tenant gets a config object that tells the frontend who they are, what they look like, and what features they can use. Getting this data model right is more important than any component architecture.
The config must be available before the first render. An API call for config adds a round trip that delays the initial paint — especially painful on slow networks, which was exactly the problem at Razorpay where many bank customers had poor connectivity.
The solution: inline the config into the HTML as a global JavaScript object. The server (or edge worker) reads the tenant from the request, fetches the config, and injects it into a <script> tag before the app bundle loads.
example.html
<!-- Injected by server/edge during HTML generation -->
<script>
window.__TENANT_CONFIG__ = {
id: "bank-kvb",
name: "Karur Vysya Bank",
brand: {
primaryColor: "#C41E3A",
logoUrl: "/logos/kvb.svg",
fontFamily: "'Public Sans', sans-serif"
},
auth: { type: "password" },
features: { enableExport: true, maxUsers: 50 }
};
</script>
<!-- App bundle loads after config is available -->
<script src="/app.js" defer></script>
On the client, the app reads window.__TENANT_CONFIG__on boot and caches it in a React context. No API call needed for the initial render. To prevent tampering by end users, the config is cached in a closure immediately on page load — no event listeners are attached, and the global is deleted after capture.
Never trust tenant config from the client for authorization decisions. The inline script is a performance optimization, not a security mechanism. Always validate tenant identity and feature access on the server side. A user could theoretically modify the config in their browser — this should only affect UI chrome, never backend permissions.
4. Interface Definition (API)
The API layer in a multi-tenant system must route requests to the correct tenant's data. This is typically done via a tenant header or by embedding the tenant ID in the URL path. All API responses should include the tenant context so the frontend can verify consistency.
Tenant-Aware Endpoints
example.text
── Tenant Config ──────────────────────────────────
GET /api/tenant/config
→ { tenant: TenantConfig }
→ Headers: X-Tenant-Id is read by server
→ Cache: private, no-cache (per-user or per-session)
── Per-Tenant APIs (data is isolated by tenant) ──
GET /api/users?page=1&size=20
→ { users: User[], pagination }
→ Tenant determined from X-Tenant-Id header
→ Never return data from another tenant
PUT /api/tenant/config/brand { primaryColor, logoUrl, ... }
→ { tenant: TenantConfig }
→ Only tenant admin can modify
── Auth Endpoints ─────────────────────────────────
GET /api/auth/login
→ Redirects to tenant-specific SSO provider
→ Determined by tenant config: auth.type
POST /api/auth/callback
→ Validates token against tenant's provider
→ Issues session cookie scoped to tenant domain
── Cross-cutting ─────────────────────────────────
GET /api/health
→ { status: "ok", tenantCount: 150 }
→ No tenant context needed
Tenant Header Pattern
The frontend sends the tenant ID with every API request via a custom header. The backend gateway validates that the header matches the authenticated user's tenant. This is simpler than embedding the tenant in the URL path and avoids path collision issues.
The tenant header pattern is simple, but it puts a lot of trust in the frontend to send the correct header. Always validate the backend: the API gateway should verify that the X-Tenant-Id matches the session's tenant. Double-checking at the infrastructure layer prevents tenant confusion attacks.
5. Tenant Isolation Strategy
Tenant isolation is the non-negotiable requirement. A configuration bug or routing mistake that leaks Tenant A's data to Tenant B is a catastrophic failure — especially in regulated industries like banking or healthcare. Isolation must be enforced at every layer.
Layers of Isolation
example.text
┌──────────────┐
│ DNS / Edge │ ← Wildcard SSL, host-based routing
├──────────────┤
│ CDN Cache │ ← Cache key includes tenant ID
├──────────────┤
│ App Runtime │ ← TenantContext, config injection
├──────────────┤
│ API Gateway │ ← Validates X-Tenant-Id against session
├──────────────┤
│ Backend │ ← Database queries filtered by tenant_id
│ Services │ Rows have tenant_id column
├──────────────┤
│ Database │ ← Row-level security (RLS) or
│ │ separate schemas per tenant
└──────────────┘
Subdomain Isolation
Subdomains provide natural isolation. Tenant A's JavaScript runs ona.example.com and cannot access cookies or localStorage set on b.example.com. The browser enforces this separation automatically. This is the strongest client-side isolation you can get without iframes.
Subpath Isolation — Shared-Nothing by Convention
Subpath isolation is weaker. All tenants share the same origin, so cookies and localStorage are shared. You must enforce separation proactively: prefix localStorage keys with the tenant ID, scope cookies to the path (Path=/tenant-a), and validate the tenant on every server-side request.
example.ts
// localStorage isolation for subpath tenants
const storage = {
get(key: string) {
const tenantId = getCurrentTenantId();
return localStorage.getItem(\`t:\\${tenantId}:\\${key}\`);
},
set(key: string, value: string) {
const tenantId = getCurrentTenantId();
localStorage.setItem(\`t:\\${tenantId}:\\${key}\`, value);
},
};
// Cookie isolation via path scoping
// Set-Cookie: session=abc; Path=/tenant-a; SameSite=Strict
// This cookie is only sent for /tenant-a/* requests
URL-Based Tenant Leaking
Subpath routing has a subtle security risk: URL-based tenant leaking. If a user copies a URL from Tenant A's session and shares it, the recipient might land on Tenant A's workspace. Mitigate this by:
Redirecting to the authenticated user's own tenant if the path tenant does not match the session tenant
Using opaque tenant IDs (UUIDs) in URLs instead of guessable slugs
Showing a clear error if a user tries to access a tenant they do not belong to
Tip
For maximum isolation, consider deploying separate browser contexts per tenant using subdomains. If your SaaS is in a regulated industry (banking, healthcare, government), subdomain routing is the safer choice. The DNS setup cost is worth the security guarantee.
6. White-Label Theming
White-label theming is where multi-tenant architecture meets the visual brand. Each tenant wants their logo, their colors, their fonts — and they want it to feel like a custom-built app. The golden tool for this is CSS custom properties (variables).
CSS Custom Properties — The Design Token Pipeline
Map every tenant config brand value to a CSS custom property. The component code never references a raw color — it uses var(--fx-primary). Changing a tenant's theme is as simple as updating their config object and flushing the CDN cache.
// Step 1: CSS uses variables everywhere
.button {
background: var(--fx-primary);
color: var(--fx-primary-foreground);
border-radius: var(--fx-radius);
font-family: var(--fx-font);
}
// Step 2: On mount, inject tenant theme into :root
function applyTheme(config: TenantConfig) {
const root = document.documentElement;
root.style.setProperty("--fx-primary", config.brand.primaryColor);
root.style.setProperty("--fx-primary-foreground", "#FFFFFF");
root.style.setProperty("--fx-bg", config.brand.backgroundColor);
root.style.setProperty("--fx-font", config.brand.fontFamily);
root.style.setProperty("--fx-radius", \`\${config.brand.borderRadius}px\`);
// Logo
const logo = document.getElementById("brand-logo") as HTMLImageElement;
if (logo) logo.src = config.brand.logoUrl;
// Favicon
const favicon = document.getElementById("favicon") as HTMLLinkElement;
if (favicon) favicon.href = config.brand.faviconUrl;
}
The Razorpay Approach — Bank-Specific Login Pages
At Razorpay, each bank had a completely different login flow. Some used customer ID + OTP, others used card number + password, some used card number + ATM PIN + OTP. The auth flows were so divergent that a single config-driven login component was impossible.
The solution: individual login components per bank, rendered via a switch on the tenant config's auth.loginFormType. Each login form was a separate chunk loaded lazily, so Tenant A never downloaded Tenant B's login code.
The key lesson from Razorpay: some tenant customizations cannot be expressed as config values. When a tenant needs a fundamentally different component (like a completely different login form), lazy-load per-tenant components. The shared code is the shell, routing, and data layer — the tenant-specific parts are loaded on demand. This keeps the base bundle small while supporting deep customization.
Design System Integration
A design system is your best friend in multi-tenant theming. By defining all visual properties as design tokens — and mapping those tokens to CSS custom properties — you guarantee that every component respects the tenant theme. Components never hardcode colors. The design system becomes the contract between the tenant config and the rendered UI.
example.ts
// Design tokens map to CSS variables
// token → CSS variable → tenant config value
const TOKENS = {
colorPrimary: "--fx-primary",
colorBg: "--fx-bg",
colorText: "--fx-fg",
colorTextMuted: "--fx-fg-muted",
colorBorder: "--fx-border",
colorSurface: "--fx-surface",
radius: "--fx-radius",
font: "--fx-font",
spacing: "--fx-spacing",
} as const;
function applyDesignTokens(config: TenantConfig) {
const root = document.documentElement;
const theme = resolveTheme(config); // adds contrast, variants, etc.
for (const [token, cssVar] of Object.entries(TOKENS)) {
root.style.setProperty(cssVar, theme[token]);
},
}
7. Routing by Tenant
Once the tenant is identified, the app needs to route requests within that tenant's context. The routing strategy differs depending on whether you use subdomains or subpaths, but the core logic is the same: ensure the tenant is known before any page component mounts.
Middleware-Based Tenant Resolution
In a Next.js or similar framework, middleware is the ideal place to resolve the tenant. It runs before the page renders, can access request headers and cookies, and can redirect or rewrite URLs before the application code executes.
example.ts
// Next.js middleware — tenant resolution at edge
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const { hostname, pathname } = request.nextUrl;
// 1. Resolve tenant from hostname (subdomain) or path
const tenantSlug = resolveTenant(hostname, pathname);
if (!tenantSlug) {
// No tenant found — show tenant selector or error
return NextResponse.rewrite(new URL("/tenant-chooser", request.url));
}
// 2. Set tenant cookie for client-side access
const response = NextResponse.next();
response.cookies.set("x-tenant-slug", tenantSlug, {
httpOnly: true,
sameSite: "strict",
secure: true,
path: "/",
});
// 3. For subpath routing, strip /:tenant from path
// so the app routes normally
if (isSubpathRouting) {
const newPath = pathname.replace(\`/\\${tenantSlug}\`, "") || "/";
request.nextUrl.pathname = newPath;
return NextResponse.rewrite(request.nextUrl);
}
return response;
}
function resolveTenant(hostname: string, pathname: string): string | null {
// Try subdomain first
const parts = hostname.split(".");
if (parts.length >= 3 && parts[0] !== "www") {
return tenantDomainMap[parts[0]] ?? null;
}
// Fall back to path prefix
const firstSegment = pathname.split("/")[1];
return tenantPathMap[firstSegment] ?? null;
}
export const config = {
matcher: ["/((?!api|_next|static|favicon.ico).*)"],
};
Client-Side Tenant Context
Once the middleware has resolved the tenant, the client-side app needs to consume it. The tenant cookie set by middleware is available to the browser, but for the initial page load, the inline config script is faster. The React context bridges the two.
example.ts
// Root layout — wraps entire app with tenant context
function RootLayout({ children }: { children: React.ReactNode }) {
// Read config from inline script
const config = useMemo(() => window.__TENANT_CONFIG__, []);
return (
<TenantContext.Provider value={config}>
<ThemeInjector config={config} />
{children}
</TenantContext.Provider>
);
}
// ThemeInjector applies CSS custom properties on mount
function ThemeInjector({ config }: { config: TenantConfig }) {
useEffect(() => { applyTheme(config); }, [config]);
return null;
}
// In any component
function Header() {
const tenant = useTenant();
return (
<header>
<img src={tenant.brand.logoUrl} alt={tenant.name} />
<h1>{tenant.name} Dashboard</h1>
</header>
);
}
Subpath Routing — Nested Layouts
For subpath routing, you need nested layouts. The tenant layout wraps all routes within a tenant's path prefix. This ensures the tenant context is available for all pages under that tenant's namespace.
For subpath routing, be careful with your 404 page. A typo likeexample.com/acmee/dashboard should show a tenant-specific 404, not the default platform 404. Many multi-tenant apps miss this — the error page itself needs to be tenant-aware.
8. Performance Optimization
Multi-tenant frontends have unique performance challenges. The most important one: the config fetch must not block the initial render. Every millisecond the user stares at a blank screen waiting for config is a millisecond they might churn.
Technique 1: Config Preloading (The Inline Script)
As described in Section 3, the single biggest performance win is inlining the tenant config into the HTML. This eliminates the network round trip for config and lets the app render immediately with the correct theme and features.
example.text
// Timing comparison:
// ❌ Without inline config:
// Load HTML → load JS → fetch /api/tenant/config (RTT) → render
// Total: HTML + JS + 1 round trip
//
// ✅ With inline config:
// Load HTML (has config) → load JS → render
// Total: HTML + JS (no additional round trip)
// On slower networks (3G, emerging markets):
// Without: ~3-4s to first meaningful paint
// With: ~1.5-2s to first meaningful paint
Technique 2: Per-Tenant CDN Cache Keys
When using ISR or SSR, the CDN cache key must include the tenant identifier. Otherwise, Tenant A gets Tenant B's cached page. Configure your CDN to vary the cache by the Host header (for subdomain) or the tenant path segment (for subpath).
example.ts
// CDN cache configuration (Cloudflare Workers example)
export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url);
const tenant = identifyTenant(request);
// Cache key: include tenant + path
const cacheKey = new Request(
\`https://\\${tenant}\${url.pathname}\${url.search}\`,
request,
);
const cache = caches.default;
let response = await cache.match(cacheKey);
if (!response) {
response = await fetch(request);
if (response.ok) {
response = new Response(response.body, response);
response.headers.set("Cache-Control", "public, s-maxage=300");
// Store with tenant-scoped key
await cache.put(cacheKey, response.clone());
}
}
return response;
},
};
Technique 3: Code Splitting by Tenant Feature
Do not load code for features that the current tenant does not use. If Tenant A has enableExport = false, the export module should never appear in Tenant A's bundle. Use dynamic imports guarded by feature flags.
example.ts
// Feature-flagged code splitting
function Sidebar() {
const tenant = useTenant();
const [AnalyticsPanel, setAnalyticsPanel] = useState<ComponentType>();
useEffect(() => {
if (tenant.features.enableAnalytics) {
import("./panels/AnalyticsPanel").then((m) =>
setAnalyticsPanel(() => m.default)
);
}
}, [tenant.features.enableAnalytics]);
return (
<aside>
<CommonPanel />
{tenant.features.enableExport && <ExportButton />}
{AnalyticsPanel && <AnalyticsPanel />}
</aside>
);
}
// Even better: preload likely chunks based on tenant profile
function preloadTenantChunks(config: TenantConfig) {
if (config.features.enableAnalytics) {
const link = document.createElement("link");
link.rel = "preload";
link.as = "script";
link.href = "/chunks/analytics-panel.js";
document.head.appendChild(link);
}
}
Technique 4: Tenant-Aware ISR
For public-facing tenant pages (like a Shopify storefront), ISR with per-tenant revalidation is optimal. A product page for Tenant A is a different page from the same product for Tenant B. The cache key must include the tenant, and revalidation must invalidate only that tenant's cache.
example.ts
// Tenant-aware ISR with on-demand revalidation
export const revalidate = 300; // 5 min default
async function TenantPage({ params }: { params: { tenant: string } }) {
const config = await getTenantConfig(params.tenant);
const data = await fetchTenantData(config.id);
return (
<TenantLayout config={config}>
<PageContent data={data} />
</TenantLayout>
);
}
// On-demand revalidation (when tenant config changes)
// POST /api/revalidate?tenant=acme
export async function revalidateTenant(tenantSlug: string) {
await revalidatePath(\`/\\${tenantSlug}\`);
// Also purge CDN cache for this tenant
await purgeCDNCache(\`*\\${tenantSlug}*\`);
}
Key Insight
The performance hierarchy for multi-tenant: (1) Inline config is worth more than all other optimizations combined. It eliminates the round trip that blocks the first render. (2) Per-tenant CDN cache keys prevent cross-tenant cache poisoning. (3) Feature-flagged code splitting keeps bundles lean. Do them in this order.
9. Security Considerations
Security in multi-tenant systems is about one thing: tenant isolation. A cross-tenant data leak is not just a bug — it is a compliance violation (GDPR, SOC2, HIPAA, PCI-DSS) that can destroy customer trust and result in massive fines.
Config Tampering Prevention
The inline config script is a performance optimization, but it creates a security surface: a user could modify __TENANT_CONFIG__before the app reads it. Mitigate this by:
Capturing and deleting the global immediately in a synchronous script
Never storing authorization-relevant data in the config (only UI chrome and feature flags)
Validating all feature flag checks on the backend, not just the frontend
Tenant ID Spoofing
The X-Tenant-Id header is set by the frontend. A malicious user could change it to access another tenant's data. The backend must validate that the header matches the authenticated user's tenant. The API gateway or middleware is the right layer for this check.
example.ts
// Backend tenant validation (Node.js example)
function requireTenantAccess(req: Request, res: Response, next: NextFunction) {
const headerTenant = req.headers["x-tenant-id"];
const userTenant = req.session.tenantId;
if (!headerTenant || headerTenant !== userTenant) {
return res.status(403).json({
error: "Tenant mismatch",
code: "CROSS_TENANT_ACCESS_DENIED",
});
}
// Also check that the user has access to this tenant
if (!req.user.tenants.includes(headerTenant)) {
return res.status(403).json({
error: "User does not belong to this tenant",
code: "TENANT_FORBIDDEN",
});
}
next();
}
// Apply to all API routes
app.use("/api", requireTenantAccess);
Content Security Policy
Multi-tenant apps often allow tenants to upload their own logo images and custom CSS. This opens XSS vectors. Enforce a strict CSP that only allows loading resources from tenant-specific allowed origins.
example.ts
// Dynamic CSP per tenant
function buildCSP(tenant: TenantConfig): string {
const logoOrigin = new URL(tenant.brand.logoUrl).origin;
return [
"default-src 'self'",
"script-src 'self' 'nonce-abc123'",
"style-src 'self' 'unsafe-inline'", // needed for CSS vars
\`img-src 'self' \\${logoOrigin} data:\`,
"connect-src 'self' " + tenant.api.baseUrl,
"frame-ancestors 'none'", // prevent clickjacking
].join("; ");
}
// Set CSP header in middleware
response.headers.set("Content-Security-Policy", buildCSP(tenant));
Cross-Tenant CSRF
If you use subpath routing (same origin for all tenants), a CSRF attack from one tenant's page could target another tenant's API. Mitigate by:
Using per-tenant CSRF tokens tied to the tenant ID
Setting SameSite=Strict on session cookies
Validating the Origin header against the expected tenant domain
Warning
The same-origin problem with subpath routing is the biggest security argument for subdomains. If Tenant A injects a script that reads localStorage, they get all tenants' data (since localStorage is per-origin). With subdomains, each tenant's data is isolated by the browser. For high-security applications, subdomains are non-negotiable.
10. Key Takeaways
Building a multi-tenant frontend is as much about organizational decisions as technical ones. Here is what matters most.
Start with config-driven monolith
A single codebase with per-tenant config serves 99% of teams. Add micro-frontends only when team autonomy demands it.
Inline config eliminates the biggest perf bottleneck
The round trip for tenant config data is the single biggest performance tax. Eliminate it with server-injected inline scripts.
CSS custom properties are your theming superpower
Design tokens expressed as CSS vars let you theme any component without touching its implementation. The design system becomes the theming contract.
Subdomain routing for isolation, subpath for simplicity
Subdomains give you browser-enforced isolation at the cost of DNS setup. Subpaths are simpler but require manual isolation at every layer.
Every tenant customization must be a config value or a lazy chunk
If it cannot be a config value, it must be a lazy-loaded component. Never build per-tenant branches or forks — you will regret the maintenance burden.
Validate tenant identity at every layer
Middleware validates the host. The API gateway validates the header. The backend validates the session. Every layer must check the tenant. Trust no single layer.
Key Insight
The companies that do multi-tenant well — Shopify, Zendesk, Atlassian, Salesforce — all follow the same pattern: one codebase, one deployment, config-driven customization, and aggressive caching at the edge. The tenants think they have their own app. That is the illusion you are building. The config object is the illusion engine.
Build your config model first. Everything else — theming, routing, feature flags, auth — follows from it. A well-designed tenant config lets you onboard a new customer by adding a JSON blob and a DNS record. No code changes. No deployment. That is the goal.