title: Next JS - Handling getInitialProps on _app.js in SSR vs CSR
body: <p>I am trying to create a Next JS application that handles the authentication and initial routing inside getInitialProps. I discovered this method can be executed either in the server or on the client.
  My approach so far it's to have 2 different handlers based on detecting if I am in executing in the server checking for the presence of the req attribute inside of ctx.
  This does the trick but doesn't feel like is the right way of doing. Can somebody, please, tell me if there is a cleaner way.
  All authentication is handled in a separate subdomain, so I just need to redirect to the auth subdomain if there is no cookie or auth request fails for some other reason.</p>
  <pre><code>import &quot;../../styles/globals.css&quot;;
  
  function MyApp({ Component, pageProps }) {
    return &lt;Component {...pageProps} /&gt;;
  }
  
  MyApp.getInitialProps = async (appContext) =&gt; {
      let cookie, user;
  
      let ctx = appContext.ctx;
  
      //Check if I am in the server.
      if (ctx.req) {
          cookie = ctx.req.headers.cookie
          //Do auth request.
  
          //Redirect base on user properties
          // handle redirects using res object
          ctx.res.writeHead(302, { Location: &quot;/crear-cuenta&quot;});
           
      }  else {
          cookie = window.document.cookie;
          //Do auth request.
          //Redirect base on user properties
          //Do redirects using client side methods (useRouter hook, location.replace)???
      }
  
      //Return pageProps to the page with the authenticted user information.
      return { pageProps: { user: user } };
    
  };
  
  export default MyApp;
  </code></pre>