How to Pass Custom dimensions from local code to Matomo analysis Dashboard

I want to need, display the username of login username from the local code to the Motomo dashboard.

  • here this is App/tsx file. I implemented code for fetching username from Microsoft-AD.
useEffect(() => {
      // Function to handle Microsoft login and retrieve user information
    async function handleMicrosoftLogin(): Promise<void> {
  
      try {
        await msalInstance.initialize();
        // Initialize the MSAL instance
        await msalInstance.handleRedirectPromise();
        // Redirect the user to the Microsoft login page
        const loginRequest = {
          scopes: ['user.read'],
        };

        msalInstance.loginRedirect(loginRequest);
    
        // After successful login, handle the redirect back to your website
        const response = await msalInstance.handleRedirectPromise();
        if (response !== null) {
          // Get the user's account information
          const account = msalInstance.getAccountByHomeId(response.account?.homeAccountId);
    
          // Access the user's name and email if the account is not null
          const userName = account?.name ?? 'Unknown';
          const userEmail = account?.idTokenClaims?.emails?.[0] ?? 'Unknown';
    
          // Print the user's name and email in the console log
          console.log('User Name:', userName);
          console.log('User Email:', userEmail);

          // Replace the placeholders in the Matomo script with the actual userName
          const modifiedMatomoScript = `
              var _paq = window._paq = window._paq || [];
              _paq.push(['setCustomDimension', 1, '${userName}']);
          `;

          // Create a new script element
          const script = document.createElement('script');
          script.text = modifiedMatomoScript;

          // Append the script to the document body
          document.body.appendChild(script);
        }
      } catch (error) {
        console.error('An error occurred during Microsoft login:', error);
      }
    }

    handleMicrosoftLogin();
  }, []);
  • this is index.html file.
<!-- Matomo -->
    <script>
      var _paq = window._paq = window._paq || [];
      /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
      _paq.push(["setCookieDomain", "*.localhost"]);
      _paq.push(['setCustomDimension', 1, `${userName}`]);
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
      (function() {
        var u="//localhost:8080/";
        _paq.push(['setTrackerUrl', u+'matomo.php']);
        _paq.push(['setSiteId', '5']);
        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);
      })();
    </script>
  • output of Matomo Dashboard.
    image

  • so how to pass that username from the local code to Matomo Dashboard?

In order to pass the username from your local code to the Matomo Dashboard, you are on the right track by using custom dimensions. However, there’s an issue in your implementation. The userName variable is not defined in the scope where you are trying to use it in the Matomo script.

Here’s how you can modify your code:

// ...

useEffect(() => {
  // Function to handle Microsoft login and retrieve user information
  async function handleMicrosoftLogin(): Promise<void> {
    try {
      await msalInstance.initialize();
      // Initialize the MSAL instance
      await msalInstance.handleRedirectPromise();
      // Redirect the user to the Microsoft login page
      const loginRequest = {
        scopes: ['user.read'],
      };

      msalInstance.loginRedirect(loginRequest);

      // After successful login, handle the redirect back to your website
      const response = await msalInstance.handleRedirectPromise();
      if (response !== null) {
        // Get the user's account information
        const account = msalInstance.getAccountByHomeId(response.account?.homeAccountId);

        // Access the user's name and email if the account is not null
        const userName = account?.name ?? 'Unknown';
        const userEmail = account?.idTokenClaims?.emails?.[0] ?? 'Unknown';

        // Print the user's name and email in the console log
        console.log('User Name:', userName);
        console.log('User Email:', userEmail);

        // Set the custom dimension in Matomo script
        setMatomoScript(userName);
      }
    } catch (error) {
      console.error('An error occurred during Microsoft login:', error);
    }
  }

  // Function to set the Matomo script with custom dimension
  function setMatomoScript(userName: string): void {
    // Replace the placeholders in the Matomo script with the actual userName
    const modifiedMatomoScript = `
      var _paq = window._paq = window._paq || [];
      _paq.push(['setCustomDimension', 1, '${userName}']);
      _paq.push(['trackPageView']);
      _paq.push(['enableLinkTracking']);
    `;

    // Create a new script element
    const script = document.createElement('script');
    script.text = modifiedMatomoScript;

    // Append the script to the document body
    document.body.appendChild(script);
  }

  handleMicrosoftLogin();
}, []);

// ...

This modification ensures that the userName variable is passed to the setMatomoScript function, and then it’s used in the Matomo script to set the custom dimension. Now, the Matomo script will include the correct username when it’s executed on the page.

1 Like