javascriptreactjsnext.jsmatomopiwiktracker

Listen to route change with next.js to use with matomo/piwik


I'm trying to listen to route changes on a next.js app, in order to log navigation to matomo (aka piwik). According to next.js' documentation, I have to do something like this:

Router.events.on('routeChangeStart', url => {
  // Do something
});

Where do I have to use this code in my app in order to log all the route change events?

("where" means in which file/class/method)


Solution

  • You have to add it in pages/_app.js, in the componentDidMount method:

    componentDidMount() {
      Router.events.on("routeChangeStart", url => {
        if (window && window._paq) {
          window._paq.push(["setCustomUrl", url]);
          window._paq.push(["setDocumentTitle", document.title]);
          window._paq.push(["trackPageView"]);
        }
      });
    }
    

    Don't forget to initialize it in your base page (i.e. your Layout or something like that):

    <!-- Matomo -->
    <script type="text/javascript">
      var _paq = window._paq || [];
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
      (function() {
        var u="//{$PIWIK_URL}/";
        _paq.push(['setTrackerUrl', u+'piwik.php']);
        _paq.push(['setSiteId', {$IDSITE}]);
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
      })();
    </script>
    <!-- End Matomo Code -->