Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nextjs router.events.on not called on intial page load

I have a working useEffect to call my google analytics when changing page. This works fine when changing pages but when you initially load for the first time or refresh it does not call the router.events.on

this is my code

 useEffect(() => {
    if (cookies === true) {
      router.events.on("routeChangeComplete", () => {            
        ReactGA.pageview(window.location.pathname);
      });
      return () => {
        router.events.off("routeChangeComplete", () => {
          ReactGA.pageview(window.location.pathname);
        });
      };
    }
  }, [router.events]);

I thought of using an other useEffect to initially call the reactGA but then when changing page it would be called twice, which is not good.

any idea on how to make this work on the initial page load?

like image 953
Maxime Ghéraille Avatar asked Oct 31 '25 23:10

Maxime Ghéraille


1 Answers

That's expected behaviour - router.events is only triggered on client-side page navigations initiated by the Next.js router.

You can call ReactGA.pageview on a separate useEffect to handle initial page loads.

useEffect(() => {
    if (cookies === true) {            
        ReactGA.pageview(window.location.pathname);
    }
}, []);
like image 59
juliomalves Avatar answered Nov 02 '25 13:11

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!