skip to Main Content

I’m currently working on a Next.js 14 project where I’m implementing permissions like User.Read and Role.Read using middleware to control user access to certain parts of the site. While this setup is functioning adequately, I’m facing a challenge in integrating the permissions obtained from middleware with my menu items, which are defined in a file named menu.tsx.

Here’s a simplified version of how my menu.tsx file looks:

// menu.tsx
export const Menu: MenuProps[] = [
  {
    href: '/dashboard',
    icon: <Gauge size={20} />,
    title: 'Dashboard',
  },
  // Other menu items...
];

The problem arises from the fact that permissions are received within the accessToken, which is stored in a secure, HTTP-only cookie. My goal is to dynamically display or hide menu items based on the permissions obtained from middleware.

My question is: How can I effectively pass the permissions obtained from middleware to the Menu constant array in my menu.tsx file?

2

Answers


  1. You could use a state management library like Zustand.
    For example, when your user logs in, you can fetch all the user permissions such as "view dashboard" and each time you render your menù, you can search if in the zustand state x user has y permission for that part of the menù.

    What i use in my application (not in the context of permission management) is something like this:

    export const useGlobals = create<Globals>((set, get) => ({
        user: undefined,
        setUser: (state: Object) => set({ user: state }),
    }));
    

    In your case you can simply append at the user object (or in a separate object) the user permissions.

    So in your middleware you can access this state and find if the user has or not the permission to access the required page.

    With this approach you have to think if permissions must be 100% of the time synchronized, if not you have to think when to refetch the user permissions (refetch the user permissions so that if they are edited you update your state)

    Login or Signup to reply.
  2. Option 1. If your access token is a JWT token you can parse on the frontend and access the permissions for the user.

    Option 2. If your permissions are stored in your api but are not included in the token you will need to create a new api call that returns the list of permissions available for that token.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search