SocialGouv / matomo-next

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

Previous page title is being used as action name #132

Open linusjaderlund opened 1 month ago

linusjaderlund commented 1 month ago

Hello 😄

I'm having an issue when tracking data is sent on route change. Problem is that the action name is being set to the previous pages title. So if I go from "A" to "B" and the data is sent for route "B" I get action name "A". Everything else in the data seems to be correct.

I've rewritten the application to set the page title as soon as possible, now it happens as the page is rendered on the server. But the more I optimize the application the more consequential this issue gets.

First: is this an issue or by design? Second: if not by design, how do i solve it?

Initialization happens in _app.tsx withing a custom hook that looks like this:

export const useHandleTracking = () => {
  const cookieService = new CookieService();
  const isStatisticsCookieAccepted = cookieService.isCookieAccepted(CookieType.STATISTICS);
  const { matomoUrl, matomoSiteId }: ApplicationConfig = getConfig().publicRuntimeConfig.application;

  type WindowPaq = Window & typeof globalThis & { _paq: Array<any> };

  useEffect(() => {
    const matomoBrowserObject = (window as WindowPaq)._paq;
    const isInitialized = Array.isArray(matomoBrowserObject) && matomoBrowserObject.length > 0;

    if (isStatisticsCookieAccepted && !isInitialized) {
      init({ url: matomoUrl, siteId: matomoSiteId });
    }
  }, [isStatisticsCookieAccepted, matomoSiteId, matomoUrl]);
};