Next.js Discord

Discord Forum

Need Help with Role-Based Routing in Next.js 14 App Using NextAuth

Unanswered
hojomojo posted this in #help-forum
Open in Discord
Hey everyone,

Next.js 14 I’m facing an issue with role-based routing using NextAuth. I’ve set up roles for users and admins, and while the user paths are working fine, I’m running into trouble with the admin routes. Even though the user has the admin role, accessing the admin path redirects to an unauthorized page.
When I check the console, the user role is correctly shown as admin, but I still get redirected to the /unauthorized page when trying to access the admin route.

Role-Based Routing Logic for protecting routes based on roles.
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";
export const config = {
matcher: [
"/",
"/add-student",
"/profile",
"/settingsPage",
"/approvals",
"/enrolments",
"/courses",
"/students",
"/student-details/:id*",
],
};

// Middleware function to handle role-based routing
export async function middleware(req) {
const token = await getToken({ req });
const url = req.nextUrl.clone();

if (!token) {
// Redirect to sign-in page if not authenticated
url.pathname = "/auth/signin";
return NextResponse.redirect(url);
}

const userRole = token.role;
console.log("🚀 ~ middleware ~ userRole: admin...........", userRole);
const path = req.nextUrl.pathname;

// Define role-based access rules
const adminPaths = [
"/",
"/approvals",
"/students",
"/courses",
"/add-student",
"/student-details",
];

const userPaths = ["/", "/profile", "/settingsPage", "/enrolments"];

// Check if the path is restricted to admin users
if (
adminPaths.some((p) => path.startsWith(p)) &&
userRole !== "SUPER_ADMIN"
) {
url.pathname = "/unauthorized";
return NextResponse.redirect(url);
}
if (
userPaths.some((p) => path.startsWith(p)) &&
userRole !== "TRAINING_PARTNER"
) {
url.pathname = "/unauthorized";
return NextResponse.redirect(url);
}
return NextResponse.next();
}

0 Replies