- 23 Nov 2022
- 6 min read
Don't Let Adblockers Break Your Website Analytics
Smart way of integrating Google Analytics with Next.js app
While I was integrating Google Analytics (GA) with my website powered by Next.js I discovered a couple of tricks that allowed me to do even more than I had to, so I decided to share my results here.
This unblocking method was tested with Google Analytics (GA) but should apply to other industry-standard analytics solution whose server addresses are already blocked by ad-blockers rules.
The Problem
When I wanted to get a better grasp of my website, I decided to add Google Analytics scripts and faced two issues:
- Some Google Analytics metrics are not collected correctly in Next.js apps
- Google Analytics script is blocked by many ad-blockers extensions installed on the userâs browser, so it rarely works
The first issue is related to the nature of Next.js and its optimization for quick page load. In some cases (like PWA), when we go to the next page within the same Next.js app, the actual page reload is not happening. Hence, GA script cannot spot the difference and report a user visiting only one page, the first one.
The second issue is more complex, and itâs about âsmartâ ad-blocker rules preventing common third-party analytics collection script URLs.
While I want to respect user choice not to be âtracked,â I lose important SEO statistics when a gtag
script is blocked. This statistic should help me better understand what I can improve for that user experience.
Instead of blind blocking, it would be much better when a user can decide when to load the analytics script by opting out of cookies consent, for example.
Example of embedding GA scripts with âinline Ifâ by logical && operator
The Solution
The resolution for missing PageViews statistics was pretty straightforward. To collect these metrics without actual page reloading, we need to use React Effect Hook and manually send pageView stat to Google on every routeChange event. There is a lib that does it, and Iâll show you how to use it later.
Now, about nasty ad-blockers. After a quick googling, I sought people selling whole solution products to this, but that could be done much easier and for free. (P.S. I am sorry for ruining someoneâs business model with this tutorial). We must use a local version of the collection script, and proxy all blocked URLs.
Step 1
Note that there could be different regions in a request (probably for a better response time), so we configure it as a :region variable to substitute inside the data collections script.
Step 2
Now we need to load gtag script (in incognito mode) and save it to /public/js/ga-stat.js
file. It should be available through the following link:
https://www.googletagmanager.com/gtag/js?id=YOUR_GA_ID
Then open and replace âhttps://â+a+â.google-analytics.com/g/collectâ
with â/stat/â+a
, so eventually, it will be rewritten by config from step 1 with the correct region.
Storing gtag script locally is a drawback of this solution as we potentially lose any father script updates from Google and have to update it manually after. (Please let me know if you have a better solution for this.)
Step 3
At this point, we need to add nextjs-google-analytics lib and modify our _app.tsx
file. Hereâs the code:
This lib simplifies the whole GA-Next.js integration and helps us to collect PageViews
correctly. Here I am using our local gtag script from step 2 along with strategy=âlazyOnloadâ to minimize GA impact on a user browsing experience.
Also, you have to set your NEXT_PUBLIC_GA_MEASUREMENT_ID
in .env.production
and/or .env.developmpent
file(s) to control when you want GA to work.
Checking if it works
Once you have done it correctly, there should no longer be errors about blocked GA scripts in a console. Instead, you should see successful data-collection requests to our custom route. Eventually, they are proxied to something like https://redion1.google-analytics.com/g/collect.
Summary
Adding analytics scripts to a Next.js application turned out to be more tricky than inserting standard gtag
code snippets to index.tsx
. Finally, I managed to get Google Analytics working correctly with PWA and avoided ERR_BLOCKED_BY_CLIENT
error coming from data collection requests being blocked with adblocker by:
- using nextjs-google-analytics lib
- saving analytic-collections script locally and modifying it to reroute request
- proxying blocked URLs with Next.js Rewrites
I hope I saved you some time googling, and see you in the next round.
Originally published at https://medium.com