javascriptreactjsgoogle-analyticsnext.jsstyled-components

How to use google analytics with next.js app?


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?

I checked next.js google analytics example but as I said my _document file is different because of using styled-components.

// _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 = () => originalRenderPage({
        enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
      })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

export default MyDocument


Solution

  • Next.js since v11 recommends using their <Script> tag, and the right place to add it is the App component.

    pages/_app.jsx

    import React from 'react';
    import Script from 'next/script';
    
    const App = ({ Component, pageProps }) => {
      return (
        <>
          <Script
            src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxxx"
            strategy="afterInteractive"
          />
          <Script id="google-analytics" strategy="afterInteractive">
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){window.dataLayer.push(arguments);}
              gtag('js', new Date());
    
              gtag('config', 'G-xxxxxxxxxx');
            `}
          </Script>
    
          <Component {...pageProps} />
        </>
      );
    };
    
    export default App;
    

    You can see this solution working in nestjs-starter where I'm also setting the tag from an env var.

    For v10 and lower use regular <script> tags according to Google's guide.

    Keep in mind that Google Analytics does automatic page tracking, but this will not work for every use case. For example, hash and search parameter changes are not tracked. This can lead to a lot of confusion. For example, when using HashRouter or anchor links the navigation will not be tracked. To have full control over page view tracking you can disable automatic tracking. See for a detailed explanation: The Ultimate Guide to Google Analytics (UA & GA4) on React (Or Anything Else

    Manual page tracking: https://stackoverflow.com/a/63249329/2771889