# Multi-tenant

Goal: one build answers several domains, each with its own content, canonical URL and name. The runnable sample is `examples/recipes/multi-tenant/`; `acme.test` and `globex.test` are served by the same build.

1. List the hosts in `site.tenants`. A request whose host (`Host`, or `X-Forwarded-Host` under `server.trustProxy`) is in a tenant's `hosts` reads that tenant: its `url`, `name` and `indexable` over the base `site`. Any other host reads the base `site`. `site.tenants` is a core key and needs a server preset ([SEO](/seo#tenants)):

````ts [recipes/multi-tenant-config.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "react",
  site: {
    url: "https://example.com",
    name: "Example",
    tenants: [
      { hosts: ["acme.test", "www.acme.test"], url: "https://acme.test", name: "Acme" },
      { hosts: ["globex.test"], url: "https://globex.test", name: "Globex", indexable: false },
    ],
  },
})
````

2. Name the tenant in server middleware. A request step can return `rewrite(path)` from `hamur/app`: the address stays, and the answer is the target page's ([Server](/server#middleware)). The sample sends every page request to `/tenants/<host>/…`. There is no `rewriteTo` and a folder that starts with `_` is never a route, so the pages live in `app/pages/tenants/[tenant]/`. Leave the `/_hamur/` endpoints and your own handler routes out:

````ts [recipes/multi-tenant-middleware.ts]
import { rewrite } from "hamur/app"
import { defineMiddleware, getRequestURL } from "hamur/server"

export const tenant = defineMiddleware(({ event }) => {
  const { hostname, pathname } = getRequestURL(event)
  if (pathname.startsWith("/_hamur/") || pathname.startsWith("/api/")) return
  return rewrite(`/tenants/${hostname}${pathname === "/" ? "" : pathname}`)
})
````

List it in `server/index.ts` as `export default defineServer({ middleware: [tenant] })`. `/` of `acme.test` renders `tenants/[tenant]/index`, and `/about` renders `tenants/[tenant]/about`, both with `params.tenant` set to `acme.test`. A request for `/tenants/acme.test` from outside is rewritten again to `/tenants/acme.test/tenants/acme.test` and answers 404, so a visitor cannot ask for another tenant's tree.

3. Read the tenant in the page. `useSiteConfig()` of the adapter returns the site of the request's host, so a page shows its tenant's name and canonical URL without knowing the list; the canonical link, `og:url`, the sitemap and the robots file of the SEO module follow it too. A page that needs more than that, such as its tenant's theme or data, reads `params.tenant` in its `load`:

````tsx [recipes/react/TenantPage.tsx]
import { Link, useRoute, useSiteConfig } from "@hamur/adapter-react"

export default function TenantHome() {
  const { params } = useRoute()
  const site = useSiteConfig()
  return (
    <main>
      <h1>{site.name}</h1>
      <p>{`Host ${String(params.tenant)}, canonical ${site.url}`}</p>
      <Link external to="/about">
        About
      </Link>
    </main>
  )
}
````

Links between tenant pages use `external`. The pages sit at `/tenants/[tenant]/…` but the address is `/about`, which no page has, so a client navigation would find nothing; `external` makes it a document request and the middleware rewrites it. A mapping the browser should apply to its own navigations belongs in a rule or the reroute file ([Rewrites](/route-rules#rewrites)).

4. Cache by host. Every default cache key of Hamur holds the host: a route rule's `swr` and `cache`, a `GET` handler's `cache` and the fetch cache. `acme.test/about` and `globex.test/about` are two entries, so one tenant never gets the other's page. The cached page also runs without the visitor's cookie, so a page that depends on the signed-in user needs `varies: ["cookie"]` ([Route rules in the cache](/api-reference/storage-details#route-rules)):

````ts [recipes/multi-tenant-cache-config.ts]
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "react",
  routeRules: { "/tenants/**": { swr: 60 } },
})
````

5. Run it. Send the host you want to test with `curl`, since both names point at the one server:

```sh
hamur build
PORT=3000 bun .output/server/index.mjs
curl -H 'host: acme.test' http://127.0.0.1:3000/
curl -H 'host: globex.test' http://127.0.0.1:3000/
```

Each answers its own heading and canonical URL. The prerender and the `static` preset use the base `site` only, and a tenant's request on a server preset never takes a prerendered file; the build says how many paths now render on demand.

See also: [SEO, tenants](/seo#tenants), [Server middleware](/server#middleware), [Route rules](/route-rules#rewrites), [Storage and cache](/storage-and-cache).
