Next.js Discord

Discord Forum

What's the simplest and more scalable way to protect pages based on role?

Black carp posted this in #help-forum
Open in Discord
Black carpOP
I have a Next.js app with NextAuth.js authentication with the CredentialsProvider, I have the roles of my users saved on the database in the User table and I'm accessing the role of a logged in user in the session object already.

I have also set a middleware.ts file that protects all the routes based on if a user is logged in or not, and now I want to add role-based authorization.

I don't want to validate every single page with something like session?.user?.role === 'ADMIN', but also don't want to create new routes for /admin and /user as I don't want to pollute the URLs.

Is there a way to achieve role-based authorization in the middleware that does it "automatically"?

For example, setting explicitly that certain roles can only access certain pages, maybe in an array syntax.

If not, what solution would you recommend?

Thanks for your time!

1 Reply

you want to do something like this?

import {withAuth} from "next-auth/middleware"

export default withAuth(
    function middleware(req) {
        // only token.role === 'admin' can enter here
        console.log('in middlewareHeader: ', req.nextauth.token)
        callbacks: {
            authorized: ({token}) => {
               console.log('in authorized: ', token)
               return token?.role === "admin"