title: What is proper way to detect device in Next.js SSR?
body: <p>I have <code>&lt;MobileLayout /&gt;</code>, <code>&lt;DesktopLayout /&gt;</code>. I'm using <code>Next.js</code> for Server Side Rendering.
  And I noticed there are many famous ui library has mobile detection components like <code>&lt;Respnosive /&gt;</code> component in Semantic-UI-React. But all of this is client side method, not working properly on <code>SSR</code></p>
  
  <p>I read some documents the conclusion is I should check <code>user-agent</code> of server side <code>req.headers</code>. In Next.js, What is proper way to detect device and conditonally render one of <code>MobileLayout</code> / <code>DesktopLayout</code>?</p>
  
  <p><strong>What I tried</strong></p>
  
  <p>in <code>_app.js</code></p>
  
  <pre><code>import isMobile from 'ismobilejs'
  
  ...
  
  function Homepage({ Component, pageProps, mobile }){
    return (
      mobile ? 
        &lt;MobileLayout&gt;&lt;Component {...pageProps} /&gt;&lt;/MobileLayout&gt; : 
        &lt;DesktopLayout&gt;&lt;Component {...pageProps} /&gt;&lt;/DesktopLayout&gt;
    )
  }
  
  HomePage.getInitialProps = async (appContext) =&gt; {
    const userAgent = appContext.ctx.req.headers['user-agent']
    const mobile = isMobile(userAgent).any
    const appProps = await App.getInitialProps(appContext)
    return { ...appProps, mobile }
  }
  </code></pre>
  
  <p>But the problem is getIntialProps on <code>_app.js</code> executed every page load. with moving page with client, the <code>appContext.ctx</code> is <code>undefined</code> so it will omit error. and I think this method might block some nextjs builtin optimizations.</p>
  
  <blockquote>
    <p>Error in error page <code>getInitialProps</code>:  TypeError: Cannot read
    property 'headers' of undefined</p>
  </blockquote>
  
  <p>So what is propery way to check device in Next.js?</p>