Next routes a subdomain with a middleware.ts that rewrites
acme.example.com/settings to /acme/settings before matching, and the
route tree never learns a host was involved. Here the same rule is the
router’s own, so the build can see it: typed routes, one stored page per
tenant, and no middleware to write.
The rule
A request from a host that is not the site’s own is matched with the host in front of the path:
| request | matched as | file |
|---|---|---|
example.com/admin |
/admin |
app/admin/page.tsx |
admin.example.com/ |
/admin |
app/admin/page.tsx — the same file |
acme.example.com/settings |
/acme/settings |
app/[domain]/settings/page.tsx, domain: "acme" |
acme.com/settings |
/acme.com/settings |
the same file, domain: "acme.com" |
A subdomain of the site contributes its label; any other host contributes the
whole host. The site’s own hosts — the one in the root layout’s
metadataBase, www. of it, and any named in rscKit({ hosts }) — contribute
nothing, so the apex keeps path routing and an app adds tenants without moving
a file. localhost and an ip address are always the site’s own.
Listing a subdomain in hosts makes it the site by path instead of a tenant —
the “app on app.example.com, marketing on the apex” split — which is a
choice, not a requirement.
And only when a route could answer it: a [domain] (or [host]) directory at
the top of app/, or a directory named for the host. Any other parameter
name at the top of app/ — [collection], [slug] — is a path segment, as
it is in Next. An app with no tenant tree routes every host by path, and a proxy that forwards to the app by an internal name is not
read as a tenant called internal.
A subdomain of the site with no directory of its name falls back the same
way: with no app/merchant/, merchant.example.com/ serves the home page.
That keeps a preview deployment under the production domain working. The dev
server says so once per host, naming the directory to add:
[rsc-kit] merchant.example.test has no app/merchant/ - served by path, as the site's own. Add app/merchant/ to route the subdomain there.The visitor’s url is untouched: acme.example.com/settings stays in the
address bar, and a link to /billing on that page goes to
acme.example.com/billing. Only the match changed.
The one step: name the site’s host
The router has to know which host is the site, and it learns it from either
the root layout’s metadataBase or rscKit({ hosts }) — one is enough, and
neither is needed for anything else here. Name neither and no host is the
site’s: merchant.example.com is then a foreign host whose segment is the
whole name, no directory matches it, and it is served by path — the home page,
with nothing said.
hosts is the one to reach for when the address is in the environment, as a
Laravel app’s is in APP_URL. It is read by the build, so the address of the
machine running it — example.test under Herd, the real domain in
production — is the one named:
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
plugins: [rscKit({ hosts: [new URL(env.APP_URL).host] })],
}
})metadataBase does the same when it is written as a literal, but it is for
metadata — the base a relative Open Graph image or canonical url is made
absolute against — and a computed one is not read for routing. An app with no
such metadata needs none.
hosts also takes a name that is neither the apex nor a subdomain of it and
is still the site rather than a tenant — a staging or internal name, or a
second brand domain:
rscKit({ hosts: ['app.internal', 'example.co.uk'] })A directory then does the rest: app/merchant/ is all merchant.example.com
needs.
A tenant tree
Whether the tenant exists is a guard, so it goes in middleware.ts. It runs
before anything is sent, on every path, and its notFound() is a real 404.
Its argument is the route’s params:
import { notFound } from '@rsc-kit/core/not-found';
import { tenantByDomain } from '@/lib/tenants';
export default async function knownTenant({ domain }) {
if (!(await tenantByDomain(domain))) notFound(); // "acme" or "acme.com", as stored
}The layout is handed the same params, as a promise. A route that lists no
urls is stored as one shell for every tenant, so what reads the tenant goes
under <Suspense>; awaited above every boundary, there is no value to store
the shell with, and the build says so and names the layout:
import { Suspense } from 'react';
import { tenantByDomain } from '@/lib/tenants';
async function TenantName({ params }) {
const { domain } = await params;
return (await tenantByDomain(domain))!.name;
}
export default function TenantLayout({ params, children }) {
return (
<>
<header>
<Suspense fallback={null}>
<TenantName params={params} />
</Suspense>
</header>
{children}
</>
);
}A layout sees its own segments’ params and those above it, never a deeper
one’s, and it is rendered again when one of its own values changes:
acme.example.com/settings to globex.example.com/settings renders the
tenant layout for globex, while the root layout above it stays mounted.
[domain] is an ordinary dynamic segment: params.domain in every page and
layout below it, hostUrl(domain, '/settings') to link to it (below), loading.tsx
and error.tsx where you put them. A directory named for a host,
app/admin/, wins over [domain] the way a static segment wins over a
parameter anywhere else.
One difference from a parameter deeper in the tree: a [domain] at the top
of app/ binds only from a host, never from a path. example.com/nope
is a 404, not a tenant called nope, and acme.example.com/ cannot be
reached as example.com/acme. Next has no such guard — its [domain] folder
matches any path once the rewrite is in place — which is why Next apps tuck
the tenant tree under a route group.
Linking to another host
A typed href is a folder path: /merchant/orders is the page at
app/merchant/orders, and that is the url a link to it goes to — the site,
by path. Both addresses work, so nothing breaks; but when the page is meant
to be seen on merchant.example.com, say so with hostUrl:
import { Link } from '@rsc-kit/core/link';
import { hostUrl } from '@rsc-kit/core/routes';
<Link href={hostUrl('merchant', '/orders')}>Orders</Link> // //merchant.example.com/orders
<Link href={hostUrl(tenant.slug, '/settings')}>Settings</Link> // //testbrand.example.com/settings
<Link href={hostUrl('acme.com', '/settings')}>Settings</Link> // //acme.com/settings
<Link href={hostUrl('/pricing')}>Pricing</Link> // //example.com/pricing, from a subdomain- The first argument autocompletes to the top-level folders of
app/, and takes any other string too: a tenant’s subdomain, read from the database at request time. A name with a dot is a whole domain, used as written. - The path is typed by what that host answers. For a folder it is the pages
under it, with the folder taken off —
hostUrl('merchant', '/orders'), not'/merchant/orders'. For any other name it is the tenant tree’s paths. - With one argument it is the site itself: the link back from a subdomain,
where a plain
/pricingwould stay on the subdomain.
The site’s host is the first one rscKit({ hosts }) names (a literal
metadataBase otherwise), port and all, so hosts: [new URL(env.APP_URL).host]
gives merchant.example.test under Herd and merchant.example.com in
production. With no host named, a folder’s url is its path,
/merchant/orders, since every page is then reached by path.
It is the same string on the server and in the browser, so the link hydrates
as it was rendered, and it works in visit() and redirect() too. On the
host it names already, Link navigates without a reload; to another host it is
a full page load, as a link to another origin always is.
Nothing redirects between the two addresses unless you name the folder, below.
A folder that lives on its subdomain
When a folder is only ever meant to be seen on its subdomain - a merchant dashboard, an admin - name it, and its subdomain becomes the page’s only url:
rscKit({ hosts: [new URL(env.APP_URL).host], subdomains: ['merchant'] })example.com/merchant/ordersanswers 301 tomerchant.example.com/orders, query kept. Only on the site’s own host: onlocalhost, an address, a preview or a platform’s own name (<app>.homeport.run) the path form still renders and links keep it, since there is no subdomain of those to go to.<Link href="/merchant/orders">,visit('/merchant/orders')andredirect('/merchant/orders')go tomerchant.example.com/orders: the typed href stays the folder path, and the host is placed for you. NohostUrl.- On the subdomain, a root path that is not under the folder is the site’s:
<Link href="/pricing">goes toexample.com/pricing. edge.jsonlists none of the folder’s pages: an edge answers by path and would skip the 301. AbackendPathsentry under the folder stops the build - visitors there send/auth, never/merchant/auth.- The build’s route table lists the folder, so a backend that names routes
puts them on the subdomain - Laravel’s
route('merchant.orders')ishttps://merchant.example.com/orders.
The trade is that example.com/merchant is no longer a page of the site: it
is the subdomain’s home page. A landing page about merchants goes in a folder
of its own, such as app/sell/. It needs the site’s host (hosts) and a
folder of that name, or dev and the build stop and say which. hostUrl is
still how you link to a tenant or a custom domain, and still works for a
named folder.
Domains in a database
generateStaticParams on the tenant route is the hook. The listed hosts are
rendered at build and stored, one file per host; a host added afterwards
falls through to the plain tree, or — if the page reads the request — renders
on demand and resolves at request time:
export async function generateStaticParams() {
const tenants = await db.tenant.findMany({ select: { domain: true } });
return tenants.map((t) => ({ domain: t.domain }));
}A tenant’s page that reads cookies() or awaits connection() is dynamic
for that tenant and stored for none, exactly as any page is.
Locally
localhost and an ip address are always the site’s own, so a dev server
opened on one routes by path as it always did. A local name is not:
example.test under Herd or Valet is a host like any other, and
merchant.example.test reaches app/merchant/ only when example.test is
named in hosts — which reading APP_URL, as above, does. A metadataBase
fixed to the production host names only that one. To try a tenant
without DNS, send the host the router will see in production:
curl -H 'X-Forwarded-Host: acme.example.com' http://localhost:3000/Or point acme.example.com at 127.0.0.1 in /etc/hosts and open it on
the dev server’s port in a browser.
Behind a proxy
The host is read from X-Forwarded-Host first, then Host. A load balancer
that terminates TLS and forwards to the app by an internal name still routes
by the name the visitor typed.
Not for a static export
An export is served by a file server, which sees no host. Host routing is a server feature; an exported site is the site’s own on every host it is served from.
Coming from Next
Delete the rewrite in middleware.ts and the [domain] directory works as
it did; the segment binds the same value the rewrite put there. Next’s
rewrite() for anything else is not here — a host maps to a tree by file,
not by code.