import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(req) {
const isUser = req.nextauth.token?.user?.role === "user";
const isAdmin = req.nextauth.token?.user?.role === "admin";
if (req.nextUrl.pathname.startsWith("/admin") && !isAdmin) {
const url = new URL(isUser ? "/" : "/auth/signin", req.url);
url.searchParams.append(
"message",
"You are not authorized admin role needed!"
);
return NextResponse.redirect(url);
}
if (req.nextUrl.pathname.startsWith("/user") && !isUser && !isAdmin) {
const url = new URL(isUser ? "/" : "/auth/signin", req.url);
url.searchParams.append(
"message",
"You are not authorized user or admin role needed!"
);
return NextResponse.redirect(url);
}
},
{
callbacks: {
//true = user is authorized, false = not
authorized: ({ token }) => !!token,
},
}
);
//Routes this middleware runs for.
export const config = {
matcher: ["/user", "/admin/:path*"],
};