Published on

Google Analytics in Nextjs

Authors

How Add Google Analytics to a Next.js Website

import '../styles/globals.css'
import Layout from '../components/layout/index.js'
import { Fragment } from 'react'
import Script from 'next/script.js'

function MyApp({ Component, pageProps }) {
  return (
    <Fragment>
      <Script
        strategy="afterInteractive"
        src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-XXXXXXXX', {
            page_path: window.location.pathname,
            });
            `,
        }}
      />
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </Fragment>
  )
}

export default MyApp