title: Best way to prevent unauthorized user on Angular site from seeing site for a split second before being redirected to login?
body: <p>I am currently building an Angular front end on a site that pulls much of its data from an API that requires authorization via login.</p>
  
  <p>I have built the following authInterceptor that works well and redirects users to the login page if a 401 error is sent from the server:</p>
  
  <pre><code>angular
    .module('myApp.services')
    .factory('authInterceptor', ['$rootScope', '$q', '$window', '$location', function($rootScope, $q, $window, $location) {
  
      return {
          'request': function(config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
              config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
  
            return config;
          },
          'response': function(response) {
            return response || $q.when(response);
          },
          responseError: function(rejection){
            if (rejection.status == 401){
              $location.path('#/login');
            }
            return $q.reject(rejection);
          }
  
        };
    }])
  </code></pre>
  
  <p>The problem with this is that the API calls and therefore, the 401 errors don't occur until the end of the page load process -  so, users can see a split second of all of the elements (e.g., HTML, CSS, images and all other elements that don't hit the API) loading up on my page before the application hits the API and gets the 401.</p>
  
  <p>I've worked around this by putting a random API call right at the beginning of my MainController that doesn't really do anything but this seems like the wrong way to do it since I'm making an unnecessary ping to the server. Any suggestions and best practices around this?</p>
  
  <p>Also, when I do hit those unauthorized routes, I get the ugly 401 error messages in my console - is there a way to do this redirect without displaying those to the user or is this normal?</p>