DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

3

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

Course

Build your SaaS in 2 weeks - Start Now

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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 :)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs