Skip to content
SaaS Engineering10 min read

Multi-Tenant SaaS Architecture: Next.js App Router, Subdomains, and PostgreSQL RLS

Engineering blueprint for building high-compliance B2B SaaS. Implement wildcard subdomain routing, tenant isolation, and bulletproof PostgreSQL Row-Level Security.

E
By Elvantro Engineering Team
Updated
Multi-Tenant SaaS Architecture: Next.js App Router, Subdomains, and PostgreSQL RLS

Why Multi-Tenancy Architecture Dictates SaaS Valuations and Security

When architecting a B2B SaaS application, data isolation is non-negotiable. Whether serving seed-stage startups or enterprise companies with strict SOC2 Type II and GDPR requirements, an accidental cross-tenant data leak is catastrophic.

Early-stage engineering teams often choose between three fundamental multi-tenancy models:

  1. Database-per-tenant: Total isolation, but nightmare DevOps overhead and exorbitant operational costs as you scale to thousands of customers.
  2. Schema-per-tenant: Clean logical boundaries in PostgreSQL, but running migrations across 2,000 separate schemas during a production deployment frequently locks tables and fails.
  3. Shared-Database, Shared-Schema with Row-Level Security (RLS): The modern gold standard. Every record contains a tenant_id or organization_id, and PostgreSQL itself guarantees data segregation at the kernel level.

In this guide, we break down how to architect a production multi-tenant SaaS using Next.js App Router, edge middleware, and PostgreSQL RLS.

1. Dynamic Wildcard Subdomain Routing with Next.js Middleware

In an enterprise B2B SaaS, each customer expects their own workspace URL (acme.yourproduct.com). Using Next.js edge middleware, you can rewrite wildcard subdomains to internal dynamic routes without client-side redirects:

typescriptCode Architecture
// middleware.ts
import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: ["/((?!api/|_next/|_static/|[\\w-]+\\.\\w+).*)"],
};

export default async function middleware(req: NextRequest) {
  const url = req.nextUrl;
  const hostname = req.headers.get("host") || "";

  // Define allowed root domains
  const currentHost = hostname.replace(/:\d+$/, ""); // Remove port in dev
  const rootDomain = process.env.NEXT_PUBLIC_ROOT_DOMAIN || "yourproduct.com";

  // Check if currentHost is a custom subdomain
  const isSubdomain = currentHost.endsWith(`.${rootDomain}`) && currentHost !== `www.${rootDomain}`;
  const subdomain = isSubdomain ? currentHost.replace(`.${rootDomain}`, "") : null;

  if (subdomain) {
    // Rewrite path to /_tenants/[subdomain]/...
    return NextResponse.rewrite(new URL(`/_tenants/${subdomain}${url.pathname}`, req.url));
  }

  // Fallback to standard marketing/public routes
  return NextResponse.next();
}

With this middleware, visiting acme.yourproduct.com/dashboard transparently renders src/app/_tenants/[subdomain]/dashboard/page.tsx on the server.

2. Bulletproof PostgreSQL Row-Level Security (RLS)

Relying on application-level filtering (where: { tenant_id: currentTenant }) is dangerous. A single missed filter in a developer's query exposes another tenant's confidential records.

Instead, enforce tenant isolation at the database layer using PostgreSQL RLS:

sqlCode Architecture
-- 1. Enable RLS on the table
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

-- 2. Create the policy checking the session's active tenant
CREATE POLICY tenant_isolation_policy ON documents
FOR ALL
USING (
  tenant_id = (current_setting('app.current_tenant_id', true))::uuid
);

When executing queries from Next.js server actions or API routes, set the tenant context in a localized database transaction:

sqlCode Architecture
BEGIN;
SET LOCAL app.current_tenant_id = 'c4b18f4a-9e12-4c6e-9311-5369bb93e1b4';
SELECT * FROM documents; -- Automatically filtered to only this tenant's rows!
COMMIT;

Even if a rogue developer writes SELECT * FROM documents;, PostgreSQL guarantees that zero rows from competing companies are returned.

3. Automated Workspace Onboarding Flow

To convert prospective signups into retained customers, workspace provisioning must be completely frictionless:

  1. User enters company name (Acme Corp).
  2. Slugify name into subdomain (acme) and verify uniqueness in PostgreSQL.
  3. Create organization record and assign the user as ROLE_OWNER.
  4. Initialize default project templates, notification settings, and Stripe customer IDs in a single atomic database transaction.
  5. Redirect user to their new branded workspace: acme.yourproduct.com/onboarding.

4. Compliance & Enterprise Readiness Checklist

  • Strict Audit Logs: Maintain an immutable audit_events table logging every team member invite, role change, and document deletion.
  • Role-Based Access Control (RBAC): Support distinct roles (Owner, Admin, Member, Viewer) with granular permission checks.
  • Single Sign-On (SAML / SSO): Allow enterprise tenants to authenticate through Okta, Google Workspace, or Microsoft Azure AD.
  • Tenant Export & Data Purging: Implement programmatic one-click GDPR data exports and soft-deletion cascades.
Topics:#SaaS#Next.js App Router#Multi-Tenancy#PostgreSQL RLS#Software Architecture

Continue Reading

Recommended Engineering Deep Dives