Files
menulio/apps/web/src/middleware.ts
T
AyrisAI 77eecd53ac fix(web): strip trailing slash from wildcard/custom-domain rewrite target
Root-path requests to a subdomain or custom domain rewrote to
/menu/<slug>/ (trailing slash), which the [slug] dynamic route can't
match — the app fell through to notFound() even for verified,
published restaurants. Custom domains (e.g. ad.ayris.tech) always hit
this since their only real traffic is the root path.
2026-08-20 05:18:59 +03:00

33 lines
1.3 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
const ROOT_DOMAIN = process.env.ROOT_DOMAIN ?? "menul.io";
// Wildcard subdomain routing: kebapci-ahmet.menul.io -> /menu/kebapci-ahmet
// Custom domains resolve here too once verified (PRD §11).
export function middleware(req: NextRequest) {
const host = req.headers.get("host") ?? "";
const hostname = host.split(":")[0] ?? host;
const isRootDomain = hostname === ROOT_DOMAIN || hostname === `www.${ROOT_DOMAIN}`;
if (isRootDomain || hostname === "localhost") {
return NextResponse.next();
}
const subdomain = hostname.endsWith(`.${ROOT_DOMAIN}`)
? hostname.replace(`.${ROOT_DOMAIN}`, "")
: hostname; // custom domain — resolved to a slug via domains table at render time
// On the root path, req.nextUrl.pathname is "/" — appending it as-is would
// rewrite to "/menu/<slug>/" (trailing slash), which the [slug] dynamic
// route does not match. Only append the original path when it's non-root.
const originalPath = req.nextUrl.pathname === "/" ? "" : req.nextUrl.pathname;
const url = req.nextUrl.clone();
url.pathname = `/menu/${subdomain}${originalPath}`;
return NextResponse.rewrite(url);
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};