Auth0 React SPA onRedirectCallback redirection solution

Hey everyone,

I’ve just started using Auth0 so I’m fairly new to all of this. I followed the React SPA tutorial and then ran into some issues down the line when using routes. When I logged in from a route, I wanted to be redirected there. This wasn’t working at all and I couldn’t work out why.

For those that are stuck with this issue, you need to make use of appState when users log in. If you followed the tutorial like I did, you will have this bit of code in your main index.js file:

const onRedirectCallback = appState => {
  history.push(
    appState && appState.targetUrl
      ? appState.targetUrl
      : window.location.pathname
  );
};

This code is correct, but it will always redirect to window.location.pathname (which translates to http://localhost:3000 in your local environment) if appState is undefined. You need to define appState and a targetUrl somewhere to get the correct redirect.

This can be done like this:

loginWithRedirect({ appState: { targetUrl: window.location.pathname } });

If you use that method when logging in, you will be properly redirected after logging in. I hope this helps someone else down the line!

Thanks for posting this solution!

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