Google Analytics 4 (GA4) in Next.js 14 and React. With event tracking.
Google has transitioned to Google Analytics 4 (GA4), and while setting it up on a Next.js 14 site, I noticed a lack of clear, practical guides — especially for the widely-used npm package, react-ga4. Let’s address that gap!
Update: Opting for Next.js’ Official Component for Third-Party Integrations
After publishing this guide, redditor wplaga highlighted an alternative to using react-ga4 for integrating services like Google Analytics, Google Tag Manager, or Google Maps into Next.js projects. Next.js offers an official component specifically built for handling third-party integrations, providing a more direct and potentially more reliable method. This approach mirrors the react-ga4 method in many ways but benefits from being a native solution within the Next.js ecosystem. If you’re interested in the react-ga4 approach or looking to expand your understanding, the next section has got you covered. However, if you prefer a more straightforward method using Next.js’s own tools, here’s what you need to do:
To get started, install the @next/third-parties
library:
yarn add @next/third-parties@latest next@latest
Important notice: The latest version of next/third-parties
(14.0.4) is missing the export for the Google Analytics component. You will receive an error: Unsupported Server Component type: undefined
. This is fixed in the latest canary release of the package. See this issue. You can install it with:
yarn add @next/third-parties@14.0.5-canary.38
Let’s get started. To apply Google Analytics across all routes in your application, you can incorporate the Next.js Third-Party Google Analytics component into your root layout. Just provide your measurement ID, and you’re ready to go. This method offers a direct and well-supported way to integrate Google Analytics into your Next.js project.
// src/app/layout.js
import { GoogleAnalytics } from '@next/third-parties/google'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
<GoogleAnalytics gaId="G-XYZ" />
</html>
)
}
Now, page views are being tracked. To load Google Analytics for a single route, include the component in your page.
To track user interactions as events in client components, use the sendGAEvent
function. It is sending events using the dataLayer
object. For this function to work, the <GoogleAnalytics />
component must be included in either a parent layout, page, or component or directly in the same file.
// One of your components, for example:
// src/components/EventButton.jsx
'use client'
import { sendGAEvent } from '@next/third-parties/google'
export function EventButton() {
return (
<div>
<button
onClick={() => sendGAEvent({ event: 'buttonClicked', value: 'xyz' })}
>
Send Event
</button>
</div>
)
}
That’s it. You find the full guide and explanations for Google Tag Manager or Google Maps over here: https://nextjs.org/docs/app/building-your-application/optimizing/third-party-libraries#google-analytics
Using react-ga4 — Getting Started.
I’m assuming you have a Google Analytics account, a created property, and your measurement ID. You should also have a working Next.js or React site ready for tracking. We’ll jump straight into configuring Google Analytics 4.
Our Aim: SSR-Compatible, Flexible Event Tracking with Google Analytics 4
Our goal is simple: we want a site that’s fast, leverages server-side rendering (SSR) without the Google Analytics script slowing it down, and allows for event tracking across different components.
Let’s start by installing react-ga4. The package is the successor to react-ga. Installation is straightforward.
yarn add react-ga4
Next, we’ll create a utility file to hold two functions: one for initializing Google Analytics and another for tracking events. Here’s how I set up mine in /src/utilities/google-analytics.js
:
// /src/utilities/google-analytics.js
import ReactGA from "react-ga4";
const initializeGA = () => {
// Replace with your Measurement ID
// It ideally comes from an environment variable
ReactGA.initialize("YOUR_MEASUREMENT_ID");
// Don't forget to remove the console.log() statements
// when you are done
console.log("GA INITIALIZED");
};
const trackGAEvent = (category, action, label) => {
console.log("GA event:", category, ":", action, ":", label);
// Send GA4 Event
ReactGA.event({
category: category,
action: action,
label: label,
});
};
export default initializeGA;
export { initializeGA, trackGAEvent };
Now, we need to call initializeGA()
when the page loads. In Next.js 14, since pages likely use SSR, and we want to avoid slowing down the page, we'll use a client component. In this component, useEffect
will handle initializing Google Analytics right when the component mounts. We'll also make sure to note in the window context if Google Analytics has been initialized. This component can then be imported into our main page structure.
// /src/components/GoogleAnalytics.jsx
"use client";
import { useEffect } from "react";
import { initializeGA } from "@/utils/GoogleAnalytics";
export default function GoogleAnalytics() {
useEffect(() => {
if (!window.GA_INITIALIZED) {
initializeGA();
window.GA_INITIALIZED = true;
}
}, []);
}
Include this in your main page file (like page.jsx
, _app.jsx
, etc.):
// /src/app/page.jsx
import GoogleAnalytics from "@/components/GoogleAnalytics";
export default async function Home() {
return (
<div className="bg-white">
<!-- Import the component right at the top -->
<GoogleAnalytics />
<Header />
<main>
<!-- Whatever your page looks like -->
</main>
<Footer />
</div>
);
}
Verifying Page Views
Check if page views are being tracked by filtering the network tab in your browser’s developer tools for “google”, or use a Google Analytics debugger extension.
Setting Up Event Tracking
For event tracking, import trackGAEvents
from the utility file we set up, define the event category, action, and label, and you're ready to go:
// /src/components/MyForm.jsx
"use client";
import { trackGAEvent } from "@/utils/GoogleAnalytics";
export default function MyForm({ className }) {
// This is just a dummy component to show
// how to use the trackGAEvent function
// You can use it in any function call where you
// want to track an event
function handleSubmit(event) {
trackGAEvent("My Category", "My Action", "My Label");
// handle the actual form submission here
}
return (
<form className={className} action={handleSubmit}>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<button type="submit">Submit</button>
</form>
);
}
That’s it! I hope I made you happy, and…
I hope this guide helps you smoothly integrate Google Analytics 4 into your Next.js projects. And if this article was useful, check out the project I’m working on: layers. It’s an AI-powered journaling companion that automatically turns your entries into actionable insights and helps you live a balanced and self-determined life.
It’s like having a coach ready to help you reflect on your life, thoughts, and challenges at any time, providing detailed weekly reports and even a personalized podcast. Give it a try and enhance your journaling experience 🙂