homeresume
 
   

Integrating Next.js app with Google analytics 4

Published February 6, 2022Last updated January 27, 20231 min read

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

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")}>

 

© 2023