How to get the current page title using Next.js?

Hello guys, first at all, thank you so mucho for your help and support :pray:t5:

I am developing a website using React, Typescript and Next.js 14 (app router) and I could implement the Matomo tracking code successfully.

The issue now is that when I am navigating on my page, the page title is always behind. If I check the history I can see the page title say something but the url is different.

This is the implementation as component loaded in my layout.tsx page.

and the code is:

"use client";

import { useEffect } from "react";

declare global {
  interface Window {
    _mtm: any[];
    _paq: any[];

const Matomo = () => {
  useEffect(() => {
    var _mtm = (window._mtm = window._mtm || []);
    _mtm.push(["setDocumentTitle", document.title]);
    _mtm.push({ "mtm.startTime": new Date().getTime(), event: "mtm.Start" });
    (function () {
      var d = document,
        g = d.createElement("script"),
        s = d.getElementsByTagName("script")[0];
      g.async = true;
      g.src = "env.local.MATOMO_TRACKING_URL";
      if (s && s.parentNode) {
        s.parentNode.insertBefore(g, s);
  }, []);

  return null;

export default Matomo;

I would appreciate any help, suggestions or advice on how to solve this little problem with the logging of the titles of the pages I am visiting.

MrMatomo :pray:t5: