Role-Based routing on my Next.js application

Hey community.
I’m trying to have different routes for admins and users on my Next.js app.
I have two main routes. /admin/* and /dashboard/*. I have some Rules on my Auth0 application that adds the user role to its claims.
Now on my application, I want to limit users. So the normal users can’t access admin routes.

I don’t want use useUser hook on the client-side and do the redirect if their role is not Admin. I want to do in a more cleaner way so users don’t see a glimpse of admins pages and then get redirected to other routes. I want to do it on the server-side.
I thought maybe using middlewares could be a good option for me. But I wasn’t successfule.
Here’s the simple code on my middleware.

export default withMiddlewareAuthRequired(async function middleware(req) {
    const res = NextResponse.next();
    const { user } = await getSession(req, res) as Session;
    const userRoles = getUserRoles(user as UserProfile)
    const requestedPath = req.nextUrl.pathname

    if(requestedPath.includes("admin") && userRoles.includes(UserRoles.ADMIN)){
        return res
    } else {
        NextResponse.redirect(new URL("/dashboard", req.url))
    }
});

export const config = {
    matcher: ['/admin/:path*', '/dashboard/:path*'],
}

Do you have any idea why it’s not working? Or even do you have a better way to achieve it?

Hi @bardiya

Welcome to the Auth0 Community!

I am sorry about the late reply to your post!

If you still need assistance with your issue or for anybody else who may wonder, I would recommend to review the following community post:

For more information on the matter, you can review this knowledge article and this post from StackOverflow which addressed the same issue.

If you have any other questions, feel free to reply or to post again on the community.

Kind Regards,
Nik