How to add Google Analytics 4 to Next.js

Here’s how to add Google Analytics version 4 to a website based upon Next.js.

Create a Google Analytics property and save the property ID in a NEXT_PUBLIC_GOOGLE_ANALYTICS environment variable.

Then, you need to add a useEffect() call in the pages/_app.js file, which might look like this now:

import '/public/style.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Change it to

import { useEffect } from 'react'
import { useRouter } from 'next/router'

import 'tailwindcss/tailwind.css'
import '/public/style.css'

function MyApp({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = url => {
      window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
        page_path: url,
      })
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return <Component {...pageProps} />
}

export default MyApp

Finally, add a pages/_document.js file that creates a Next.js custom document that injects the Google Analytics script, with:

import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

Note: solution adapted from a post by Marie Starck on https://mariestarck.com/add-google-analytics-to-your-next-js-application-in-5-easy-steps/


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

Here’s how to add Google Analytics version 4 to a website based upon Next.js.

Create a Google Analytics property and save the property ID in a NEXT_PUBLIC_GOOGLE_ANALYTICS environment variable.

Then, you need to add a useEffect() call in the pages/_app.js file, which might look like this now:

import '/public/style.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

Change it to

import { useEffect } from 'react'
import { useRouter } from 'next/router'

import 'tailwindcss/tailwind.css'
import '/public/style.css'

function MyApp({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = url => {
      window.gtag('config', process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS, {
        page_path: url,
      })
    }
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return <Component {...pageProps} />
}

export default MyApp

Finally, add a pages/_document.js file that creates a Next.js custom document that injects the Google Analytics script, with:

import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
              page_path: window.location.pathname,
            });
          `,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

Note: solution adapted from a post by Marie Starck on https://mariestarck.com/add-google-analytics-to-your-next-js-application-in-5-easy-steps/


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-06-27T05:00:00+00:00) How to add Google Analytics 4 to Next.js. Retrieved from https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/

MLA
" » How to add Google Analytics 4 to Next.js." flaviocopes.com | Sciencx - Sunday June 27, 2021, https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/
HARVARD
flaviocopes.com | Sciencx Sunday June 27, 2021 » How to add Google Analytics 4 to Next.js., viewed ,<https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/>
VANCOUVER
flaviocopes.com | Sciencx - » How to add Google Analytics 4 to Next.js. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/
CHICAGO
" » How to add Google Analytics 4 to Next.js." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/
IEEE
" » How to add Google Analytics 4 to Next.js." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/. [Accessed: ]
rf:citation
» How to add Google Analytics 4 to Next.js | flaviocopes.com | Sciencx | https://www.scien.cx/2021/06/27/how-to-add-google-analytics-4-to-next-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.