-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmiddleware.ts
42 lines (33 loc) · 1.01 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
// see https://nextjs.org/docs/advanced-features/middleware for more information.
import type { NextRequest } from "next/server";
import { Role } from "@prisma/client";
import { NextResponse } from "next/server";
import { getIronSession } from "iron-session/edge";
import { sessionOptions } from "@Lib/config";
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
const session = await getIronSession(req, res, sessionOptions);
const { user, guest } = session;
if (!guest) {
session.guest = {
id: "guest",
cart: [],
wishlist: [],
};
await session.save();
}
if (req.nextUrl.pathname.startsWith("/signin")) {
if (user) {
return NextResponse.redirect(new URL(req.url).origin);
}
}
if (req.nextUrl.pathname.startsWith("/admin")) {
if (!user || user.role != Role.ADMIN) {
return NextResponse.redirect(new URL(req.url).origin);
}
}
return res;
}
export const config = {
matcher: ["/signin", "/admin/:path*", "/(.*)"],
};