SocialGouv / matomo-next

Matomo for Next.js applications
Apache License 2.0
155 stars 22 forks source link

With NextJs 13 error setTrackerUrl (setSiteId) is registered more than once #104

Open rich-info opened 1 year ago

rich-info commented 1 year ago

The following error is displayed in the developer console: 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.

Next.Js version 13.4.2

tordans commented 1 year ago

I followed https://www.linkedin.com/pulse/preventing-useeffect-from-running-twice-strict-mode-useref-tingre/ and got rid of the warning with the code below.

It would be nicer to have an unInit function that can be called to cleanup the integration in the hooks return statement or something. Maybe init should be useInit and handle this kind of check internally.

  const matomoInitialized = useRef(false)

  useEffect(() => {
    if (MATOMO_URL && MATOMO_SITE_ID && matomoInitialized.current === false) {
      init({ url: MATOMO_URL, siteId: MATOMO_SITE_ID })
    }
    return () => {
      matomoInitialized.current = true
    }
  }, [])
MaxHjarpe commented 1 year ago
  const matomoInitialized = useRef(false)

  useEffect(() => {
    if (MATOMO_URL && MATOMO_SITE_ID && matomoInitialized.current === false) {
      init({ url: MATOMO_URL, siteId: MATOMO_SITE_ID })
    }
    return () => {
      matomoInitialized.current = true
    }
  }, [])

Thank you! This solved the console error and the issue I had with it registering every page view twice!

revolunet commented 11 months ago

@tordans shouldn't the library just handle mutliple init calls properly ?

laem commented 8 months ago

In case you were wondering, like me, this snippet will let Matomo track the initial page load, but not the subsequent SPA page router changes. It's not enough and the library does not handle this natively for Next 13.

See https://github.com/SocialGouv/matomo-next/issues/99 for WIP solution.