# Protect route with role in React

**URL:** <https://community.auth0.com/t/protect-route-with-role-in-react/61289>\
**Category:** Get Help\
**Tags:** react, rules, roles, auth0\
**Created:** [April 17, 2021, 10:21pm UTC](https://community.auth0.com/t/protect-route-with-role-in-react/61289 "2021-04-17T22:21:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gidon](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/gidon/32/26192_2.png) [@gidon](https://community.auth0.com/u/gidon)\
**Post date:** [April 17, 2021, 10:21pm UTC](https://community.auth0.com/t/protect-route-with-role-in-react/61289/1 "2021-04-17T22:21:22Z")

</div>

I have setup a rule which injects roles into the `idTokenClaim`. I can now conditionally render components based on these roles but I would like to protect a route based on the roles. Is there a way to use `withAuthenticationRequired` but also require specific roles?

---

<div class="post-metadata">

**Author:** ![stephanie.chamblee](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/stephanie.chamblee/32/26087_2.png) [@stephanie.chamblee](https://community.auth0.com/u/stephanie.chamblee)\
**Post date:** [April 19, 2021, 12:33pm UTC](https://community.auth0.com/t/protect-route-with-role-in-react/61289/3 "2021-04-19T12:33:43Z")

</div>

Hi @gidon,

Welcome to the Community!

I don’t believe there is a built-in way to protect routes based on roles in the React SDK, however, I was able to find this example that a colleague wrote. This code creates a `withRoleBasedRedirect` wrapper for components. I haven’t tested this out, but hopefully this provides you with some ideas for your own implementation:

```auto
import React, { FC } from 'react';
import { ComponentType, useState, useEffect } from "react";
import { useHistory } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
export interface WithRoleBasedRedirectOptions {
  role: string;
}
const roleClaimType = 'https://demo.com/roles';
export const withRoleBasedRedirect = <P extends object>(
  Component: ComponentType<P>,
  options: WithRoleBasedRedirectOptions
): FC<P> => (props: P): JSX.Element => {
  const history = useHistory();
  const { getIdTokenClaims } = useAuth0();
  const [isAuthorized, setIsAuthorized] = useState(false);
  useEffect(() => {
    async function getRoles(): Promise<Array<string>> {
      const claims = await getIdTokenClaims();
      return claims[roleClaimType] || [];
    }
    async function checkRoles(role: string) {
      const roles = await getRoles();
      const isAuthorized = roles.includes(role);
      if (!isAuthorized) {
        history.push('/not-authorized');
      } else {
        setIsAuthorized(true);
      }
    }
    checkRoles(options.role);
  }, [getIdTokenClaims, history]);
  return isAuthorized ? <Component {...props} /> : <div></div>;
};

```

```auto
import React from "react";
import { Route } from "react-router-dom";
import { withAuthenticationRequired } from "@auth0/auth0-react";
import Loader from "../Loader/Loader";
import { withRoleBasedRedirect } from "../withRoleBasedRedirect/withRoleBasedRedirect";
export const ProtectedRoute = ({ component, role, ...args }: any) =>
  role ? (
    <Route
      component={withAuthenticationRequired(
        withRoleBasedRedirect(component, { role }),
        {
          onRedirecting: () => <Loader />,
        }
      )}
      {...args}
    />
  ) : (
    <Route
      component={withAuthenticationRequired(component, {
        onRedirecting: () => <Loader />,
      })}
      {...args}
    />
  );

```

route configuration:

```auto
<BrowserRouter>
  <ProtectedRoute path="/" exact role="Admin" component={UserPage} />
  <ProtectedRoute
      path="/not-authorized"
      exact
      component={NotAuthorized}
   />
</BrowserRouter>

```

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [May 4, 2021, 12:34pm UTC](https://community.auth0.com/t/protect-route-with-role-in-react/61289/4 "2021-05-04T12:34:35Z")

</div>

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