One codebase, many companies: tenant subdomains in Next.js
ERES, our ERP, runs every client from one Next.js deploy. Each company gets its own subdomain and sees only its own books. Two layers make that work, and only one of them is about the URL.
Layer one: read the host
In Next.js 16 the old middleware file is called proxy.ts. It runs before every request, so it is the place to turn acme.example.com into a tenant slug and pass it on in a header.
import { NextResponse, type NextRequest } from "next/server";
const ROOT = process.env.ROOT_DOMAIN!; // e.g. example.com
export function proxy(req: NextRequest) {
const host = req.headers.get("host")?.split(":")[0] ?? "";
const slug = host.endsWith("." + ROOT) ? host.slice(0, -(ROOT.length + 1)) : null;
const headers = new Headers(req.headers);
headers.delete("x-tenant"); // never trust one sent by the browser
if (slug && slug !== "www") headers.set("x-tenant", slug);
return NextResponse.next({ request: { headers } });
}Layer two: every query filters on the tenant
The subdomain only says which company the visitor is looking at. Whether they may see it is decided by the signed-in user's own tenant, and that check belongs in the code that reads the database, where no page can forget it.
import { requireSession } from "@/lib/auth";
export async function scoped() {
const session = await requireSession();
const tenantId = session.user.tenantId;
return {
tenantId,
where<T extends object>(filter: T) {
return { ...filter, tenantId };
},
};
}
// usage
const { where } = await scoped();
const invoices = await Invoice.find(where({ status: "open" }));What we would tell anyone starting one
- Put tenantId on every collection from day one, with compound indexes that start with it.
- Strip any tenant header the browser sends before setting your own.
- Write one test per model that signs in as company A and tries to read company B.
- Wildcard DNS and a wildcard certificate cover every new client without a deploy.