-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmiddleware.ts
More file actions
51 lines (42 loc) · 1.6 KB
/
Copy pathmiddleware.ts
File metadata and controls
51 lines (42 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import NextAuth from "next-auth";
import { NextRequest, NextResponse } from "next/server";
import { authConfig } from "@/lib/auth.config";
import { isPlatformHost, normalizeDomain } from "@/lib/custom-domain";
const authMiddleware = NextAuth(authConfig).auth;
async function resolveDomainEventPath(request: NextRequest) {
const host = normalizeDomain(request.headers.get("x-forwarded-host") || request.headers.get("host") || "");
if (!host || isPlatformHost(host)) return null;
const apiUrl = new URL(`/api/events/resolve-domain?domain=${encodeURIComponent(host)}`, request.nextUrl.origin);
try {
const response = await fetch(apiUrl.toString(), {
method: "GET",
headers: {
"x-forwarded-host": host,
},
cache: "no-store",
});
if (!response.ok) return null;
const data = await response.json();
return data?.eventPath || null;
} catch (error) {
console.error("Custom domain resolve failed:", error);
return null;
}
}
export default async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (pathname === "/" || pathname === "") {
const eventPath = await resolveDomainEventPath(request);
if (eventPath) {
const rewriteUrl = request.nextUrl.clone();
rewriteUrl.pathname = eventPath;
return NextResponse.rewrite(rewriteUrl);
}
}
return authMiddleware(request as any);
}
export const config = {
matcher: [
"/((?!api/auth|_next/static|_next/image|favicon.ico).*)",
],
};