How to track initial page views in next.js projects?

Viewed 1355

I went through next.js example projects, especially how to integrate google analytics and facebook pixel.

Both integrations use routeChangeComplete event here and here. It triggers when user changes route and then page view event is sent to analytics tools.

routeChangeComplete event doesn't trigger on initial render (first user visit). It triggers only when user changes route (enters another route). I think Google Analytics and Facebook Pixel page view events should be sent on the first user's visit as well. How to do that correctly in next.js projects?

1 Answers

You can do it by creating a custom _app.jsx file. There you can track the initial visit by adding a useEffect hook with an empty dependency array so that the function will only fire on the initial render:

export default function MyApp({ Component, pageProps }) {
  React.useEffect(() => {
    // Track the initial view
  }, []);

  return <Component {...pageProps} />;
}
Related