Easiest Way to Install Google Analytics 4 on NextJS

BY Connor Bearse / FILED UNDER Development

Installing Google Analytics 4 on a NextJS deployment is harder than it should be. Despite the SSR making an SEO-friendly website a reality, using GA4 isn’t as straightforward.

Since NextJS only “loads” once and then hydrates the rest of the application afterward – we don’t get actual page load events. We get history change events. If you are going to install GA4 manually, then you have to watch for those events and send them correctly.

It can be done, but it also can be easier. I don’t love wasting time on side projects getting basic analytics working. So behold – quick overview of a handy package that makes installing GA4 onto NextJS a breeze.

If you just need a reference for the package – you can check out the NPM listing here: https://www.npmjs.com/package/nextjs-google-analytics

NextJS Google Analytics NPM Package

Requirements

  • NextJS >= 11.0.0
  • Google Analytics 4 Property

Instructions

First, install the NPM package by running the following in your terminal.

npm install --save nextjs-google-analytics

Open up your _app.js (if you do not have one already, click here to get one setup) and add the following line to import the package.

import { GoogleAnalytics } from "nextjs-google-analytics";

Then, in the return statement of _app.js, place the <GoogleAnalytics trackPageViews /> component above the <Component {…pageProps} /> component.

return (
<>
<GoogleAnalytics trackPageViews />
<Component {...pageProps} />
</>
);

Next, throw a new variable in your .env.local file and adjust the value to your Google Analytics measurement ID. Click here for a handy reference if you’re not sure where that is.

NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"

Finally, in Vercel, navigate to your project settings and then select “Environment” variables.  Add in the NEXT_PUBLIC_GA_MEASUREMENT_ID and put in your Google tracking variable.

Be sure it’s available to your production environment.

Hoorah! You’ve done it!

Time to deploy and check your tag! I still use the legacy tag assistant, but you can use the more “modern” tag assistant to verify.

Legacy Tag Assistant GA4 Verification




More From ClickShepherd...