Implementing Auth0 Protected Routes using React Router v6...?

Hello Friends,

I’m wondering if there’s anyone who could please provide a resource on how to implement Auth0 Protected Route functionality using React Router v6?

The Auth0 React tutorial that currently exists, while very while authored, appears to be for React Router version 5 or earlier. Hence, it does not appear to work for those of us who are using v6. I have tried to make the logical updates that one would expect going from RR v5 to v6, such as using “Navigate to” instead of “Redirect,” using “element=” instead of “component=”, and changing how I wrap routes using “ProtectedRoute”, but I still cannot get things to work properly…

The errors I receive when trying to implement Protected Routes using the guide vary from
“A is only ever to be used as the child of element, never rendered directly. Please wrap your in a . protected route” to

“Error: [ProtectedRoute] is not a component. All component children of must be a or <React.Fragment>”

The errors vary depending on what change I’m attempting to implement in going from v5 to v6 using the current guide.

If anyone has a code sample or guide on how to use Auth0 with RR v6, I would be very grateful. Thanks…!

1 Like

Note- I just saw in the comments for the Auth0-React guide that the author (Dan) is planning to update the guide for React Router v6 in early 2022. Therefore, I will be patient and happily await his updates!

1 Like

Hey Rob,

In my team we recently ran into this problem and our strategy goes something like this:

const App => 
  <Routes>
    <Route path="some-path" element={<ProtectedComponent component={SomePrivateView} aProps={prop1} anotherProp={prop2} />} />
    ...more routes
  </Routes>

SomePrivateView is the component function. i.e.:

const SomePrivateView = (props) =>  <>something</>

In ProtectedComponent we let withAuthenticationRequired to the redirection if needed:

const ProtectedComponent = ({ component, ...propsForComponent}) => {
  const Cp = withAuthenticationRequired(component);
  return <Cp {...propsForComponent} />
}

For the moment, this has been enough. Hope this helps someone also looking to upgrade.

Regards,
Juan Carlos

2 Likes

Thanks Juan Carlos this works a treat!

1 Like

@jcespinoza

Apologies sir for the late response, as I got locked up in another, totally unrelated area.

Indeed - thank you for posting this. This is great, and it works…!

Just as a follow- up question… do you or anyone else happen to have any idea on how to do a redirect to another page in the case of the login attempt failing?

Auth0 appears to use a module called withAuthenticationRequired() to handle this, but it’s sort of a blackbox to me, and I can’t really find any detailed documentation on how it works. Therefore, I have no idea how to set the redirect page to something else…? The example given in the React guide is for React Router v5 only…

Thanks,