Search code examples
javascriptgoogle-analyticsserver-side-renderinggoogle-analytics-4react-ga

Troubles with setting Google analytics in React SSR project


a saw a pretty similar question but there was not even one answer to it, so if somebody can help somehow it would be great.

I have a project with SSR on React js, without using Next.js. When i trying to set Google analytics just as Docs says and paste initialisation code to Layout.cshtml like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-D93F680HTN"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'G-xxxxxxxxxxx');
    </script>

it works but only shows coommon events like pageview

then i tried to add react-ga lib, and i paste initialization code to Layout.tsx like this:

 import ReactGA from 'react-ga';
    
    const history = useHistory();
        
        React.useEffect( () => {
            ReactGA.initialize('G-xxxxxxxxxxx');
        }, []);
    
        React.useEffect(() => {
            ReactGA.pageview(history.location.pathname + history.location.search);
            console.log('GAGAGA');
            console.log(history.location.pathname, 'PATH');
        }, [history.location.pathname, history.location.search]);

and add a cusom event to button in a homepage component:

const GAevent = (cat, act) => {
        ReactGA.event({
            category: cat,
            action: act,
            label: 'Homepage Thing',
            value: 1
        });
    };

<button onClick={() => GAevent('Promotion', 'Displayed Promotional Widget')}>
    TEST
</button>

after it when i change url or click the button, in devtools -> network a can see requests sending:

https://www.google-analytics.com/collect?v=1&_v=j90&a=373007786&t=event&_s=9&dl=http%3A%2F%2Flocalhost%2F&ul=ru-ru&de=UTF-8&dt=urlpart1%urlpart2%20%7C%20urlpart3%20of%20urlpart4&sd=24-bit&sr=1920x1080&vp=1903x969&je=0&ec=Promotion&ea=Displayed%20Promotional%20Widget&el=Homepage%20Thing&ev=1&_u=CACAAEABAAAAAC~&jid=&gjid=&cid=1105544602.1617783853&tid=G-Dxxxxxxxx&_gid=1622278569.1618564467&z=1200894868

but I do not see any changes in google analytics events itself.

If anybody can help somehow, what I'm doing wrong?

I also installed Google Tag Assistant extension and it see my events either pege_view or my custom event but in Google Analytics still happens nothing

enter image description here


Solution

  • You are using a GA4 Property but you're trying to send Universal Analytics hits.

    To simplify, I suggest you to create a Universal Analytics Property (that has id like UA-XXXXXXX-XX instead of G-XXXXXXXX) and using that.

    You can create it by clicking on Show advanced options (when you create a new property):

    enter image description here