-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.ts
53 lines (44 loc) · 1.21 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const verifyToken = async (token: string | undefined) => {
if (!token) return false;
const user = await fetch(`${process.env["NEXT_PUBLIC_API_URL"]}/auth`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => res.json())
.then((data) => {
if (data.auth) return true;
return false;
});
return user;
};
const matcher = [
"/sign-up",
"/login",
"/dashboard/:path",
"/poll/:path",
"/my-polls",
"/create",
];
const freeRoutes = ["/sign-up", "/login", "/"];
const protectedRoutes = ["dashboard", "my-polls", "create", "poll"];
export async function middleware(request: NextRequest) {
const token = request.cookies.get("token");
const user = await verifyToken(token);
if (!user) {
if (protectedRoutes.includes(request.nextUrl.pathname.split("/")[1])) {
return NextResponse.redirect(new URL("/", request.url));
}
} else {
if (freeRoutes.includes(request.nextUrl.pathname)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher,
};