I am working on a react app using react-router-dom. The default app behaviour is making the user navigate through a sequence of forms , fill them , validate the information submitted and complete signing up. In order to prevent the users from jumping between pages and directly accessing the signup page before all required forms are submitted, I am passing a prop to navigation as shown below.
navigate("pathName", { state: { valid: true } });
Inside the corresponding component , I decode the state value like this :
const location = useLocation();
valid = location.state && location.state.valid
This way if a user directly manipulates the url in browser, the location specific prop will not be present and valid
would evaluate to false. In that case , I immediatly take them back to the previous page.
This setup works fine for blocking direct url manipulation and only allows programatic navigation. But the problem is, for one particular flow the app takes users to auth0 -> makes them login and then redirect them back to the app after successful login. But since I have blocked direct url manipulation, the call from auth0 gets blocked too and user is taken back to the auth0 login page.
How can I distinguish a normal browser url manipulation from a auth0 callback, so that I can let the latter go through ?
I eventually ended up doing this by creating a custom hook which would be loaded every time user navigates to a new page and if that is a page where direct navigation is not allowed , user would then be taken back to the landing page.
Since all my routes are defined on a single react component I only had to call the hook in one component.
export function useNav(isValidNav) {
const navigate = useNavigate();
const currentPath = window.location.pathname.substring(1),
isDirectNavAllowed =
currentPath === PAGE_X ||
currentPath === PAGE_Y ||
useEffect(() => {
if (isValidNav !== true && isDirectNavAllowed !== true) {
navigate("/", { replace: true });
}
}, [isValidNav]);
}
isValidNav is a prop that is passed through the state component of navigate hook , if a redirect to a page happened properly( i.e by interacting with the web app correctly rather than editing the url)
navigate(`/${pathname}`, { state: { isValidNav: true } });