How to implement Google Analytics with Next.js?

by naomi_cronin , in category: SEO Tools , 6 months ago

How to implement Google Analytics with Next.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by harrison.goodwin , 6 months ago

@naomi_cronin 

To implement Google Analytics with Next.js, you can follow these steps:

  1. Sign up for Google Analytics and create a new property for your website.
  2. Once you have created a property, you will be provided with a tracking ID (e.g., UA-XXXXXXXXX-X). Make a note of this ID.


Next.js provides a Head component that allows you to modify the <head> of your pages. You can use this component to add the Google Analytics script to your pages.

  1. Install the react-ga package by running the following command in your terminal:
1
npm install react-ga


  1. Create a new file, for example analytics.js, and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import ReactGA from 'react-ga';

export function initGA() {
  ReactGA.initialize('UA-XXXXXXXXX-X'); // Replace with your Google Analytics tracking ID
}

export function logPageView() {
  ReactGA.set({ page: window.location.pathname });
  ReactGA.pageview(window.location.pathname);
}


  1. Wrap your Next.js application with a custom App component by creating a pages/_app.js file and adding the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { initGA, logPageView } from '../analytics';

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

  // Initialize Google Analytics on client-side
  useEffect(() => {
    if (!window.GA_INITIALIZED) {
      initGA();
      window.GA_INITIALIZED = true;
    }
    logPageView();
  }, [router.pathname]);

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

export default MyApp;


  1. Import and use the Head component from Next.js in your page components to add the Google Analytics script. For example, in pages/index.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import Head from 'next/head';

function Home() {
  return (
    <div>
      <Head>
        <script
          async
          src="https://www.google-analytics.com/analytics.js"
        ></script>
      </Head>
      {/* Your page content */}
    </div>
  );
}

export default Home;


That's it! Now, Google Analytics should be implemented with your Next.js application. You can check the Real-Time reporting in your Google Analytics dashboard to verify if the tracking is working properly.