Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › App Router

Multi-Tenancy in Next.js 15: A Production SaaS Architecture

By Freedom251 Team · · 11 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

For most SaaS products, the practical multi-tenant pattern in Next.js 15 is one App Router deployment that serves many subdomains and custom domains. Resolve the incoming host in middleware.ts, map it to a tenant record, and internally rewrite the request to a tenant-aware route. Keep that tenant identity in trusted server context, then enforce membership and role checks in a server-only data layer and every mutation. For storage, choose shared PostgreSQL with Row-Level Security (RLS) when operational simplicity matters, or a database per tenant when contractual, regional, backup, or blast-radius requirements justify the extra operations. Routing identifies a tenant; authorization and database guards are what actually isolate it.

What is the recommended multi-tenant pattern in Next.js 15?

Use a single Next.js 15 App Router deployment, a tenant registry, host-based resolution in middleware, and server-side authorization on every data access. A request for acme.example.com/dashboard is resolved to the tenant record for Acme and rewritten internally to a route such as /__tenants/acme-id/dashboard. The browser keeps its original URL, while your application receives a stable tenant identifier for page rendering, queries, caching, jobs, and logs.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This design avoids a separate deployment for every customer while supporting tenant subdomains, verified custom domains, wildcard DNS, automatic TLS, and preview environments. It also keeps routing separate from security: a host can suggest which tenant the user intends to visit, but only an authenticated membership check can decide whether that user may read or change tenant data.

The request lifecycle

  1. Read and normalize the request hostname, including removing a development port.
  2. Resolve an exact custom domain or subdomain to one active tenant record.
  3. Reject unknown, suspended, or reserved hosts before application code runs.
  4. Rewrite the public path to an internal tenant route.
  5. In the server data layer, verify the signed-in user’s membership and role for that tenant.
  6. Apply the same tenant scope to database queries, cache keys, background jobs, webhooks, and object-storage paths.

The Next.js documentation describes middleware as code that runs before route completion and can modify the response through rewrites, redirects, headers, or a direct response. In Next.js 15 the file is middleware.ts. Edge is the default runtime; Node.js middleware is stable starting with Next.js 15.5.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How do I resolve a tenant from a subdomain or custom domain?

Maintain a registry that treats domains as data, not as code. Each tenant should have a stable internal ID, a URL-safe slug, a status, a list of allowed domains, and configuration such as branding or feature flags.

Tenant registry fields

  • id: an immutable identifier used in foreign keys and internal routes.
  • slug: the subdomain value, subject to uniqueness and reserved-name checks.
  • status: for example, provisioning, active, suspended, or deleted.
  • domains: normalized custom hostnames mapped to exactly one tenant.
  • configuration: tenant-specific settings that are safe to load on the server.

A Redis-backed registry commonly stores subdomain records under a key pattern such as subdomain:{name}. A relational registry works just as well; the important property is a single authoritative mapping that can be checked on every request and updated during domain changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Normalize and validate the host

Use the framework URL hostname where available, or parse the Host header on the server. Lowercase the name, remove a development port, and handle trailing dots consistently. Reserve the platform root domain and administrative hosts such as admin, api, and www. Never let a query parameter such as ?tenantId=... select the tenant.

Resolve exact custom-domain matches before subdomains. A request to customer.example.com should not accidentally match a custom-domain record for another customer, and an unrecognized host should receive a controlled 404 or redirect rather than falling through to an arbitrary tenant.

Illustrative middleware shape

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(request: NextRequest) {
  const host = request.nextUrl.hostname.toLowerCase()
  const tenant = await resolveTenantByHost(host)

  if (!tenant || tenant.status !== 'active') {
    return new NextResponse('Tenant not found', { status: 404 })
  }

  const url = request.nextUrl.clone()
  url.pathname = `/__tenants/${tenant.id}${url.pathname}`

  const response = NextResponse.rewrite(url)
  response.headers.set('x-resolved-tenant', tenant.id)
  return response
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}

The header in this example is useful for internal tracing, but it is not a security boundary. Do not trust a client-supplied copy of that header. The server data layer should derive the tenant from trusted request context and verify it against the authenticated session and the route’s resolved tenant.

Where should tenant authorization happen?

Authorization belongs in a server-only Data Access Layer (DAL), with a second check inside every Server Action or other mutation endpoint. Middleware can perform an early redirect or rewrite, but it is too early and too lightweight to be your only authorization layer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authentication versus authorization

Authentication answers “who is this user?” Authorization answers “may this user perform this operation for this tenant?” A user can be signed in and still have no membership in the tenant identified by the host, or have a role that permits viewing but not deleting data.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

