Skip to the code

A shop on every tea house's own address

Leaf and Kettle now runs online shops for tea houses, all from one Next.js app. Each tea house's pages live under app/sites/[tenant], so /sites/kyoto/menu is the Kyoto tea house's menu. Visitors never see that path: each shop has its own address, and proxy.ts rewrites its requests to the right folder. Write it.

The address the visitor asked for is in the request's host header, like kyoto.leafandkettle.app or, on your computer, kyoto.localhost:3000. Read it from there: on a server started with next start, request.url names the server itself, http://localhost:3000/..., whatever the visitor typed, and so do the tests' requests. Drop any port and compare in lowercase. @/lib/tenants has ROOT_DOMAIN, the shop's own domain; tenants, the tea houses' subdomains; and customDomains, a Map from the domains tea houses brought themselves to their tea house.

Leaf and Kettle's own site, leafandkettle.app, www.leafandkettle.app, and localhost, goes on to its pages unchanged: return NextResponse.next().

A tea house's address is a subdomain of ROOT_DOMAIN that's in tenants, the same subdomain of localhost, or a domain in customDomains. Rewrite its requests to its folder, keeping the path and query: kyoto.leafandkettle.app/teas/sencha?size=50g shows /sites/kyoto/teas/sencha?size=50g, and the shop's home page, /, shows /sites/kyoto.

Any other host is a shop that doesn't exist: answer 404 with an empty body, straight from the proxy. That includes tokyo.leafandkettle.app, a subdomain of a subdomain like tea.kyoto.leafandkettle.app, and look-alikes such as fakeleafandkettle.app and kyoto.leafandkettle.app.example.

The /sites folder is only for rewrites. A request for /sites or any path under it answers 404 too, on any host, so nobody can open one shop's pages at another shop's address or on the main site.

config.matcher keeps the proxy away from the API (/api/...), Next.js's own files (/_next/...), and any path with a dot, like /favicon.ico.

GET /menu?table=4   Host: kyoto.leafandkettle.app
→ shows /sites/kyoto/menu?table=4, while the address stays kyoto.leafandkettle.app/menu?table=4
 
GET /menu           Host: shop.yunnanhouse.example   → shows /sites/yunnan/menu
GET /menu           Host: tokyo.leafandkettle.app    → 404
GET /sites/kyoto    Host: leafandkettle.app          → 404

The app's other files

lib/tenants.ts, read-only. Import it as @/lib/tenants.

/** Leaf and Kettle's own domain. Each tea house gets a subdomain of it, like kyoto.leafandkettle.app. */
export const ROOT_DOMAIN = "leafandkettle.app";
 
/** The tea houses with a shop, by their subdomain. Their pages live in app/sites/[tenant]. */
export const tenants = ["kyoto", "yunnan", "darjeeling"];
 
/** Domains tea houses brought themselves, each with the tea house whose shop it shows. */
export const customDomains = new Map<string, string>([
  ["shop.yunnanhouse.example", "yunnan"],
  ["darjeelingestate.example", "darjeeling"],
]);

What the tests check

  1. runs for pages, not the API, Next.js's files, or paths with a dot
    for (const path of ["/", "/menu", "/teas/sencha", "/sites/kyoto"]) expect(proxyRuns(path)).toBe(true);
    for (const path of ["/api/orders", "/_next/static/chunks/main.js", "/_next/image", "/favicon.ico", "/images/leaf.png"]) expect(proxyRuns(path)).toBe(false);
    
  2. rewrites a tea house's subdomain to its folder, keeping the path and query
    // As with next start, request.url is http://localhost:3000/...; the host header has the address.
    const visit = (host, path) => proxy(request(path, { headers: { host } }));
    const shown = (response) => {
      const target = response.headers.get("x-middleware-rewrite");
      return target === null ? null : new URL(target).pathname + new URL(target).search;
    };
    const menu = await visit("kyoto.leafandkettle.app", "/menu?table=4");
    expect(shown(menu)).toBe("/sites/kyoto/menu?table=4");
    expect(menu.headers.get("location")).toBeNull();
    expect(shown(await visit("kyoto.leafandkettle.app", "/teas/sencha"))).toBe("/sites/kyoto/teas/sencha");
    expect(shown(await visit("darjeeling.leafandkettle.app", "/"))).toBe("/sites/darjeeling");
    
  3. reads the host without its port, in any case, and on localhost
    const visit = (host, path) => proxy(request(path, { headers: { host } }));
    const shown = (response) => {
      const target = response.headers.get("x-middleware-rewrite");
      return target === null ? null : new URL(target).pathname + new URL(target).search;
    };
    expect(shown(await visit("yunnan.localhost:3000", "/menu"))).toBe("/sites/yunnan/menu");
    expect(shown(await visit("Yunnan.LeafAndKettle.app:443", "/menu"))).toBe("/sites/yunnan/menu");
    expect(shown(await visit("kyoto.localhost:3000", "/"))).toBe("/sites/kyoto");
    
  4. custom domains show their tea house's shop
    const visit = (host, path) => proxy(request(path, { headers: { host } }));
    const shown = (response) => {
      const target = response.headers.get("x-middleware-rewrite");
      return target === null ? null : new URL(target).pathname + new URL(target).search;
    };
    expect(shown(await visit("shop.yunnanhouse.example", "/menu"))).toBe("/sites/yunnan/menu");
    expect(shown(await visit("darjeelingestate.example", "/"))).toBe("/sites/darjeeling");
    expect(shown(await visit("darjeelingestate.example", "/teas?sort=price"))).toBe("/sites/darjeeling/teas?sort=price");
    
  5. Leaf and Kettle's own site goes on unchanged
    for (const [host, path] of [["leafandkettle.app", "/"], ["www.leafandkettle.app", "/teas/mint"], ["localhost:3000", "/teas?sort=price"]]) {
      const response = await proxy(request(path, { headers: { host } }));
      // NextResponse.next() marks its answer with x-middleware-next: 1; returning nothing does the same.
      expect(response === undefined ? "1" : response.headers.get("x-middleware-next")).toBe("1");
      expect(response?.headers.get("x-middleware-rewrite") ?? null).toBeNull();
    }
    
  6. unknown shops and look-alike hosts get an empty 404
    const hosts = ["tokyo.leafandkettle.app", "tea.kyoto.leafandkettle.app", "fakeleafandkettle.app", "kyotoleafandkettle.app", "kyoto.leafandkettle.app.example", "tokyo.localhost:3000", "yunnanhouse.example"];
    for (const host of hosts) {
      const response = await proxy(request("/menu", { headers: { host } }));
      expect(response.status).toBe(404);
      expect(response.headers.get("x-middleware-rewrite")).toBeNull();
      expect(await response.text()).toBe("");
    }
    
  7. /sites can't be opened from outside, on any host
    for (const [host, path] of [["leafandkettle.app", "/sites/kyoto/menu"], ["kyoto.leafandkettle.app", "/sites/yunnan/menu"], ["localhost:3000", "/sites"], ["shop.yunnanhouse.example", "/sites/kyoto"]]) {
      const response = await proxy(request(path, { headers: { host } }));
      expect(response.status).toBe(404);
      expect(response.headers.get("x-middleware-rewrite")).toBeNull();
    }
    const page = await proxy(request("/sites-we-love", { headers: { host: "kyoto.leafandkettle.app" } }));
    const target = page.headers.get("x-middleware-rewrite");
    expect(target && new URL(target).pathname).toBe("/sites/kyoto/sites-we-love");
    

Learn more

proxy.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).