Redirection Using JavaScript

A core principle of Single Page Web Applications (SPA) is things that used to live on the server now live in the browser. One of those responsibilities is managing redirections. For example when you make an AJAX call to a secure service and without a valid authorization token. The service should return a 401 status code. When receiving a 401 status code the application should redirect the user to the login address.

Javascript browser redirection

In classic web development the AJAX request would have been a page request or postback. The server recognizes the unauthorized state and performs the proper redirect server-side. In ASP.NET we do this with the response.redirect function.

In a SPA the client application’s code needs to manage the redirect. I have encountered two common scenarios; redirecting to an external party or (secure token server) STS or to the application’s login view. The internal redirection is fairly easy, change the hash fragment’s route to the login view.

window.location.hash = '#!login';

If you are familiar with single page applications you will recognize this as a programatic way to trigger navigation changes.

Remember when redirecting due to stale or missing authentication token you are most likely using active authentication and need to persist the authentication token somewhere, like localStorage. If you are using passive authentication the page will post back to the authentication server and the token returned, typically in the header.

Redirecting to an STS normally involves changing the browser’s address from the SPA URL to the authentication URL. The STS URL is most likely on a completely different domain, server, etc. Whatever the case may be the location must change. Most developers’, me included, first reaction is to set the location.href property to the new URL. Doing this is disappointing because nothing happens. The href is a read-only property.

To change the browser’s address you must use the location.redirect function. This causes the browser to load the new URL.


Now the browser loads the new target. In this scenario the user then logins using the STS and return to the application authenticated.

Authentication is one scenario you might find yourself needing to programatically redirecting the user. Of course there are many other scenarios where you might need to redirect a user either internally or externally in the course of normal application usage. When you can use an anchor tag you should avoid managing navigation in code as much as possible. But when you do need this control these are the two ways to handle common redirection needs in web applications, setting the window.location.hash value or passing a URL to the window.location.redirect function.