Client Side Redirects

Using window.location.href = 'https://example.com' seems like a normal synchronous operation, but this is not the case. Any code after this statement will still run while the browser is downloading the page. Only after the browser has nothing on the stack and the download has completed, the current page will be unloaded and the new page will be loaded. Setting window.location.href again during this window will result in the download of the page being canceled, and a new download being queued with the new page.

Recently, I experienced a bug regarding this:

  • I have a timer running every 15 seconds that checks if the user is logged out by checking some value in session storage. If this is the case, it will redirect to a logged-out page via a client-side redirect.
  • I also have a logout button. This button will first clear the local storage and then submit a form with details for the backend regarding logout. The backend will then redirect to a logged-out page via a server-side redirect. When pressing the logout button, the form will submit and will in a similar way download the page to which it will navigate before unloading the current page.

Now, if the timer interval occurs between the button click and the unloading of the page, it will override redirect from the form post with the redirect from the timer interval callback, which is not the right behavior in this case. The fix was to cancel the timer on button click.

Even though these client-side redirects are asynchronous, they are not promises. So, one cannot await them. If you are doing these client-side redirects, make sure to handle the case where the code continues to execute before loading the new page to prevent errors. You could make use of a timeout for redirection for example, or set a flag that prevents execution of code harmful to the redirect. Also be aware that race conditions can occur.

Mirror gitlab to github over sshImmutable updates