How can I redirect to previous page of my guarded auth0 path in React?

Viewed 162

I am currently following this auth0 guide to protect my routes. If a user enters my guarded path, it will correctly lead me to my auth0 universal login page. However, if for 'x' reason a user decides to click on the browser's back button, it will return to the guarded path which will once again redirect me to the auth0 universal login page! I would be creating a ProtectedRoute component similar to the tutorial:

<Route
    component={withAuthenticationRequired(component, {
      onRedirecting: () => <Loading />,
    })}
    {...args}
/>

Is there a way for me to redirect to the previous page before reaching the guarded path when I click on the browser's back button?

What I had in mind was to call a 'componentWillMount' function to check if the page was reached by calling the back button and then I would call history.push('/');

const useWillMount = (fn) => {
    const willMount = useRef(true);

    if (willMount.current && fn && typeof fn === 'function') {
      fn();
    }

    willMount.current = false;
};

useWillMount(() => {
    if (
      String(window.performance.getEntriesByType('navigation')[0].type) ===
      'back_forward'
    ) {
      history.push('/');
    }
});

Using this, it correctly redirects to the home page. However, after a few milliseconds, it immediately throws me back to auth0 universal login page. (I believe this happens because it renders the ProtectedRoute component even though I called the history.push). Am I going towards the correct path, or am I completely lost here?

1 Answers

I'm more experienced with Vue than React so I can't comment on exact implementation but would an approach like this be suitable:

  1. Each time a non-logged in user navigates to a non-protected page, the path is stored as the page key in local storage
  2. User navigates to protected route while not logged in.
  3. If it does not exist, key called route_guard_accessed is stored in local storage and they are redirected to the login.
  4. If user is redirected back to a protected page, and route_guard_accessed key exists in local storage, redirect them to the page stored in path key.
  5. If user was redirected back to their old, non-protected page and route_guard_accessed key exists, then delete it from local storage.

In essence, you log the last non-protected page a non-logged-in user accesses. You also log when they attempt to access a protected page. If they access the protected page and they don't have the route_guard_accessed key in local storage, they are redirected to login. If they do, they are redirected back to their last non-protected page and the route_guard_accessed key is destroyed.

Related