Published on

How to fix Next.js error Matomo setTrackerUrl registered more than once in _paq variable?

Authors

How to fix Next.js error: 'setTrackerUrl is registered more than once'

Website performance analytics provide insights into how users interact with your website. Matomo analytics (formerly Piwik) is a powerful open-source web analytics platform that provides detailed insights into website traffic and user behavior. It offers a wide range of features, including real-time monitoring, customizable reports, and data privacy control. When using it with Next.js version 13.x, however, I received an error message and would like to explain a simple solution here.

With Next.js you can use the npm package @socialgouv/matomo-next.

npm i @socialgouv/matomo-next

The package works very well with the Next.js version 12.x. But with the new version 13.4.x you get an error message. However, the tracking still works.

Do you also receive the error message "The method setTrackerUrl (setSiteId) is registered more than once in "_paq" variable. Only the last call has an effect. Please have a look at the multiple Matomo trackers documentation" on your developer console?

What can you do to solve this problem?

Correct the affected part of the code.

const containsElement = (arr: Array<any>, param1: string, param2: string): boolean => {
  return arr.some((item) => item[0] === param1 && item[1] === param2)
}

const trackerUrlSetting = ['setTrackerUrl', `${url}/${phpTrackerFile}`]
const siteIdSetting = ['setSiteId', siteId]

if (!containsElement(window._paq, trackerUrlSetting[0], trackerUrlSetting[1])) {
  push(trackerUrlSetting)
}
if (!containsElement(window._paq, siteIdSetting[0], siteIdSetting[1])) {
  push(siteIdSetting)
}

The error message is no longer displayed because the push of the values only takes place after a check.