import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { getCustomerDashboardOrigin, hostAppFor, rewriteBusinessPath, rewriteCustomerPath, } from "@/lib/host"; function isAuthPublicPath(pathname: string) { return ( pathname === "/login" || pathname === "/forgot-password" || pathname === "/auth/handoff" ); } export function middleware(request: NextRequest) { const host = request.headers.get("host"); const { pathname } = request.nextUrl; const app = hostAppFor(host); if (app === "admin") { if ( pathname === "/business" || pathname.startsWith("/business/") || pathname === "/customer" || pathname.startsWith("/customer/") ) { const url = request.nextUrl.clone(); url.pathname = "/"; return NextResponse.redirect(url); } return NextResponse.next(); } if (app === "customer") { if (pathname === "/businesses" || pathname.startsWith("/businesses/")) { const url = request.nextUrl.clone(); url.pathname = "/"; return NextResponse.redirect(url); } if (pathname === "/business" || pathname.startsWith("/business/")) { const url = request.nextUrl.clone(); url.pathname = "/"; return NextResponse.redirect(url); } if (pathname === "/customer" || pathname.startsWith("/customer/")) { return NextResponse.next(); } if (isAuthPublicPath(pathname)) { return NextResponse.next(); } const target = rewriteCustomerPath(pathname); if (target) { if (target === pathname) return NextResponse.next(); const url = request.nextUrl.clone(); url.pathname = target; return NextResponse.rewrite(url); } const url = request.nextUrl.clone(); url.pathname = "/"; return NextResponse.redirect(url); } // Business host if (pathname === "/businesses" || pathname.startsWith("/businesses/")) { const url = request.nextUrl.clone(); url.pathname = "/profile"; return NextResponse.redirect(url); } if (pathname === "/customer" || pathname.startsWith("/customer/")) { const url = request.nextUrl.clone(); url.pathname = "/profile"; return NextResponse.redirect(url); } // Shared login lives on the customer host. if (pathname === "/login" || pathname === "/forgot-password") { const url = new URL(pathname, `${getCustomerDashboardOrigin()}/`); return NextResponse.redirect(url); } if (pathname === "/business" || pathname.startsWith("/business/")) { return NextResponse.next(); } if (pathname === "/auth/handoff") { return NextResponse.next(); } const target = rewriteBusinessPath(pathname); if (target) { if (target === pathname) return NextResponse.next(); const url = request.nextUrl.clone(); url.pathname = target; return NextResponse.rewrite(url); } const url = request.nextUrl.clone(); url.pathname = "/profile"; return NextResponse.redirect(url); } export const config = { matcher: [ "/((?!_next/static|_next/image|favicon.ico|images/|fonts/).*)", ], };