import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { parseHost } from "@/lib/host"; // Host → URL-rewrite. Acme visits acme.localhost:3000/dashboard; we // internally rewrite to /acme/dashboard so the [slug] route group renders. // URL bar stays unchanged. // // Backstage (backstage.) rewrites to /__backstage__/. // Apex hosts (localhost, breakpilot.com) get a marketing/landing page // at the root route. export function middleware(request: NextRequest) { const match = parseHost(request.headers.get("host")); const url = request.nextUrl.clone(); if (match.kind === "tenant") { if (!url.pathname.startsWith(`/${match.slug}/`) && url.pathname !== `/${match.slug}`) { url.pathname = `/${match.slug}${url.pathname === "/" ? "" : url.pathname}`; return NextResponse.rewrite(url); } } else if (match.kind === "backstage") { if (!url.pathname.startsWith("/__backstage__")) { url.pathname = `/__backstage__${url.pathname === "/" ? "" : url.pathname}`; return NextResponse.rewrite(url); } } return NextResponse.next(); } export const config = { // Skip Next internals + API + static assets so middleware doesn't // double-rewrite the auth callback or _next/static. matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"], };