-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
46 lines (41 loc) · 1.31 KB
/
middleware.js
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 { NextResponse } from "next/server";
import { cookies } from "next/headers";
export function middleware(request) {
const AuthToken = cookies().get("authToken")?.value;
if (
request.nextUrl.pathname === "/api/login" ||
request.nextUrl.pathname === "/api/signup" ||
request.nextUrl.pathname === "/api/post" ||
request.nextUrl.pathname === "/api/check-email" ||
/^\/api\/post\/\w+$/.test(request.nextUrl.pathname)
) {
return null;
}
const loggedInUserNotAccessPath =
request.nextUrl.pathname === "/login" ||
request.nextUrl.pathname === "/register";
if (loggedInUserNotAccessPath) {
// if user is logged in, redirect to home page
if (AuthToken) {
return NextResponse.redirect(new URL("/", request.nextUrl));
}
} else {
// if user is not logged in, redirect to login page
if (!AuthToken) {
if (request.nextUrl.pathname.startsWith("/api")) {
return NextResponse.json(
{ error: "You are not authorized" },
{ status: 401 }
);
} else if (
!AuthToken &&
request.nextUrl.pathname.startsWith("/add-blog")
) {
return NextResponse.redirect(new URL("/login", request.nextUrl));
}
}
}
}
export const config = {
matcher: ["/", "/login", "/register", "/add-blog", "/api/:path*"],
};