How can I get user roles client side?

Hi, I’m new to using Auth0 sos still trying to get an understanding of how things work.

What i’m wanting to do is conditional checks client-side which will show/hide certain content depending on authenticated user roles.

All users will either have a role of default or admin set. If a users role is admin, then the conditional will pass using something like the below.

Is there away to get role data set on a user through useUser? if not, is there a different or better way to achieve what i’m trying to do?

This is for a Nextjs project.

    const { isLoading, error, user } = useUser();

    if (isLoading) return <div>Loading...</div>;
    if (error) return <div>{error.message}</div>;

if (user.roles.includes('admin')) {
  console.log('User is an admin.');
  // Perform admin-specific actions here
} 

Thanks in advance!

Hey @luke2 welcome to the community!

Have you tried adding roles to tokens? In this case you’d want to focus on the ID token in particular:

roles should then be available via the useUser hook.

Yeah I managed to get it working in the end with

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'roleType';
  
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}`, event.authorization.roles);
    api.accessToken.setCustomClaim(`${namespace}`, event.authorization.roles);
  }
}
1 Like

That’s great, thanks for confirming!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.