TanStackT
TanStack2y ago
46 replies
urgent-maroon

[RACE CONDITION] Auth0 Redirect and Context

Is there a way I can put my Auth0 State into my Router Context and be able to use useNavigate() in order to redirect back to routes a user is trying to access?

I'm trying to use useAuth0 and
useNavigate
but RouterProvider is waiting for its context from useAuth0 and
useNavigate
that is being used inside of the Auth0ProviderWithRedirect needs to be within RouterProvider

Here is their example with react-router https://github.com/auth0/auth0-react/blob/main/EXAMPLES.md#protecting-a-route-in-a-react-router-dom-v6-app

Any extra pair of 👀 would be helpful

function Auth0ProviderWithRedirect({ children, ...props }: Auth0ProviderWithRedirectProps) {
  const navigate = useNavigate(); // <-- Needed to redirect a user back to a page they are trying to navigate to while unauthorized
  const onRedirectCallback: Auth0ProviderOptions['onRedirectCallback'] = (
    appState,
  ) => {
    navigate({ to: appState?.returnTo || window.location.pathname });
  };

  return (
    <Auth0Provider {...props} onRedirectCallback={onRedirectCallback}>
      {children}
    </Auth0Provider>
  );
}


function InnerApp() {
  const auth = useAuth0(); // <-- needed to populate my context
  return <RouterProvider router={router} context={{ auth }} />;
}

function App() {
  return (
    <Auth0ProviderWithRedirect
      domain={...}
      clientId={...}
      authorizationParams={{
        redirect_uri: '...',
        audience: '...',
      }}
    >
      <InnerApp />
    </Auth0ProviderWithRedirect>
  );
}
GitHub
Auth0 SDK for React Single Page Applications (SPA) - auth0/auth0-react
auth0-react/EXAMPLES.md at main · auth0/auth0-react
Was this page helpful?