title: How to use google analytics with next.js app?
body: <p>I'm using styled-components with next.js so my styles need to be server-side rendered, hence how can I add google analytics to my website?</p>
  
  <p>I checked <a href="https://github.com/zeit/next.js/tree/canary/examples/with-google-analytics" rel="noreferrer">next.js google analytics example</a> but as I said my _document file is different because of using styled-components.</p>
  
  <pre class="lang-js prettyprint-override"><code>// _document.js
  
  import React from 'react'
  import Document from 'next/document'
  import { ServerStyleSheet } from 'styled-components'
  
  class MyDocument extends Document {
    static async getInitialProps(ctx) {
      const sheet = new ServerStyleSheet()
      const originalRenderPage = ctx.renderPage
  
      try {
        ctx.renderPage = () =&gt; originalRenderPage({
          enhanceApp: (App) =&gt; (props) =&gt; sheet.collectStyles(&lt;App {...props} /&gt;),
        })
  
        const initialProps = await Document.getInitialProps(ctx)
        return {
          ...initialProps,
          styles: (
            &lt;&gt;
              {initialProps.styles}
              {sheet.getStyleElement()}
            &lt;/&gt;
          ),
        }
      } finally {
        sheet.seal()
      }
    }
  }
  
  export default MyDocument
  
  </code></pre>