How to Add Google Analytics 4 to Next.js
In this tutorial, we will walk you through the process of adding Google Analytics version 4 to a Next.js website. Follow the steps below:
Step 1: Create a Google Analytics Property
First, create a Google Analytics property and remember to save the property ID. This property ID will be used later on in the implementation.
Step 2: Set Up Environment Variables
Next, set up environment variables for your Next.js project. Create an environment variable called NEXT_PUBLIC_GOOGLE_ANALYTICS and assign it the value of your Google Analytics property ID.
Step 3: Modify the _app.js File
Now, open the pages/_app.js file in your Next.js project and make the following modifications:
1 | import { useEffect } from 'react' |
Here, we import the useEffect hook and the useRouter hook from the react and next/router libraries, respectively. Then, we add the useEffect hook to handle route changes. Within the useEffect hook, we define a function called handleRouteChange that triggers the Google Analytics tracking code.
Step 4: Create the _document.js File
Next, create a pages/_document.js file in your Next.js project. This file will serve as the custom document for injecting the Google Analytics script. Here’s the content of the _document.js file:
1 | import Document, { Html, Head, Main, NextScript } from 'next/document' |
In this file, we import Html, Head, Main, and NextScript components from the next/document module. Inside the Head component, we include the Google Analytics script using the property ID from the environment variable.
That’s it! You’ve successfully added Google Analytics 4 to your Next.js website. Now you can track user activities and gain valuable insights about your website’s performance.
Note: This solution is adapted from a post by Marie Starck on mariestarck.com
tags: [“Next.js”, “Google Analytics”, “SEO”, “Tracking”, “Web Analytics”]