how can I protect private routes by roles. That is, if I am a user type "user" I can have access to the /normal route and if I am admin I can have access to the /admin route. That is, multiple private routes with specific roles, the official documentation only shows an example of a single role for a single route. but what I want is to make it multiple.
middleware.ts
import { withAuth } from "next-auth/middleware"
export default withAuth(
// `withAuth` augments your `Request` with the user's token.
function middleware(req) {
console.log(req.nextauth.token)
},
{
callbacks: {
authorized: ({ token }) => token?.role === "admin",
},
}
)
export const config = { matcher: ["/admin"] }
Here is the code extracted from the official next-auth documentation https://next-auth.js.org/configuration/nextjs
what I want is that export const config = { matcher: ['/dashboard'] };
applies to that callback type "user" but I want to make more protected routes depending on the user's role
I am using nextjs 14
Make your middleware apply to both routes and check in your
authorizedcallback which one is being accessed. Then resolve the required roles based on the paths.A very simple setup could look like this: