-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
77 lines (63 loc) · 2.48 KB
/
proxy.ts
File metadata and controls
77 lines (63 loc) · 2.48 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
// Protected routes that require authentication
const protectedRoutes = ["/app"];
// Auth routes that should redirect to /app if already authenticated
const authRoutes = ["/sign-in", "/sign-up"];
export default async function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
// Check if current path is protected or auth route
const isProtectedRoute = protectedRoutes.some((route) =>
pathname.startsWith(route)
);
const isAuthRoute = authRoutes.some((route) => pathname.startsWith(route));
const isRoot = pathname === "/";
const isAdmin = pathname === "/admin";
// Only load auth if we need to check authentication
if (isProtectedRoute || isAuthRoute || isRoot || isAdmin) {
const { auth } = await import("@/server/auth/config");
return auth((req) => {
const session = req.auth;
const { pathname } = req.nextUrl;
const isAuthenticated = !!session?.user?.id;
// Check if current path is protected
const isProtectedRoute = protectedRoutes.some((route) =>
pathname.startsWith(route)
);
// Check if current path is an auth route
const isAuthRoute = authRoutes.some((route) =>
pathname.startsWith(route)
);
// Protect routes that require authentication
if (isProtectedRoute && !isAuthenticated) {
const url = req.nextUrl.clone();
url.pathname = "/sign-in";
return NextResponse.redirect(url);
}
// If user is authenticated and trying to access auth routes, redirect to app
if (isAuthenticated && isAuthRoute) {
const url = req.nextUrl.clone();
url.pathname = "/app";
return NextResponse.redirect(url);
}
// If user is authenticated and on landing page, redirect to app
if (isAuthenticated && pathname === "/") {
const url = req.nextUrl.clone();
url.pathname = "/app";
return NextResponse.redirect(url);
}
// Prevent authenticated users from accessing admin panel
if (isAuthenticated && pathname === "/admin") {
const url = req.nextUrl.clone();
url.pathname = "/app";
return NextResponse.redirect(url);
}
return NextResponse.next();
})(req, { params: Promise.resolve({}) });
}
return NextResponse.next();
}
// Reduce matcher scope to only necessary routes
export const config = {
matcher: ["/", "/app/:path*", "/sign-in", "/sign-up", "/admin"],
};