spomeni/src/middleware.ts
2026-06-22 23:39:19 +02:00

42 lines
1.4 KiB
TypeScript

import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
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 = getSubdomain(req);
if (subdomain && !req.nextUrl.pathname.startsWith("/api")) {
const url = req.nextUrl.clone();
url.pathname = `/${subdomain}${url.pathname === "/" ? "" : url.pathname}`;
return NextResponse.rewrite(url);
}
return NextResponse.next();
});
export const config = {
matcher: ["/(api|trpc)(.*)", "/__clerk/:path*", "/((?!_next|api/static|.*\\..*).*)"],
};