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

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


2 min read

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();

    } catch (error) {

function logPageView() {

function logPageViews() {
  logPageView();'routeChangeComplete', () => {

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(() => {
  }, []);

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

export default MyApp;

3. Add your GA code as an environment variable:

# .env.local


๐ŸŽ‰ 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! โค๏ธ