- Which SDK this is regarding: auth0-react
- SDK Version: v1.6.0
- Platform Version: React 17
The SDK docs/samples mention that Auth0Provider
should wrap the React Router
element
(auth0-react/EXAMPLES.md at master · auth0/auth0-react · GitHub):
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{/* Don't forget to add the history to your router */}
<Router history={history}>
<Switch>
<Route path="/" exact />
<ProtectedRoute path="/profile" component={Profile} />
</Switch>
</Router>
</Auth0Provider>
This forces us (the SDK users) to create history
object manually and then pass it to both Auth0Provider
and to the Router
, so that we’ll be able to manipulate the same version of history on authentication redirects (again, as explained in the docs).
It seems to be possible to reverse the order of nesting, having Auth0Provider
wrapped by the default BrowserRouter
. This allows us to create custom wrapper over Auth0Provider
with access to the built-in history object via useHistory
hook:
export const AppAuthentication: React.FC = (props) => {
const history = useHistory();
const onRedirectCallback = (appState: AppState) => {
history.replace(appState?.returnTo || window.location.pathname);
};
return (
<Auth0Provider
domain={...}
clientId={...}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
{props.children}
</Auth0Provider>
);
};
The usage is simpler now -
const App: React.FC = () => {
return (
<Router>
<AppAuthentication>
....
</AppAuthentication>
</Router>
);
};
I’ve did some quick testing, and it seems to be working fine. Is there a reason not to follow this approach? It seems to be cleaner than maintaining own history copy…
Regards,
Anton.