How to Integrate Google Analytics into Your Next.js Web App

Photo by @goumbik on Unsplash

Photo by @goumbik on Unsplash

Today in this article, we will see how we can add Google Analytics to our Next.js app. So without further ado, let’s jump right into it.

Step 1: Creating a new Next.js app

First, let’s create a new Next.js app by running the command in the terminal:

npx create-next-app demo-app

This step is not required if you already have an existing Next.js app and want to add Google Analytics.

Step 2: Create a new property in Google Analytics

Now, let’s go to the Google Analytics website. Create your Google Analytics account if you haven’t already.

After creating the Google Analytics account, click on the “Admin” section in the bottom left corner and click “Create Property.” Give the property a name and fill out all the other staffs the form is asking for.

Step 3: Create DataStream in Google Analytics

Next, we need to set up our data stream for our Next.js app. Here, we can set up data streams for three types of platforms. As we add analytics to our Next.js app, we will choose “Web.”

Then we should give our website URL and a stream name. When you have done that, click on “Create Stream.”

Step 4: Add Google Analytics script to your Next.js app

After creating the stream, you get the web stream details page. Expand the “Global site tag (gtag.js),” and you should see some script code.

Now, add this script in _app.tsx of your Next.js app.

We used Next.js’s Script component to render the script tag. We added strategy=”lazyOnload” in the Script component. We also put the Google Analytics Code in our environment variable (in the .env file), named NEXT_PUBLIC_GOOGLE_ANALYTICS_CODE. The rest are similar to what we copied from the Google Analytics website.

Step 5: Test if Google Analytics is correctly set up on your web app

We have completed setting up Google Analytics in our Next.js web application. Now we need to test whether Google Analytics is correctly set up.

Let’s connect to our web application and open the console from the browser. On the console, let’s write dataLayer and hit enter. If Google Analytics is correctly set up on our web app, we should see something similar to the bottom.

Conclusion

We have successfully integrated Google Analytics into our Next.js web application. We can now analyze our web visitors from the Google Analytics charts.