title: Protect Routes/Pages with NextJs
body: <p>I have a simple project that I built that protects the routes/pages of the website by using the if and else statement and putting each page with a function <code>withAuth()</code>, but I'm not sure if that is the best way to protect routes with nextjs, and I noticed that there is a delay in protecting the route or pages, like 2-3 seconds long, in which they can see the content of the page before it redirects the visitor or unregistered user to the login page.</p>
  <p>Is there a way to get rid of it or make the request faster so that unregistered users don't view the page's content? Is there a better approach to safeguard a certain route in the nextjs framework?</p>
  <h1>Code</h1>
  <hr />
  <pre><code>import { useContext, useEffect } from &quot;react&quot;;
  import { AuthContext } from &quot;@context/auth&quot;;
  import Router from &quot;next/router&quot;;
  
  const withAuth = (Component) =&gt; {
    const Auth = (props) =&gt; {
      const { user } = useContext(AuthContext);
  
      useEffect(() =&gt; {
        if (!user) Router.push(&quot;/login&quot;);
      });
  
      return &lt;Component {...props} /&gt;;
    };
  
    return Auth;
  };
  
  export default withAuth;
  </code></pre>
  <h2>Sample of the use of withAuth</h2>
  <pre><code>import React from &quot;react&quot;;
  import withAuth from &quot;./withAuth&quot;;
  
  function sample() {
    return &lt;div&gt;This is a protected page&lt;/div&gt;;
  }
  
  export default withAuth(sample);
  </code></pre>