How can I create routes by roles with next-auth/authjs nextjs/13/14?

289 Views Asked by At

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

1

There are 1 best solutions below

0
Minn On

Make your middleware apply to both routes and check in your authorized callback which one is being accessed. Then resolve the required roles based on the paths.

A very simple setup could look like this:

const AUTH_CONFIG = {
  '/admin': 'admin',
  '/normal': 'user',
};

export default withAuth(
  {
    callbacks: {
      authorized: ({ token, req }) => {
        const requiredRole = AUTH_CONFIG[req.nextUrl.pathname];
        return !requiredRole || token?.role === requiredRole;
      },
    },
  }
)

export const config = { matcher: ["/(admin|normal)"] }