title: Next.js: How to prevent flash of the Unauthorized route/page prior to redirect when implementing a private route?
body: <p>Essentially I created a HOC for two pages in my Next.js app (i.e. <code>profile</code> and <code>dashboard</code>) two prevent users from accessing them if they're not authorized.</p>
  <p>Example: <code>pages/profile.js</code></p>
  <pre><code>import withAuth from &quot;../components/AuthCheck/index&quot;;
  
  function Profile() {
    return (
      &lt;&gt;
        &lt;h1&gt;Profile&lt;/h1&gt;
      &lt;/&gt;
    )
  }
  
  
  export default withAuth(Profile);
  </code></pre>
  <p>My Auth component/HOC:</p>
  <pre><code>import { useRouter } from 'next/router'
  import { useUser } from '../../lib/hooks'
  import { PageLoader } from '../Loader/index'
  
  const withAuth = Component =&gt; {
    const Auth = (props) =&gt; {
      const { isError } = useUser(); //My hook which is calling /api/user see if there is a user
      const router = useRouter()
  
  
      if (isError === 'Unauthorized') {
        if (typeof window !== 'undefined' &amp;&amp; router.pathname === '/profile' || router.pathname === 'dashboard') router.push('/login')
  
        return &lt;PageLoader /&gt;
      }
      return (
        &lt;Component {...props} /&gt;
      );
  
    };
  
    if (Component.getInitialProps) {
      Auth.getInitialProps = Component.getInitialProps;
    }
  
    return Auth;
  };
  
  export default withAuth;
  </code></pre>
  <p>Now what is happening is if you happen to enter <code>/profile</code> or <code>/dashboard</code> in the browser URL bar, before the redirect you'll see the page for a second i.e. flash.</p>
  <p>Any idea why that is happening?</p>