DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

Integrating Next.js app with Google analytics 4

Google analytics helps get more insights into app usage.

Prerequisites

  • Google analytics product is already set up, tracking ID is needed
  • Next.js app should be bootstrapped
  • react-ga4 package is installed

Analytics initialization

Analytics should be initialized inside pages/_app.js file.

import ReactGA from "react-ga4";
// ...
if (isEnvironment("production")) {
  ReactGA.initialize(ANALYTICS_TRACKING_ID);
}
Enter fullscreen mode Exit fullscreen mode

Tracking events (clicks, e.g.)

// ...
export function trackEvent(category, label, action = "click") {
  if (isEnvironment("production")) {
    ReactGA.event({
      action,
      category,
      label,
    });
  }
}

// ...
<Button onClick={() => trackEvent("category", "label")}>
Enter fullscreen mode Exit fullscreen mode

Boilerplate

Here is the link to the boilerplate I use for the development.

Top comments (2)

Collapse
 
dinhkhai0201 profile image
Nguyen Dinh Khai

It is great!
thanks

Collapse
 
zsevic profile image
Željko Šević

I'm glad you find it helpful :)