How to make Google Analytics send requests only from the main page of the site

51 Views Asked by At

Me need send traffic only from one page of the site. I'm using React v17 and React Router v5.

I used Universal Analytics, but it no longer supports it, and Google Analytics 4 sends traffic to all pages. I tried react-ga4 and react-gtm-hook but it doesn't work.

1

There are 1 best solutions below

1
Vladislav On

You can check the current pathname(for example in history.listen) and only send a "pageview" event when the user is on the necessary page.

  if (window.location.pathname === '/') { // instead of '/' use necessary pathname
    GoogleAnalytics.send('pageview');
  }

or call GoogleAnalytics.send('pageview'); once in useEffect in your page component

const HomePage = () => {
  useEffect(() => {
    GoogleAnalytics.send('pageview');
  }, []);
};