title: NextJS screen flicker on authentication check using localstorage
body: <p>I am authenticating my NextJS frontend from a backend that gives me an <code>accessToken</code> on a successful email / password login (Laravel Sanctum). From there I am saving that accessToken in local storage.</p>
  <p>If i have a page that needs protecting, for instance <code>/profile</code>, i need to verify that the token is valid before showing the page. If it is not valid, they need to be redirected to the <code>/signin</code> page. So i have the following code which does that.</p>
  <pre><code>import { useRouter } from 'next/router';
  import { useEffect } from 'react';
  
  export default function Profile() {
      const router = useRouter();
  
      useEffect(async () =&gt; {
          const token = localStorage.getItem('accessToken');
  
          const resp = await fetch('https://theapiuri/api/user', {
              method: 'GET',
              headers: {
                  'Authorization': 'Bearer ' + token
              }
          });
  
          const json = await resp.json();
  
          if (!token &amp;&amp; json.status !== 200) {
              router.push('/signin');
          }
      })
  
      return (
          &lt;div&gt;
              &lt;h1&gt;Protected Profile Page&lt;/h1&gt;
          &lt;/div&gt;
      )
  }
  </code></pre>
  <p>It works, sort of. If I am logged out, and i try to visit <code>/profile</code> it will flash up the profile page for a second or so and then redirect to signin.</p>
  <p>This doesn't look good at all. I was wondering if anyone in the same situation could share their solution, or if anyone has some advice that would be greatly appreciated.</p>