google analytics nextjs

  1. Install the necessary packages:
npm install next react react-dom
npm install @react-analytics/react-analytics
  1. Set up Google Analytics:
  2. Create a new Google Analytics property.
  3. Obtain the Tracking ID.

  4. Create a new file next.config.js at the root of your Next.js project:

module.exports = {
  env: {
    GA_TRACKING_ID: 'your_tracking_id_here',
  },
};
  1. Create a new file lib/gtag.js to handle Google Analytics integration:
export const GA_TRACKING_ID = process.env.GA_TRACKING_ID;

export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  });
};

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value: value,
  });
};
  1. Integrate Google Analytics in your _app.js or _app.tsx file:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import * as gtag from '../lib/gtag';

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

  useEffect(() => {
    const handleRouteChange = (url) => {
      gtag.pageview(url);
    };

    router.events.on('routeChangeComplete', handleRouteChange);

    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

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

export default MyApp;
  1. Add the Google Analytics script to your custom Head component (if not using Next.js built-in Head):
import Head from 'next/head';

const CustomHead = () => (
  <Head>
    {/ Other head elements /}
    <script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`} />
    <script
      dangerouslySetInnerHTML={{
        __html: `
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '${process.env.GA_TRACKING_ID}', {
            page_path: window.location.pathname,
          });
        `,
      }}
    />
  </Head>
);

export default CustomHead;
  1. Import and use your custom Head component in your pages or layout.

  2. Verify the Google Analytics setup by checking the real-time reporting in your Google Analytics dashboard.