-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
80 lines (68 loc) · 2.31 KB
/
proxy.ts
File metadata and controls
80 lines (68 loc) · 2.31 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
const protectedRoutes = ["/dashboard"];
// Runtime CORS for /api/* — handles credentials-bearing requests correctly
// (dynamic per-request origin, required when Access-Control-Allow-Credentials: true)
const allowedOrigins = [
process.env.BETTER_AUTH_URL,
process.env.NEXT_PUBLIC_APP_URL,
].filter(Boolean) as string[];
const corsHeaders = {
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true",
};
export async function proxy(req: NextRequest) {
const path = req.nextUrl.pathname;
const origin = req.headers.get("origin") ?? "";
const isAllowedOrigin = allowedOrigins.includes(origin);
// CORS preflight — only for /api/* routes
if (req.method === "OPTIONS" && path.startsWith("/api/")) {
return NextResponse.json(
{},
{
headers: {
...(isAllowedOrigin && { "Access-Control-Allow-Origin": origin }),
...corsHeaders,
},
},
);
}
// Auth redirect: protect dashboard routes
const isProtectedRoute = protectedRoutes.some(
(route) => path === route || path.startsWith(`${route}/`),
);
if (isProtectedRoute) {
const session = await auth.api.getSession({ headers: req.headers });
if (!session) {
return NextResponse.redirect(new URL("/login", req.nextUrl));
}
}
// Auth redirect: send logged-in users away from login page
if (path === "/login") {
const session = await auth.api.getSession({ headers: req.headers });
if (session) {
return NextResponse.redirect(new URL("/dashboard", req.nextUrl));
}
}
const response = NextResponse.next();
// Attach CORS headers on /api/* responses
if (path.startsWith("/api/") && isAllowedOrigin) {
response.headers.set("Access-Control-Allow-Origin", origin);
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
}
return response;
}
export const config = {
matcher: [
{
source: "/((?!_next/static|_next/image|favicon.ico).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
};