Learn how to add Google Analytics to your site using Next.js, a React framework for building SEO-friendly websites.
Setting Up Google Analytics
Google Analytics provides insights into the behavior of people visiting your website. It tells you which pages get the number of views and gives you audience data like location, age, interest, and the device they use. This data can help make decisions about the direction your business should take to be successful.
To get started, visit the analytics dashboard and create a new account by following these steps:
Click the Create Account button in the admin tab to create a new account. Add an account name under the Account setup section. Create the analytics property by providing a name. Add the business details. Select the options that apply to your website. Click the Create button to finish setting up the property. Click on web stream to specify the data stream Google Analytics should track. Specify the URL to your website and give the data stream a name. Click on tagging instructions and get the script you will use on your website. Copy the measurement ID (the tracking code) to use later.
Once you get the tracking code, you can set up the Next.js project.
Setting Up the Next.js Project
If you don’t already have a Next.js project set up, see the Next.js official guide to get started.
When you created the Global site tag property, you got a script like this:
You need to add this script to the head tag of your website. In Next.js, you use the Script component from next/script. This component is an extension of the HTML script tag. It allows you to include third-party scripts to your Next.js website and set their loading strategy, improving performance.
The Next.js Script component offers different loading strategies. The “afterinteractive” strategy is suitable for an analytics script. This means it will load after the page is interactive.
Open the pages/_app.js file and import the Script component at the top.
Next, modify the return statement of the App component to include the script tag from Google analytics.
Note that this tag is slightly different from the one Google Analytics provides. It uses dangerouslySetInnerHTML and includes a loading strategy. They, however, work the same.
Remember to replace G-XXXXXXX with your tracking code. It is also advisable to store the tracking code in a .env file to keep it secret.
Adding Google Analytics to a Single Page Application
You can use the script tag above for a regular website and leave it at that. However, for a single-page application like a Next.js website, you need to take a few extra steps.
A single-page application (SPA) is a website that loads all content upfront, in response to an initial request. The browser loads content dynamically as a user clicks on links to navigate the site. It does not make a page request, only the URL changes.
This is different for Next.js pages that use getServerSideProps as the browser renders those on request.
The Google tag works by recording a page view when a new page loads. So, for SPAs, the Google tag is only executed once, when the page initially loads. Therefore, you must manually record the views as the user navigates to different pages.
See the single-page measurement Google Analytics guide to learn more.
To manually record page views in Next.js using the gtag script, create a new folder called lib and add a new file, gtag.js.
Next, modify /pages/_app.js to use these functions and track page views in the useEffect hook.
This example uses the useRouter and useEffect hooks to record a page view every time the user navigates to another page.
Call the useRouter method from next/router and assign it to the router variable. In the useEffect hook, listen to the routeChangeComplete event on the router. When the event fires, record a page view by calling the handleRouteChange function.
The useEffect hook’s return statement unsubscribes from the routeChangeComplete event with the ‘off’ method.
Use Google Analytics to Collect User Data
Data is hugely beneficial to making good decisions, and adding Google Analytics to your website is one way to collect it.
You can add Google Analytics to a Next.js project using hooks to ensure you record all the page views even when a page uses client-side routing. Now you can see how many views your site gets on your Google Analytics dashboard.