Hi @binh,
I am glad this has worked well so far, but indeed there are a few other additions to be made.
You are right, the problem lies in the fact that the appState from the initial login is not automatically carried over to the second, silent loginWithRedirect call. Each loginWithRedirect is a new, isolated transaction.
The easiest and most reliable way to solve this is to manually persist the returnTo path across the redirects using the browser’s localStorage or sessionStorage.
First, you need to capture the appState from the first login attempt and save it before it gets lost. You can do this in a custom onRedirectCallback function provided to your Auth0Provider .
This function will intercept the appState and save its returnTo property to sessionStorage . It will also handle the final redirection at the end of the entire process.
// You could implement something similar to this
const onRedirectCallback = (appState) => {
// Check if the appState from the login has a returnTo path.
if (appState?.returnTo) {
sessionStorage.setItem('auth_return_to', appState.returnTo);
}
navigate(sessionStorage.getItem('auth_return_to') || window.location.origin);
};
You then need to ensure your Auth0Provider uses this function by passing it as a property: onRedirectCallback={onRedirectCallback} .
You will also need to modify your /callback component to retrieve the path you just saved.
Inside the useEffect hook in your /callback component, retrieve the stored value:
const returnTo = sessionStorage.getItem('auth_return_to');
Then, inject this value back into the appState of the silent loginWithRedirect call. This explicitly tells the Auth0 SDK where the user should be sent after this second, final authentication is complete.
loginWithRedirect({
appState: {
// Re-apply the original intended path here
returnTo: returnTo || '/'
},
authorizationParams: {
organization: newOrgId,
},
});
By following these steps, you create a chain that preserves the user’s original destination across both redirects, ensuring they land on the correct page after the seamless organization assignment is complete.
I hope this helps, so you can let me know how it goes and if you have other questions!
Thank you,
Remus