-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
77 lines (58 loc) · 2.27 KB
/
middleware.ts
File metadata and controls
77 lines (58 loc) · 2.27 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, type NextRequest } from "next/server";
// import { getSessionCookie } from "better-auth/cookies";
// const protectedRoutes = ["/tools", "/learn", "/Quiz", "/dashboard"];
// function isProtectedPath(pathname: string) {
// return protectedRoutes.some(
// (route) => pathname === route || pathname.startsWith(`${route}/`)
// );
// }
// export async function middleware(request: NextRequest) {
// const { pathname, search } = request.nextUrl;
// // CRITICAL: Never intercept auth routes — not even for a millisecond
// // The state cookie must flow through untouched
// if (pathname.startsWith("/api/auth")) {
// return NextResponse.next();
// }
// if (!isProtectedPath(pathname)) {
// return NextResponse.next();
// }
// // Use cookie check ONLY — zero DB calls, zero latency
// // This reads the session cookie header directly
// const sessionCookie = getSessionCookie(request);
// if (!sessionCookie) {
// const signInUrl = new URL("/signin", request.url);
// signInUrl.searchParams.set("next", `${pathname}${search}`);
// return NextResponse.redirect(signInUrl);
// }
// return NextResponse.next();
// }
// export const config = {
// matcher: [
// // Explicitly exclude /api/auth/* at the matcher level as well
// "/((?!api/auth|_next/static|_next/image|favicon.ico).*)",
// ],
// };
import { NextResponse, type NextRequest } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
const protectedRoutes = [ "/dashboard"];
export async function middleware(request: NextRequest) {
const { pathname, search } = request.nextUrl;
// Auth routes must NEVER be touched by middleware
if (pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
const isProtected = protectedRoutes.some(
(r) => pathname === r || pathname.startsWith(`${r}/`)
);
if (!isProtected) return NextResponse.next();
const sessionCookie = getSessionCookie(request);
if (!sessionCookie) {
const signInUrl = new URL("/signin", request.url);
signInUrl.searchParams.set("next", `${pathname}${search}`);
return NextResponse.redirect(signInUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico).*)" ],
};