Skip to main content

Command Palette

Search for a command to run...

Integrating Google Analytics 4 with Next.js πŸ“ˆ

Updated
β€’2 min read
Integrating Google Analytics 4 with Next.js πŸ“ˆ
A

Software Developer with over 7 years of experience building Mobile Apps and Websites. Founder of multiple startups, two of which have been featured in Forbes and one that won the Cellerant Best of Class Technology Award for emerging dental products.

Today, I decided to add Google Analytics to my portfolio which was built in Next.js

At first, I thought that I could achieve this with react-ga, but after trying to add my GA code I realized that it doesn't support Google Analytics 4, only Universal Analytics. At this point, I could go and enable Universal Analytics, but I am not into legacy stuff, sorry... πŸ€·β€β™‚οΈ

Luckily I found a library that does support Google Analytics 4, it's called ga-4-react. Disclaimer: It doesn't have a lot of starts, but it works! 🀫

But integrating it with Next.js is different than just plain react, there a few things you must do!

1. Create a util file in the root project:

/* utils/ga.js */

import Router from 'next/router';
import GA4React from 'ga-4-react';

let ga4react;

export async function init(G) {
  if (!GA4React.isInitialized() && G && process.browser) {
    ga4react = new GA4React(G, { debug_mode: !process.env.production });

    try {
      await ga4react.initialize();

      logPageViews();
    } catch (error) {
      console.error(error);
    }
  }
}

function logPageView() {
  ga4react.pageview(window.location.pathname);
}

function logPageViews() {
  logPageView();

  Router.events.on('routeChangeComplete', () => {
    logPageView();
  });
}

export function logEvent(action, label, category) {
  ga4react.event(action, label, category);
}

2. Modify the _app.js file to initiate the ga.js service:

/* ... */

import { useEffect } from 'react';

import { init } from 'utils/ga';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    init(process.env.NEXT_PUBLIC_G);
  }, []);

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

export default MyApp;

3. Add your GA code as an environment variable:

# .env.local

NEXT_PUBLIC_G=G-<YOUR CODE>

πŸŽ‰ Voila, now you should be able to see an active device in Google Analytics DebugView! If you don't, try to disable your AdBlock as it could create problems sometimes...

That's it for today folks, hope this article was helpful to you! Leave a like and comment if it was! See you tomorrow on another blog post! 😊


p.s 🀫 I recently started a podcast called The Anxious Developer where I share my knowledge on how to reduce your stress, become more present and productive as a Developer. I would love to hear your thoughts on it! 😊

Remember, you are worthy, you are loved and you matter! Have a great day! ❀️

M

Hello, thank you for the guidance!

I don't know a lot about analytics and I am having a hard time trying to identify which ID is the right ID to use with GA4.

My company uses Google Analytics and the ID has this shape: UA-xxxxxxxx-x, but I think this is not the ID I should be using with this estrategy, right?

Is it the google tag manager ID? Or something else? Thank you!

A

Thanks!

It looks like you are using Universal Analytics. In that case, I suggest you use react-ga library to manage your Google Analytics.

Hope this helps :)

M

Andrei Zgirvaci yep! I ended up just doing that and it worked very well. Thank you!

T

Thank you for this. One thing - the custom events are not showing up on GA. This seems like the old event signature.

1
A

Hmm, was a while since I have used Google Analytics. Not sure what's going on.

Maybe checking the repo issues will help...

More from this blog

A

Andrei's Zgirvaci - Blog

39 posts

πŸ‘¨β€πŸ’» CTO at Trustio Inc. | πŸ‘¨β€πŸ« React Native Mentor at CodeMentor.io | βš›οΈ Creator of React Native Status | πŸŽ™οΈ Host of The Anxious Developer Podcast