-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
58 lines (48 loc) · 1.33 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
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Bypass all static files from the middleware
if (pathname.match(/\.(svg|png|jpg|jpeg|gif|ico|json)$/)) {
return NextResponse.next();
}
const unProtectedRoutes = [
"/",
"/auth/login",
"/auth/signup",
"/auth/logout",
"/auth/verifyemail",
"/auth/emailverificationalert",
"/api/auth/verifyemail",
"/api/auth/login",
"/api/auth/signup",
"/faq",
"/contactus",
"/api/contactus",
];
if (unProtectedRoutes.includes(pathname)) {
return NextResponse.next();
}
const token = request.cookies.get("token")?.value;
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/auth/me`,
{
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
},
);
const data = await response.json();
if (!data.success) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
return NextResponse.next();
} catch (error) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};