01
One app, every tenant
I built subdomain-based multi-tenancy in middleware: extract the company from the host, validate it exists against the backend, then validate the session JWT (`/v1/auth/me`) with conditional auth redirects that remember where the user was headed — so each company gets a branded, isolated workspace from a single deployment.
// src/middleware.ts — resolve tenant from the subdomain, then auth
const subdomain = hostnameParts.length > 2 ? hostnameParts[0] : null;
const { data: company } = await fetch(
`${SERVER_URL}/v1/auth/company/check/${subdomain}`
).then((r) => r.json());
if (!company) return NextResponse.redirect(new URL("/login", request.url));
const token = request.cookies.get("__ps-c-a")?.value;
if (!token || !(await validateToken(token)))
return NextResponse.redirect(new URL(`/login?redirect=${path}`, request.url));