-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
34 lines (25 loc) · 913 Bytes
/
middleware.ts
File metadata and controls
34 lines (25 loc) · 913 Bytes
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
import NextAuth, { Session } from "next-auth";
import authConfig from "./auth.config";
import { NextResponse } from "next/server";
export const { auth } = NextAuth(authConfig);
const isProtectedRoute = (auth: Session | null, path: string) => {
if (path.startsWith("/admin") && auth?.user.role !== "ADMIN") {
return { shouldRedirect: true, path: "/" };
}
if (path.startsWith("/user") && !auth) {
return { shouldRedirect: true, path: "/" };
}
return { shouldRedirect: false, path: "/" };
};
export default auth((req) => {
const path = req.nextUrl.pathname;
const isAuth = req.auth;
const { shouldRedirect, path: redirectPath } = isProtectedRoute(isAuth, path);
if (shouldRedirect) {
return NextResponse.redirect(new URL(redirectPath, req.url));
}
return NextResponse.next();
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};