For each DAL function, accept the resolved tenant context and the requested operation, load the current session on the server, and check membership and role before querying. Return a minimal data-transfer object rather than exposing an entire ORM record. This reduces accidental leakage of internal fields and makes cache behavior easier to reason about.

Server Actions are public endpoints

Every Server Action is reachable through an HTTP request and must authorize itself. Do not assume that because a button is rendered only for an administrator, the action can skip its role check. Re-check the tenant, user, and required permission immediately before the mutation, and make the operation idempotent where retries are possible.

Authentication systems that support organizations can synchronize an organization with the resolved domain and apply organization roles. That integration can simplify sign-in and role management, but it does not replace the DAL check or a database-level guard.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which database isolation model should I choose?

There are two defensible defaults: shared PostgreSQL tables with tenant columns and RLS, or a separate database for each tenant. Choose based on isolation, operations, and regulatory requirements rather than on routing convenience.

Decision axis Shared database with tenant columns and RLS Separate database per tenant
Isolation strength Strong when every tenant-owned table has a correct policy and tenant context is set for every transaction. Stronger blast-radius separation because data and credentials are physically separated.
Operational cost One cluster, one connection strategy, and centralized monitoring. Provisioning, credentials, connection limits, monitoring, and upgrades multiply with tenant count.
Migration work One schema migration can cover all tenants, with careful rollout for large tables. Every tenant database must be migrated, retried, and reported independently.
Backup and restore Backups usually cover a broad set of tenants; restoring one tenant requires a selective procedure. Tenant-specific backup, restore, and retention policies are straightforward.
Noisy neighbors Queries and maintenance can compete for shared resources. Resource and failure impact can be bounded per database, subject to shared infrastructure.
Regional placement Tenants generally follow the placement of the shared database. Tenants can be placed in different regions when the application supports that topology.
Failure modes A missing tenant filter or RLS bypass can expose multiple tenants at once. Connection-routing and provisioning errors can send a request to the wrong database.

Shared PostgreSQL with RLS

