What you'll learn: By the end of this lesson you will be able to choose how a request reaches a tenant (subdomain, path, custom domain), resolve the tenant once and treat it as a selector rather than as proof, scope cookies and browser storage to it, key client and CDN caches by tenant so one customer never sees another's page, layer per-tenant configuration (theme tokens, features, copy) over one build, and handle a user who belongs to several tenants.
Think of a serviced office building. Every company gets its own floor, door sign, colour scheme and key cards, but the lifts, wiring and cleaning crew are shared. The danger is never the sign on the door. It is a shared lift that opens on the wrong floor, or a cleaner who carries one company's papers into another's office. A multi-tenant UI is that building: one deployed front end, many customers, and the same rule everywhere: shared machinery must remember whose floor it is on.
The running example is the seller dashboard of a grocery marketplace (a front end in the spirit of the ShopStream project used in this course): chains such as "Acme Grocers" and "Bravo Mart" each get a branded dashboard with their own orders, enabled features and sign-in provider. The names, hosts and numbers are illustrative.
The core idea
- Resolve the tenant once, early, and carry it explicitly. Every request, cache key and storage key then names it. A tenant that is only implied by "whatever the page was last showing" will leak.
- A tenant identifier from the client is a selector, not proof. OWASP's Multi-Tenant Security Cheat Sheet says to treat client-supplied tenant identifiers as selectors only, and to bind tenant context to a server-verified identity and current membership. The UI can pick which tenant to ask about; the server decides whether you may.
- Variation is configuration over one build. Colours, logos, features and copy come from data keyed by tenant, not from a fork per customer.
How a request finds its tenant
There are three common shapes, each with different browser consequences.
| Shape | Example | Browser isolation | Typical cost |
|---|---|---|---|
| Subdomain | acme.shop.example |
Separate origin per tenant | Wildcard certificate and DNS |
| Path | shop.example/acme/orders |
One origin for all tenants | Easiest to host, weakest browser isolation |
| Custom domain | orders.acmegrocers.example |
Separate origin per tenant | Certificate and DNS work per customer |
Two facts from MDN decide most of this. First, an origin is protocol, host and port, so acme.shop.example and bravo.shop.example are different origins; MDN says web storage and IndexedDB are separated by origin, and script in one origin cannot read or write the storage of another. A path-based design shares one origin, so localStorage is shared by every tenant unless your code namespaces it. Second, cookies use a different rule: a cookie with a Domain attribute is sent to that domain and all its subdomains, while a cookie without it is host-only. MDN also describes the __Host- prefix, which requires Secure, Path=/ and no Domain, so the cookie goes only to the host that set it. A session cookie scoped to shop.example would therefore be sent to every tenant subdomain; the token-handling lessons (Token Storage and Secure Cookies) cover the choice of cookie in depth.
Figure 1. Resolving the tenant at the edge
How to read this: the accent box turns a host name into a tenant id exactly once. Everything after it receives the id. The warning box is where trust is decided: the API checks that the signed-in user belongs to that tenant, whatever the browser claims.
Illustration 1: the minimal example, a host resolver
A resolver must be strict about what counts as a tenant host. Run in Node 26.13.1:
const TENANTS = new Map([
["acme", { id: "t_acme", name: "Acme Grocers" }],
["bravo", { id: "t_bravo", name: "Bravo Mart" }],
]);
const ROOT = "shop.example";
function tenantFromHost(host) {
const h = host.toLowerCase().split(":")[0];
if (!h.endsWith("." + ROOT)) return { ok: false, reason: "not a tenant host" };
const label = h.slice(0, -(ROOT.length + 1));
if (label.includes(".")) return { ok: false, reason: "nested label" };
const t = TENANTS.get(label);
return t ? { ok: true, tenant: t.id } : { ok: false, reason: "unknown tenant" };
}
for (const h of ["acme.shop.example", "BRAVO.shop.example:8443", "evil.shop.example", "a.b.shop.example", "shop.example.evil.test"]) {
console.log(h.padEnd(26), JSON.stringify(tenantFromHost(h)));
}
Output, from running it in Node 26.13.1:
acme.shop.example {"ok":true,"tenant":"t_acme"}
BRAVO.shop.example:8443 {"ok":true,"tenant":"t_bravo"}
evil.shop.example {"ok":false,"reason":"unknown tenant"}
a.b.shop.example {"ok":false,"reason":"nested label"}
shop.example.evil.test {"ok":false,"reason":"not a tenant host"}
The last row matters: a resolver that only checked "contains shop.example" would accept it. An unknown tenant gets a "not found" page, never a default tenant. This resolver is a teaching model, not a production router.
Per-tenant configuration over one build
Once the tenant is known, the app loads its configuration. Think in layers, from least to most specific: product defaults, the tenant's plan, the tenant's own settings, then the user's preferences.
Figure 2. Layering tenant configuration
How to read this: later layers win, and the merged result drives presentation. The dotted arrow is the safety rule: hiding a button for a tenant that lacks a feature is a courtesy; the server must refuse the call.
Theming. MDN describes CSS custom properties as scoped to the element they are declared on, inherited, and used with var(). That fits tenants well: set the tenant's token values on the root element and every component that reads var(--color-brand) follows (Design Tokens and Theming covers token design). Two cautions. Tenant-supplied colours are input: validate them as colours, and check the contrast of text on the brand colour at save time rather than discovering it in an audit (Accessibility and Compliance). And keep a flash of the wrong brand out of the first paint by sending the tenant's tokens in the HTML, not after a client fetch.
Features and copy. Plan-based features and gradual rollouts are covered in Feature Flags and A/B Testing, and values that differ by environment in Runtime Configuration and Environments. The tenant dimension is one more key in the same mechanism. Resist custom code per tenant: each fork multiplies testing, and the config layer is where a tenant's wishes should stop. Locale is part of the layer too (Internationalization, Localization and RTL).
Keeping tenants apart in caches and storage
OWASP's cheat sheet says to include the tenant identifier in every cache key whose value or authorization varies by tenant, and adds that key separation alone is not enough for protected values: authorization still applies before a read. The same applies in the browser and at the edge.
- Client data cache. Keys such as
["orders", filters]must become[tenantId, "orders", filters](see Server State, Caching and Revalidation). - Browser storage. On a shared origin, namespace every key by tenant and user. On separate origins, the browser separates them, but cookies scoped to the parent domain still cross.
- Service worker caches. MDN describes
CacheStorageas a mapping of string names toCacheobjects that both a service worker and the page can reach, so on a shared origin put the tenant in the cache name (Service Worker Caching Strategies). - CDN and shared caches. MDN says
Varymakes responses be cached separately by the request headers it lists. A page whose HTML depends on the tenant but is served from one URL must vary on whatever carries the tenant (usually theHost), or use per-tenant URLs. MDN'sCache-Controlpage saysprivateallows storage only in a private cache such as a browser, and that responses to requests with anAuthorizationheader are not stored by shared caches unlesspublic,s-maxageormust-revalidateunlocks that. Do not add those to tenant data to "speed things up" (HTTP Caching, CDN and Edge Caching).
Illustration 2: the realistic example, a cache key with and without the tenant
Two tenants load /orders through one cache that is shared by path. Run in Node 26.13.1:
const cache = new Map();
const naiveKey = (path) => path;
const safeKey = (tenant, path) => `${tenant}|${path}`;
function load(keyFn, tenant, path, serverData) {
const key = keyFn.length === 1 ? keyFn(path) : keyFn(tenant, path);
if (cache.has(key)) return { from: "cache", value: cache.get(key) };
cache.set(key, serverData[tenant]);
return { from: "server", value: serverData[tenant] };
}
const server = { t_acme: ["Acme order 1001"], t_bravo: ["Bravo order 2002"] };
for (const [label, keyFn] of [["key = path only ", naiveKey], ["key = tenant + path ", safeKey]]) {
cache.clear();
const a = load(keyFn, "t_acme", "/orders", server);
const b = load(keyFn, "t_bravo", "/orders", server);
console.log(label, "acme ->", a.from, JSON.stringify(a.value), "| bravo ->", b.from, JSON.stringify(b.value));
}
Output, from running it in Node 26.13.1:
key = path only acme -> server ["Acme order 1001"] | bravo -> cache ["Acme order 1001"]
key = tenant + path acme -> server ["Acme order 1001"] | bravo -> server ["Bravo order 2002"]
With the path-only key the second tenant is served the first tenant's orders from the cache, and nothing errors. This is the whole class of bug in two lines of output. A real client cache has more moving parts; this model only shows the key.
Users who belong to several tenants
Consultants, agencies and support staff often belong to more than one tenant. Make the active tenant explicit state, shown in the UI, and treat a switch as a boundary.
Figure 3. Switching tenant
How to read this: nothing from the old tenant survives the switch, including requests still in flight that could land after it. A switch that only changes a variable leaves old data in the cache.
OWASP also advises returning 404 rather than 403 for a tenant-owned object that belongs to another tenant, so the response does not confirm the object exists. The UI should show a plain "not found" for both cases.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Subdomain per tenant | Browser isolates storage and service workers | Wildcard certificates, DNS, cookie Domain discipline |
| Path per tenant | Simple hosting, one certificate | Shared origin: you namespace everything yourself |
| Custom domains | Strongest brand fit | Per-customer certificates and onboarding |
| Config over forks | One build to test and ship | Config schema and validation to maintain |
| Tenant tokens in the HTML | No flash of the wrong brand | Pages are tenant-specific and need tenant-aware caching |
Build it
This lesson has no lab (lab type none). The two Node snippets above are plain scripts that were run, with their output shown unedited; they need no install. Browser behaviour, CDN behaviour and cookie scoping were not tested here: those statements rest on the cited documentation.
In practice: the seller dashboard for retail chains
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The dashboard started as one customer's app. Three chains now use it, each wants its logo and colours, one wants a feature the others do not, and all are served from app.shop.example/<chain>/.... A shared CDN serves the HTML for every path.
Starting architecture
Figure 4. One origin, tenant in the path
How to read this: the warning boxes are where tenant identity is only a convention: shared storage and cache names, and an API that trusts the path rather than the signed-in user's membership.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Namespace every storage and cache key by tenant | Stops the worst leaks now | Discipline in every module | A missed key leaks |
| Move to subdomains | Browser-level separation | DNS, certificates, cookie review | Migration of existing bookmarks |
| Custom domains per chain | Brand fit | Onboarding steps | Operations load |
The decision
| Field | Decision record |
|---|---|
| Context | One origin, shared HTML cache, API trusting the path, tenants about to multiply. |
| Decision | Move to subdomains with an edge resolver; send tenant tokens in the HTML; key client caches by tenant id; verify membership in the API from the token, treating the host as a selector. |
| Consequences, good | Storage and service workers separate by origin, no flash of the wrong brand. |
| Consequences, bad | Redirects from old paths, wildcard certificate to renew, a session-cookie review. |
| Revisit when | A customer needs a custom domain, or the tenant count makes per-tenant HTML caching too costly. |
Rollout and verification
- Write the isolation test first: two tenants, same path, assert different data and different HTML.
- Test tenant switching for stale requests landing after the switch.
- Check cache headers on tenant HTML and tenant API responses from outside the CDN.
- Run a cross-tenant probe in staging: request tenant B's resources with tenant A's session and expect not found.
The 2 a.m. failure
A support ticket: a Bravo Mart user saw Acme's logo for a few seconds, then the right one. The tenant HTML was cached at the CDN by path, and the Host was not part of the key for one route, so one tenant's page was briefly served to another.
First three checks: (1) compare the response headers for the same URL from two hosts; (2) check whether Vary or the cache key includes the host; (3) look for data, not just branding, in the cached HTML. Mitigation: purge that route, stop caching tenant HTML until the key is fixed. Follow-up: add the two-host comparison to the release checks.
The other side of this topic
The server holds the real isolation: where tenant rows live and how the tenant is bound to each query. Multi-Tenancy: Tenant Data and Isolation covers shared, schema and database models. The UI can hide data, but only the server can refuse it.
Architect's notes
- One resolver, one place. A tenant derived in five modules is five chances to differ.
- Never default to a tenant. Unknown means not found.
- Namespace by default. Make a helper that builds every cache and storage key so nobody types a raw key.
- Treat tenant branding as input. Validate colours and images, and check contrast.
- Test with two tenants always. One-tenant tests cannot see a leak.
Common mistakes
- A cache key that omits the tenant, on the client or at the edge.
- Trusting the tenant id in the URL as proof of membership.
- Session cookies scoped to the parent domain that every tenant subdomain receives.
- Forking the app per customer instead of adding a configuration option.
- Switching tenant without clearing client state or aborting in-flight requests.
- Hiding a feature in the UI while the API still serves it.
Key takeaways
- Resolve the tenant once, early, and strictly; unknown tenants get not found.
- A client-supplied tenant id is a selector; the server checks membership.
- Subdomains are separate origins with separate storage; paths share one origin; cookies follow their own
Domainrule. - Every cache key whose value varies by tenant must include the tenant.
- Per-tenant variation is layered configuration over one build.
- A tenant switch is a boundary: abort, clear, reload configuration.
Practice exercises
Exercise 1: Starter (30 min). Extend the host resolver with a custom-domain table and add test rows for a domain that is registered by a different tenant.
Exercise 2: Intermediate (2 hours). Write a tenantKey(tenant, user, name) helper for browser storage and replace three raw keys in a sample app; explain what changes for a user in two tenants.
Exercise 3: Advanced (half day). Design the cache headers for tenant HTML, tenant JSON and shared static assets on one CDN. State which request header each depends on and what you would test from outside.
Related reading
In this course:
- Design Tokens and Theming: the token layer that tenant branding sets.
- Token Storage and Secure Cookies: cookie scope and where to keep tokens.
- RBAC and ABAC on the UI: showing and hiding by permission, with the server as the gate.
- Runtime Configuration and Environments: configuration that changes without a rebuild.
- Multi-Tenancy: Tenant Data and Isolation: the server side of isolation.
Official documentation
- OWASP: Multi-Tenant Security Cheat Sheet: tenant identifiers as selectors, cache keys, 404 for foreign objects.
- MDN: Same-origin policy: what an origin is and how storage is separated.
- MDN: Set-Cookie:
Domain, host-only cookies and the__Host-prefix. - MDN: Vary: separate cache entries by request header.
- MDN: Cache-Control: private, public and shared-cache behaviour.
- MDN: CSS custom properties: scoping and inheritance of tenant tokens.