Implement Google Analytics in Next.js
Setting up Google Anaylytics is fairly straight forward, but it can be easy to get tripped up when doing so in Next.js for the first time. In this guide, I will show you how to get GA running in your Next.js app in just a few easy steps.
If you don't already have one, create a file called
.env. Make sure to add this file to your
.gitignore as this is a place to store sensitive information that should never be uploaded to a git repository.
If you don't already have one, create a custom Document page and add the script tags provided by Google Analytics:
This will get the initial tracking set up for your app.
Here we will utilize Next's
useRouter in order to send route information to Google Analytics.
useEffectinside of a normal function (and this isn't a component). I have chosen this name and path for code organization purposes, but you can alternatively put the useEffect directly in
This is an easy step to forget. Be sure to set up
NEXT_PUBLIC_ANALYTICS_ID (from your
.env file) on your server.
Now that GA is up and running, the final step is to ensure you aren't tracking your own visits. You will need your IP address. Once you have your IP, log in to Google Analytics.
- From the main page, look to the bottom left of the screen and click on the gear (Admin) icon ⚙️.
- On the Admin screen, ensure you are on the correct GA4 property that you just set up. Click on Data Streams.
- Click the Add stream button and click on your app address.
- On the "Web stream details" panel, at the very bottom, click More Tagging Settings.
- On the "More tagging settings" panel, click Define internal traffic
- Click on the Create button, add a Rule name (e.g. Home), and leave traffic_type value as "internal". Finally, select Match type: IP Address Equals and then paste your IP address into the Value input.
- Click the Add condition button. Repeat these steps for any other IPs you want to filter.
- Click the Admin gear icon ⚙️, then select Data Settings > Data Filters
- On the "Data filters" page click the three dots to the right of the Internal Traffic filter and select "Activate Filter".
Google Analytics is a great way to keep track of who visits your site, where they are coming from, what they are looking at, and how long they are spending doing so. While it's packed with features and customizations, the UI is a bit clunky and it can be overkill for a small site. I have been on the lookout for something modern, lightweight, and free. If you know of anything that fits that description, hit me up on Twitter and let me know!