Add a non-null tenant_id to every tenant-owned table and index it with the access patterns your application uses. Before running a transaction, set a transaction-scoped tenant value. Policies then compare each row’s tenant_id with that value.

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_invoices ON invoices
  USING (tenant_id = current_setting('app.tenant_id')::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

This SQL is a shape, not a drop-in production configuration. Validate transaction boundaries, connection pooling, migrations, privileged roles, and any administrative jobs that may bypass RLS. An ORM extension example can demonstrate the technique, but it should not be treated as proof that a production connection pool or transaction setup is safe.

Separate database per tenant

A database-per-tenant model is appropriate when contracts require hard isolation, tenant-specific backups, regional placement, independent scaling, or a tightly controlled blast radius. Your application still needs a registry that maps tenant IDs to database connection details, and it needs a safe provisioning and migration controller. Keep credentials server-only and prevent a request from choosing an arbitrary connection string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

How do domains, DNS, and deployment work?

One deployment can serve tenant1.example.com and verified custom domains. A wildcard DNS record routes subdomains to the platform, while automatic TLS and CDN delivery handle the edge connection. The same model can support preview deployments, but preview hostnames must be resolved and authorized like production hosts.

Production domain checklist

  • Create a wildcard DNS record for the tenant subdomain pattern.
  • Keep the root domain available for a marketing or landing page.
  • Reserve administrative hosts and exclude them from tenant matching.
  • Verify ownership before attaching a custom domain to a tenant.
  • Store the normalized domain and its tenant ID in the registry.
  • Wait for certificate and DNS validation before marking the domain active.

For local development, a host such as tenant-name.localhost:3000 exercises the same resolver. Strip the port before lookup, and make sure your matcher does not skip the request merely because it is running on localhost.

What should tenant provisioning and suspension do?

Provisioning should be an explicit workflow, not a side effect of the first page request. Do not allow traffic until the tenant record, domain, configuration, and data safeguards are ready.

  1. Reserve and validate the requested slug, rejecting platform and administrative names.
  2. Create the tenant record in a provisioning state.
  3. Attach a custom domain only after ownership or DNS verification succeeds.
  4. Initialize configuration, roles, default records, and database scope.
  5. Run a health check that exercises tenant resolution and an authorized query.
  6. Change the status to active and begin accepting traffic.

Suspension should stop new authorized work without deleting evidence needed for support or auditing. A deleted tenant needs an explicit retention and backup policy, plus a process for removing domain mappings, queued jobs, webhook subscriptions, and object-storage paths.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do caches, jobs, webhooks, and files stay isolated?

Carry the tenant ID beyond the page route. Every cache key, background job payload, webhook signature context, and object-storage path should include a stable tenant identifier.

Cache design

A key such as dashboard:tenant-id:user-id prevents one tenant’s response from being reused for another. Include tenant identity in invalidation paths as well as in reads, and cache only data that is safe to share globally. Be especially careful with static generation, request memoization, and CDN responses for custom domains.

Background work

Queue messages should contain the tenant ID, an internal actor or system identity, and the intended operation. A worker must load the tenant context before querying and should reject a message whose tenant is suspended or whose authorization assumptions no longer hold. Retries must preserve that context rather than relying on a process-global variable.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Webhooks and object storage

Verify webhook signatures, map the event to a tenant from your own registry, and avoid accepting a tenant ID supplied only in the event body. Use storage prefixes such as tenants/{tenantId}/files/..., enforce authorization when generating download URLs, and test that changing a custom domain cannot expose another tenant’s files.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How should I test a Next.js 15 multi-tenant system?

Test isolation as a failure property, not just as a successful login flow. Use at least two tenants with overlapping user accounts, roles, records, and domains.

  • Request an unknown, suspended, and reserved host and verify the expected status.
  • Try a valid user session against a tenant where the user has no membership.
  • Attempt cross-tenant reads, writes, exports, and deletes by changing paths and request bodies.
  • Exercise custom-domain changes, certificate delays, and preview deployment hostnames.
  • Verify RLS policies with pooled connections, transaction retries, and privileged maintenance jobs.
  • Inspect generated file URLs, cache hits, queue retries, and webhook handling for tenant context.
  • Confirm logs include tenant ID, resolved host, request ID, authorization result, and database-policy failures without secrets.

Observability should make a bad resolution obvious: record the host that was received, the tenant that was resolved, and the authorization decision. Never log session tokens, database credentials, or private file URLs merely to improve tracing.

What are the most common implementation mistakes?

Trusting a client tenant ID

A hidden form field, cookie, or query parameter can be changed by the caller. Derive tenant identity from the verified host mapping and server request context, then compare it with the user’s membership.

Doing authorization only in middleware

Middleware can be bypassed by another endpoint, a Server Action, a job, or a direct data-layer call. Keep the authoritative check in the DAL and in each mutation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Forgetting non-page data

Teams often scope page queries correctly but miss exports, image URLs, search indexes, cache entries, or queue consumers. Treat every data path as tenant-owned until you have proved it is global.

Using an imprecise matcher

Running tenant lookup for framework internals and static assets wastes latency and can create surprising rewrites. Exclude paths such as _next/static, _next/image, and the favicon, then add explicit tests when new public routes are introduced.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Assuming RLS is automatically safe

RLS depends on the policy, the role used by the connection, and the transaction-scoped tenant value. A pool that reuses a connection with stale session state, or an administrative role that bypasses policies, can defeat an otherwise correct-looking design.

What does a sensible architecture look like?

Keep the layers narrow: middleware resolves a host and rewrites; a server-only context carries the tenant ID; the DAL authenticates and authorizes; the database enforces scope with RLS or a tenant-specific connection; and every asynchronous or cached subsystem repeats the tenant boundary. This arrangement lets one Next.js 15 deployment serve many customers without pretending that URL routing alone provides isolation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can one user belong to several tenants in the same Next.js session?

Yes. Store memberships separately from the user identity and select the active tenant from the verified host or an explicit, authorized switch operation. When the host changes, recompute the membership and role instead of carrying the previous tenant through a cookie.

How should tenant-aware analytics avoid leaking customer data?

Emit tenant ID as a controlled, server-derived dimension and restrict dashboards by the viewer’s membership. Do not place email addresses, raw record identifiers, or secrets in URLs or client-side analytics events unless the data policy explicitly permits it.

What happens when a customer changes its subdomain?

Treat the old slug as a reserved alias or redirect only after the new mapping is active, and invalidate caches for both hostnames. Keep the immutable tenant ID unchanged so database rows, jobs, and audit history do not need to be rewritten.

Can I migrate from shared tables to separate databases later?

Design every repository method around a tenant context rather than a global database handle. That abstraction lets you copy one tenant’s rows, verify counts and checksums, switch its registry entry, and roll back without changing route resolution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

App Routercustom domainsMulti-TenancyNext.js 15PostgreSQL RLSSaaS architecturetenant isolation

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.