How to use google analytics with next.js app?

SHAHROOZ picture SHAHROOZ · Feb 26, 2020 · Viewed 13.2k times · Source

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

Answer

thisismydesign picture thisismydesign · Jun 24, 2020

The accepted answer didn't work for me. Copying the full tracking code within dangerouslySetInnerHTML results in Unexpected token <.

Instead, do the following in _document.js or wherever you defined Head:

<Head>
  <script
    async
    src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
  />

  <script
    dangerouslySetInnerHTML={{
      __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '[Tracking ID]');
        `,
    }}
  />
</Head>

See also: