'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 1:[1]

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 -->

Solution 2:[2]

I got it to work like this

LayoutDefault.js

import NextHead from 'next/head'

export default function LayoutDefault() {
return (
    <div>
        <NextHead>
            …
            <script dangerouslySetInnerHTML={{ __html: `
                console.log('Matomo Component')

                var _paq = window._paq = window._paq || [];
                _paq.push(['trackPageView']);
                _paq.push(['enableLinkTracking']);
                (function() {
                    var u="{$MATOMO_URL}";
                    _paq.push(['setTrackerUrl', u+'matomo.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.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
                })();
            ` }} />
        </NextHead>
    </div>
)
}

_app.js

import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function MyApp({ Component, pageProps }) {
const router = useRouter()

useEffect(() => {
    const handleRouteChange = (url) => {
        if (window && window._paq) {
            _paq.push(['setCustomUrl', url]);
            _paq.push(['setDocumentTitle', document.title]);
            _paq.push(['trackPageView']);
        }
    }

    router.events.on('routeChangeStart', handleRouteChange)
}, [])

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

Solution 3:[3]

@rap-2-h answer worked great. For including the script in your base page, you can include the matomo script as dangerouslySetInnerHTML inside next.js <Head> component like this:

//import next had
import Head from 'next/head'

export default class Meta extends Component {

    render() {

        return (
          <Head>
            <script type="text/javascript" dangerouslySetInnerHTML={{
                    __html: ` var _paq = window._paq || [];
                    /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
                    _paq.push(['trackPageView']);
                    _paq.push(['enableLinkTracking']);
                  (function () {
                        var u = "https://your_matomo_link";
                        _paq.push(['setTrackerUrl', u + 'matomo.php']);
                        _paq.push(['setSiteId', '1']);
                        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 + 'matomo.js'; s.parentNode.insertBefore(g, s);
                    })();
                `}} />

    </Head>
    )
   }
}

Then add it at the top of your layout or wherever

Solution 4:[4]

To add on top of other answers: You should use the routeChangeComplete event over routeChangeStart in order to get the correct data - with routeChangeStart you will get the page title/url of the previous page.

Complete solution:

_app.js as a functional component:

import { useRouter } from 'next/router'
import { useEffect } from 'react'

export default function App({ Component, pageProps }) {
    const router = useRouter()
    useEffect(() => {
        const handleRouteChange = (url) => {
            if (window && window._paq) {
                _paq.push(['setCustomUrl', url]);
                _paq.push(['setDocumentTitle', document.title]);
                _paq.push(['trackPageView']);
            }
        }

        router.events.on('routeChangeComplete', handleRouteChange)
    }, [])

    return (
        //your code
    )
}

layout.js:

import Head from 'next/head'

export default function Layout({ children }) {
    return (
        <>
            <Head>
                <script type="text/javascript" dangerouslySetInnerHTML={{__html: `
                    var _paq = window._paq = window._paq || [];
                    _paq.push(['trackPageView']);
                    _paq.push(['enableLinkTracking']);
                    (function() {
                    var u="//<YOUR_MATOMO_URL>";
                    _paq.push(['setTrackerUrl', u+'matomo.php']);
                    _paq.push(['setSiteId', '1']);
                    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
                    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
                    })();
                `}} />
            </Head>
            //your code
        </>
    )
}

Alternatively you can use Script from next/script and enclose the js within instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rap-2-h
Solution 2 larswittenberg
Solution 3 gray
Solution 4