-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathmiddleware.ts
60 lines (51 loc) · 1.47 KB
/
middleware.ts
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
import { type NextRequest, NextResponse } from "next/server";
import { createAuthClient } from "better-auth/client";
const client = createAuthClient();
// Public routes that don't require authentication
const publicRoutes = [
"/login",
"/signup",
"/signup/verify",
"/",
"/privacy",
"/terms",
"/api/auth/early-access",
];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if the current path is a public route
const isPublicRoute = publicRoutes.includes(pathname);
// For non-public routes, check authentication
if (!isPublicRoute) {
const { data: session } = await client.getSession({
fetchOptions: {
headers: {
cookie: request.headers.get("cookie") || "",
},
},
});
if (!session) {
return NextResponse.redirect(new URL("/login", request.url));
}
}
// Handle existing rate limiting for early access
if (pathname === "/api/auth/early-access") {
const ip = request.headers.get("x-forwarded-for");
if (!ip) {
return NextResponse.json(
{
success: false,
error: "Could not determine your IP address, please try again later!",
},
{ status: 400 },
);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
// Match all paths except static files and api routes (except early-access)
"/((?!_next/static|_next/image|favicon.ico|api(?!/auth/early-access)).*)",
],
};