From aea4713aeb59ae9b82a267e129fd881005004217 Mon Sep 17 00:00:00 2001 From: echo Date: Mon, 22 Jun 2026 21:57:17 +0200 Subject: [PATCH] subdomain fix --- src/middleware.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/middleware.ts b/src/middleware.ts index 335a15f..5dfaca4 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -4,12 +4,30 @@ import type { NextRequest } from "next/server"; const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/onboarding(.*)", "/api/publish(.*)", "/api/upload(.*)", "/api/user(.*)"]); +function getSubdomain(req: NextRequest): string | null { + const host = req.headers.get("host"); + if (!host) return null; + + const apex = process.env.NEXT_PUBLIC_APP_DOMAIN || "testbed.mk"; + const portIndex = host.indexOf(":"); + const hostname = portIndex !== -1 ? host.slice(0, portIndex) : host; + + if (hostname === apex || hostname === `www.${apex}`) return null; + + if (hostname.endsWith(`.${apex}`)) { + const sub = hostname.slice(0, hostname.length - apex.length - 1); + if (sub && sub !== "www") return sub; + } + + return null; +} + export default clerkMiddleware(async (auth, req: NextRequest) => { if (isProtectedRoute(req)) { await auth.protect(); } - const subdomain = req.headers.get("x-subdomain"); + const subdomain = getSubdomain(req); if (subdomain) { const url = req.nextUrl.clone(); url.pathname = `/${subdomain}${url.pathname === "/" ? "" : url.pathname}`;