-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmiddleware.ts
More file actions
46 lines (38 loc) · 1.34 KB
/
middleware.ts
File metadata and controls
46 lines (38 loc) · 1.34 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
import { betterFetch } from "@better-fetch/fetch";
import { NextResponse, type NextRequest } from "next/server";
import type { Session } from "@/auth";
const authRoutes = ["/sign-in", "/sign-up"];
const passwordRoutes = ["/reset-password", "/forgot-password"];
const adminRoutes = ["/admin"];
export default async function authMiddleware(request: NextRequest) {
const pathName = request.nextUrl.pathname;
const isAuthRoute = authRoutes.includes(pathName);
const isPasswordRoute = passwordRoutes.includes(pathName);
const isAdminRoute = adminRoutes.includes(pathName);
const { data: session } = await betterFetch<Session>(
"/api/auth/get-session",
{
baseURL: process.env.BETTER_AUTH_URL,
headers: {
//get the cookie from the request
cookie: request.headers.get("cookie") || "",
},
},
);
if (!session) {
if (isAuthRoute || isPasswordRoute) {
return NextResponse.next();
}
return NextResponse.redirect(new URL("/sign-in", request.url));
}
if (isAuthRoute || isPasswordRoute) {
return NextResponse.redirect(new URL("/", request.url));
}
if (isAdminRoute && session.user.role !== "admin") {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};