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);}
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")}>
Course
Build your SaaS in 2 weeks - Start Now