-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.jsx
32 lines (28 loc) · 998 Bytes
/
middleware.jsx
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
import { tokenDecoder } from "@/utils";
import { NextResponse } from "next/server";
export const middleware = async (request) => {
const { pathname } = request.nextUrl;
const token = request.cookies.get("user_token")?.value;
const isUserPath = "/my-order" == pathname || "/cart" == pathname || "/login" == pathname;
if (isUserPath) {
if (pathname == "/login" && token) {
return NextResponse.redirect(new URL("/", request.nextUrl));
} else if (token) {
return NextResponse.next();
} else if (pathname != "/login") {
return NextResponse.redirect(new URL("/login", request.nextUrl));
}
}
const isAdminRoute = pathname.includes("/admin");
if (isAdminRoute) {
const user = await tokenDecoder(`Bearer ${token}`);
if (user && user.role == "admin") {
return NextResponse.next();
} else {
return NextResponse.redirect(new URL("/", request.nextUrl));
}
}
};
export const config = {
matcher: ["/:path*", "/admin/:path*"],
};