• Architecture

Architecting a Multi-Tenant Next.js Platform with Headless WordPress & WPGraphQL

Ramona Colon

Architecting Multi-Tenant Next.js Platforms with Headless WordPress & WPGraphQL

Modern engineering organizations frequently face a scaling inflection point: as a portfolio grows from a single flagship website into multiple brand experiences, microsites, and specialized subdomains, maintaining separate repositories and deployment pipelines quickly becomes unsustainable. Dependency upgrades drift apart, security patches must be replicated across half a dozen codebases, and editorial teams are forced to jump between disconnected CMS logins.

By pairing a multi-tenant Next.js App Router architecture with a WordPress Multisite network exposed via WPGraphQL, we can serve completely distinct brands, layouts, and subdomains from a single hardened TypeScript codebase—while giving content editors a unified, familiar publishing workflow.

1. Hostname-Driven Middleware & Subdomain Routing

The foundation of a multi-tenant Next.js platform is deterministic request routing. Rather than hardcoding brand logic inside page components, incoming requests are intercepted at the middleware layer (src/proxy.ts), where the Host header is normalized and mapped to a tenant configuration or specialized subdomain route.

This approach allows a single deployment to simultaneously handle:

  • Primary Brand Domains (e.g., ramonacolon.dev, mywebstaging.online) rewritten transparently to internal dynamic route segments (/sites/[site]/...).
  • Dedicated Content Subdomains (e.g., blog.ramonacolon.dev) that map clean root-level article slugs (/[slug]) directly to the tenant’s blog engine without duplicating URL prefixes.
  • Isolated Editorial Dashboards (e.g., dashboard.ramonacolon.dev) that proxy authenticated administrative traffic to the underlying WordPress Multisite control plane while keeping public domains strictly read-only.
// Example: Hostname normalization and subdomain rewrite in Next.js Middleware
export default function middleware(request: NextRequest) {
  const url = request.nextUrl;
  const hostname = normalizeDomain(request.headers.get("host"));

  // Route dedicated blog subdomain cleanly to the tenant's blog tree
  if (hostname === "blog.ramonacolon.dev") {
    const blogPath = url.pathname === "/" ? "/blog" : `/blog${url.pathname}`;
    return NextResponse.rewrite(new URL(`/sites/ramonacolon.dev${blogPath}`, request.url));
  }

  const resolvedTenant = hasTenant(hostname) ? hostname : DEFAULT_TENANT_DOMAIN;
  return NextResponse.rewrite(new URL(`/sites/${resolvedTenant}${url.pathname}`, request.url));
}

2. Mapping WordPress Multisite Subsites to Tenant Schemas

On the content management side, WordPress Multisite solves the exact same operational problem as multi-tenant Next.js. Instead of provisioning separate PHP workers and MySQL databases for every brand, a single WordPress network manages multiple isolated subsites (each identified by a unique blog_id).

Through a shared Must-Use Plugin (mu-plugins/headless-cms-schema.php), every subsite automatically inherits a standardized content contract registered with WPGraphQL:

  1. Page Copy & Hero Sections: Structured fields for headlines, role tickers, and parallax story blocks so marketing and leadership teams can iterate on messaging without code changes.
  2. Portfolio & Case Study Custom Post Types (project): Custom GraphQL fields for live project URLs, tech stack tags, and curated display ordering.
  3. Editorial Articles (post): Full long-form articles with categories, author metadata, excerpts, and featured media.

Architectural Tip: Always design your data-fetching layer with independent per-feature fallbacks. In our service layer (resolveTenantWithWp), page copy, portfolio items, and blog posts are fetched concurrently via Promise.all(). If a new tenant has not yet populated a custom post type in WordPress, only that section falls back to static TypeScript configuration—never taking down the rest of the page.

3. Defense-in-Depth HTML Sanitization & Zero-Client Overhead

A common pitfall in headless CMS implementations is piping raw HTML from GraphQL directly into dangerouslySetInnerHTML. Even when you trust your editorial team, a compromised contributor account, a vulnerable third-party WordPress plugin, or a carelessly pasted embed snippet can introduce stored Cross-Site Scripting (XSS).

To eliminate this vector without bloating the browser bundle:

  • All WordPress HTML is passed through a strict server-only allow-list sanitizer (sanitize-html) before it ever reaches a React component.
  • Disallowed tags (<script>, <iframe>, <object>, inline event handlers) and unsafe URI schemes (javascript:, data: on links) are stripped on the server.
  • External links with target="_blank" are automatically transformed to include rel="noopener noreferrer", and content images receive loading="lazy" and decoding="async" attributes automatically.
  • We wrap single-post lookups in React’s per-request cache() helper so that generateMetadata() and the page component share the exact same sanitized payload within a single render pass.

4. Sub-Second Publishing with Tag-Based On-Demand Revalidation

Static Site Generation (SSG) delivers unbeatable Time to First Byte (TTFB), but traditional static builds force editors to wait minutes for a CI/CD pipeline to rebuild the entire site after fixing a typo. Using Next.js cache tags, we tag every GraphQL request with both a global wp tag and a tenant-scoped tag (e.g., wp:tenant:ramona).

When an editor—or an automated AI publishing pipeline—publishes or updates a post in WordPress, a lightweight save_post hook dispatches a signed webhook to POST /api/revalidate:

// Constant-time secret verification and immediate cache tag expiration
const a = createHash("sha256").update(providedSecret).digest();
const b = createHash("sha256").update(expectedSecret).digest();
if (!timingSafeEqual(a, b)) {
  return NextResponse.json({ error: "Unauthorized." }, { status: 401 });
}

revalidateTag(getTenantCacheTag(tenantId), { expire: 0 });

5. Architectural Comparison: Siloed Repos vs. Multi-Tenant Headless

Dimension Siloed Single-Brand Repos Multi-Tenant Next.js + WP Multisite
Onboarding a New Brand Days (clone repo, provision CMS, configure CI/CD) Minutes (add tenant config entry + WP subsite)
Security & Dependency Patching Multiply effort by N repositories Single PR updates all tenants simultaneously
Editorial Publish Latency Full site rebuild (2–10 minutes) Instant via revalidateTag (< 200ms)
Server Memory Footprint N separate Node.js processes 1 shared Next.js process + 1 headless PHP worker

By treating multi-tenancy as a first-class architectural primitive across both the frontend routing layer and the headless CMS schema, small engineering teams can deliver enterprise-grade reliability, rapid brand experimentation, and sub-second content velocity.