Benji Friedman > Blog

How to add Google Analytics 4 to a NextJS 14 website

This is actually pretty easy once you know how to do it, but I didn't see straightforward instructions online from a quick search. If you have any questions, feel free to contact me.

Google Analytics setup and Measurement ID

First, go to your

Click on Admin, the gear icon in the lower left corner.

On the left side list of links, click into "Data collection and modification", and then the first option, "Data streams".

If you don't already have a data stream, click the blue "Add stream" button, and select the toption to add a Web stream.

(If you're setting up the data stream for the first time, you just need the website URL and whatever name you want to call the property from within Google Analytics).

Once you've set up the web data stream, you can click into it and see the "Measurement ID" value, which starts with a "G-". Copy this value and save it for the next section.

In the NextJS 14 app

Ok, now in your app's code, go to app/layout (the root layout file).

At the top of the file, import the NextJS Script element:

import Script from "next/script"

And before the closing </body> tag, add the following code:

<Script src="{GOOGLE_MEASUREMENT_ID}" />
<Script id="google-analytics">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{GOOGLE_MEASUREMENT_ID}');

Putting the Measurement ID value you copied in the two places in brackets.

Here's an image that illustrates this:

adding google analytics 4 to nextjs 14

Push the code to production, and you should start seeing data come in almost immediately. Good luck!