On-Premise Matomo with GTM: First-Party Data for Your Small Store or Project

One of the things I’ve missed since Universal Analytics was discontinued is a real-time dashboard tailored to my needs: cards showing active users, items added to the cart, and orders; a minute-by-minute graph; and a couple of tables listing traffic sources and viewed products. I had this with UA’s custom dashboards and, later, with the free Piwik PRO plan, until they discontinued it. GA4’s real-time data just doesn’t cut it for me.

At La Loma Market, my e-commerce site for extra virgin olive oil, I use GA4 via Google Tag Manager to track analytics. A few weeks ago, I decided to install Matomo on-premise on my own hosting server for three reasons:

  1. Data from our own sources. I want my visitors’ information to remain on my server and not depend on Google’s servers.
  2. Zero cost. Matomo is free software, and I could host it on the hosting service I already pay for, without any additional licenses or payment plans.
  3. A real-time experience just the way I like it. Custom dashboards to track store activity in real time. I didn’t achieve this third goal. We’ll see why later.

In this post, we’re going to install Matomo on a custom subdomain—without using the WordPress plugin—so that the analytics database remains separate from the store’s database. Next, we’ll configure it and replicate the tracking data you already had in GA4, while adhering to the consent settings of our CMP (Consent Management Platform). At the end, you’ll find the GTM container to import into your own.

Starting point: the stack

The idea is to build on what already works: the same data layer that powers GA4 will also power Matomo, and both tools will be covered by the same consent. This is the stack I’m working with:

  • Hosting: SiteGround. Includes PHP 8.2, MySQL databases, SFTP and SSH access, and cron jobs via Site Tools. The link to the hosting service includes my referral code, in case you decide to sign up.
  • Website: WordPress with WooCommerce—the same one we use to experiment with Piwik PRO.
  • Data Layer: The GTM4WP plugin, which publishes e-commerce events to the data layer using the GA4 schema, along with user data such as session status and the number of orders.
  • Tag Management: Google Tag Manager, with GA4 already implemented.
  • Consent: CookieYes, connected to GTM, as we saw in another post.
  • Matomo: Version 5.14 (on-premise), installed on a subdomain of the same hosting account.
Figure 00. Implementation diagram.

Without analytics consent, CookieYes blocks both tags, and nothing is sent to either Google or Matomo.

What You Need and How Long It Takes

With shared hosting like this, it’s enough: Matomo indicates that a single server is sufficient for fewer than 100,000 page views per month. Before you begin, make sure you have:

  • PHP 7.2.5 or later (Matomo recommends the latest 8.x version) and a MySQL or MariaDB database.
  • SFTP access to the hosting account and permission to create subdomains and cron jobs.
  • GTM is already installed on the website, with a consent banner that passes the user’s decision to it.

The installation and basic setup took me about two or three hours, most of which was spent waiting for the files to upload. Replicating the GA4 tracking in GTM will take another afternoon’s worth of work.

There’s one limitation you should be aware of from the start: on SiteGround’s shared plans, each database has a maximum size of 1 GB. For a small online store, that’s plenty for a long time, but I’ll explain below how to schedule the deletion of old data.

Step 1: Set up SiteGround

Matomo will run on its own subdomain, with its own certificate and its own database. Everything is set up through Site Tools.

The subdomain

Go to Domain → Subdomains to create the subdomain. I recommend choosing an non-obvious name that doesn’t include words like “analytics,” “matomo,” or “stats”: many ad-blocker lists include those subdomains and would exclude your metrics. In this post, I’ll usek3x9.tudominio.com as an example. In the screenshots, you’ll see the actual subdomain I used in my installation, but the process is identical.

Image 01. Creating a subdomain in Site Tools.
Image 01. Creating a subdomain in Site Tools.

Next, under Security → SSL Manager, install a Let’s Encrypt certificate for the subdomain. Wait for it to become active and verify that https://k3x9.tudominio.com opens with the padlock icon before continuing: if you install Matomo without HTTPS, you’ll have to fix mixed content warnings later.

Image 02. Let's Encrypt SSL certificate installed for the subdomain.
Image 02. Let’s Encrypt SSL certificate installed for the subdomain.

The database

Under Website → MySQL, we created a database exclusively for Matomo. Don’t share it with the WooCommerce database: that way, the 1 GB limit applies only to analytics, and the store won’t be affected. SiteGround generates the name automatically, and I added the tag ” matomo_analytics ” to identify it.

Image 03. Accessing the MySQL manager from the Site Tools menu.
Image 03. Accessing the MySQL manager from the Site Tools menu.
Figure 04. Creating the database.
Figure 04. Creating the database.
Image 05. Database created, with the tag "matomo_analytics."
Image 05. Database created, with the tag “matomo_analytics.”

On the Users tab, we create a new user—just for Matomo—and assign it to the database with full privileges. Matomo needs to create and modify tables, so read-only access won’t work.

Figure 06. Creating the database user.
Figure 06. Creating the database user.
Figure 07. Assigning the user to the database with full privileges.
Figure 07. Assigning the user to the database with full privileges.

Enter the database name, username, and password into your password manager exactly as SiteGround displays them (including the prefix). You’ll need them in the installer.

Step 2: Upload Matomo via SFTP

Download the latest version from builds.matomo.org, the official repository. Avoid third-party copies: Matomo publishes its GPG signature (the .asc files) along with each release in case you want to verify that no one has tampered with the package.

Image 08. Downloading matomo.zip from builds.matomo.org.
Image 08. Downloading matomo.zip from builds.matomo.org.

When you unzip it on your computer, you’ll see a folder named ” matomo ” that contains another folder named ” matomo.” The one we’re interested in is the inner folder, which contains ” index.php,” ” core,” ” config,” and ” tmp.”

Image 09. Extract the ZIP file to the Downloads folder.
Image 09. Extract the ZIP file to the Downloads folder.

I use WinSCP to upload it, although FileZilla works just as well. When you connect, you’ll see a folder for each domain and subdomain in your account.

Figure 10. SFTP client: locally, the downloaded folder; remotely, the folders for each domain.
Figure 10. SFTP client: locally, the downloaded folder; remotely, the folders for each domain.

Here’s the mistake I made: the files go insidepublic_html from the subdomain, which is what the server publishes, and not in the root of your folder. Upload the contents of the foldermatomo inside, not the folder itself, and if insidepublic_html there is aindex.html Welcome message, delete it so it doesn’t cover theindex.php by Matomo .

Figure 11. The Matomo content goes inside the `public_html` directory of the subdomain.
Figure 11. The Matomo content goes inside the `public_html` directory of the subdomain.
Figure 12. Uploading files with WinSCP.
Figure 12. Uploading files with WinSCP.

There are several thousand small files, so take your time. When you’re done, check the permissions: only tmp and config need to be writable by the server. Don’t apply permissions recursively to the entire directory tree.

Step 3: The Web Installer

When you open https://k3x9.tudominio.com, the Matomo wizard appears: eight steps that, as promised, take about five minutes to complete.

Figure 13. Installer welcome screen.
Figure 13. Installer welcome screen.

1. System check. Matomo checks the PHP version, extensions, and permissions. If anything appears in red, it tells you exactly what’s missing; PHP extensions are enabled in Site Tools, under Devs → PHP Manager.

    Figure 14. System check passed.
    Figure 14. System check passed.

    2. Database. Use the server 127.0.0.1 (or localhost) as suggested. The username and database are the same as in Step 1, with the prefix added by SiteGround. The table prefix matomo_ and the adapter PDO\MYSQL remain unchanged.

    Figure 15. Database connection information.
    Figure 15. Database connection information.
    Figure 16. Tables created.
    Figure 16. Tables created.

    3. Superuser. This is the account you’ll use to log in to Matomo; it’s different from the database user. Avoid obvious names like admin; use a long password generated by your password manager and an email address you actually check, because that’s how you’ll recover access and receive security alerts.

    Figure 17. Creating the superuser.
    Figure 17. Creating the superuser.

    4. First website. Name, URL, time zone, and, for a store, e-commerce functionality.

    Figure 18. Setting up the first website with e-commerce enabled.
    Figure 18. Setting up the first website with e-commerce enabled.

    5. Tracking code. Don’t paste it into the topic: we’ll implement it using GTM. Note down the site ID (for the first website, 1) and your Matomo URL.

    Figure 19. Tracking code generated by Matomo.
    Figure 19. Tracking code generated by Matomo.
    Figure 20. Available integration options, including Google Tag Manager.
    Figure 20. Available integration options, including Google Tag Manager.

      Once we’re done, we’ll be taken to the login screen. Since Matomo detects that the website already has GTM, the first thing it suggests is installing the code using a custom HTML tag. That guide is a good starting point, and in step 7, we’ll go quite a bit further.

      Figure 21. Logging in as the superuser.
      Figure 21. Logging in as the superuser.
      Figure 22. Matomo detects GTM and recommends it as a tracking method.
      Figure 22. Matomo detects GTM and recommends it as a tracking method.
      Figure 23. Matomo guide for installing the code as custom HTML in GTM.
      Figure 23. Matomo guide for installing the code as custom HTML in GTM.

      Step 4: Basic Configuration in Matomo

      All settings are located in the gear icon in the top menu, which opens the Settings page.

      Figure 24. Access to Matomo Administration.
      Figure 24. Access to Matomo Administration.

      The website

      Under “Websites” → “Manage, ” we edit the website using the pencil icon. Here, we enable e-commerce and internal search tracking, and we review the currency and time zone. The default search settings already include the WordPress search engine’s s; I added mot_q, which is my store’s URL. With this setup, you don’t need any tags to track searches.

      Figure 25. Website Management.
      Figure 25. Website Management.
      Figure 26. Site-wide search, e-commerce, currency, and time zone.
      Figure 26. Site-wide search, e-commerce, currency, and time zone.

      Global Settings

      Under “Websites” → “Settings,” you’ll find the settings that affect all websites:

      • Excluded IP addresses: Add yours so your tests don’t skew the data. Matomo displays it on the same screen.
      • URL parameters to exclude: The ” Common session parameters ” option removes session identifiers from URLs.
      • User agents to exclude: Using /bot|spider|crawl|scanner/i filters out a large number of bots.
      • Excluded referrers: a must-have for any online store. Add your payment gateways (in my case, paypal.com, redsys.com, and stripe.com) and your own domain. Otherwise, when the customer returns after making a payment, Matomo will open a new session and attribute the sale to the payment gateway.
      • Default time zone and currency for sites you add in the future.
      Figure 27. Excluded IP addresses, URL parameters, and user agents.
      Figure 27. Excluded IP addresses, URL parameters, and user agents.
      Figure 28. Excluded referrers and internal search parameters.
      Figure 28. Excluded referrers and internal search parameters.
      Figure 29. Default time zone and currency.
      Figure 29. Default time zone and currency.

      Privacy, Users, and Security

      • Privacy Manager: Under System → General Settings, we link to the website’s privacy policy and terms and conditions.
      • IP anonymization: under Privacy → Anonymize Data. On that same screen, you’ll find the option to periodically delete raw data, which protects you from the 1 GB limit. Enable it once the cron-based archiving has been running for a few days—never before: if data that hasn’t been processed yet is deleted, it will be lost.
      • Users: Under System → Users, you can invite other people and grant them read-only access.
      • Two-factor authentication: Enable two-step authentication for the superuser in Personal → Security. Since this is your own installation and it’s exposed to the internet, this is the measure that provides the most protection with the least effort.
      • Brand: In the Branding Settings, you can replace the Matomo logo with your own.
      Figure 30. Links to the privacy policy and the terms and conditions.
      Figure 30. Links to the privacy policy and the terms and conditions.
      Figure 31. Managing users with access to Matomo.
      Figure 31. Managing users with access to Matomo.

      Artificial Intelligence and Add-ons

      Version 5.14 introduces new features in this area. Under System → AI Providers, you can connect Anthropic, Google, OpenAI, AWS Bedrock, or your own endpoint for Matomo’s AI features; I haven’t connected any of them yet. In Manage Plugins, you can enable and disable modules; among the ones that come standard is BotTracking, which analyzes visits from chatbots like ChatGPT.

      Figure 32. AI providers available in Matomo.
      Figure 32. AI providers available in Matomo.
      Figure 33. Add-on Management.
      Figure 33. Add-on Management.

      Step 5: Archiving Reports with cron

      Matomo stores each raw visit and, separately, calculates the aggregated reports in a process called archiving. By default, it runs this process every time someone opens the dashboard, which on shared hosting results in slow dashboards and spikes in server load. It is recommended that this be done via a scheduled task.

      First, we create the task in Site Tools, under Devs → Cron Jobs. I have it set to run every 30 minutes, which is more than enough for my needs:

      */30 * * * *
      cd /home/customer/www/k3x9.tudominio.com/public_html && php console core:archive --url=https://k3x9.tudominio.com/ > /dev/null 2>&1

      The first line is the frequency, and the second is the command, which must be entered as a single line. Replace the subdomain with your own and check the path in File Manager.

      Figure 34. Cron job for archiving in Site Tools.
      Figure 34. Cron job for archiving in Site Tools.

      Once you see that the task is running without errors (the most recent run appears under Diagnostics → System Check ), go to System → General Settings → Archiving Settings and disable archiving from the browser. In the field below, 1,800 seconds limits how often the daily reports are recalculated.

      Figure 35. Archiving disabled in the browser: managed by the cron job.
      Figure 35. Archiving disabled in the browser: managed by the cron job.

      The real-time visitor log and the map read the raw data, so they continue to function in real time. What is updated via cron are the aggregated reports: the summary, products, sales, etc.

      Step 6: Custom Dimensions

      Before you start using GTM, you should decide which dimensions you’re going to send, because Matomo is more limited than GA4: by default, it offers 5 visit dimensions and 5 action dimensions (later on, you’ll see that there are 10 of each—you’ll see why). The visit dimensions describe the user throughout the entire visit; the action dimensions describe each page or event.

      When I reviewed my 31 GA4 dimensions, most of them were unnecessary because Matomo already covers them by default:

      • Client and session identifiers are internal to GA4.
      • The category, action, and tag of events make up the native structure of Matomo events.
      • The text and URL of the links appear in the outbound links and downloads reports.
      • The previous page and the pages before that are listed in the visit log and the Transitions report.
      • The user ID has its own field: I pass it the SHA-256 hash of the email address published by GTM4WP.

      With what remains, the distribution fills in the gaps provided by Matomo. Create them under Websites → Custom Dimensions, marked as active and without extractions:

      IDNameScopeDataLayer Key (GTM4WP)
      1visitorLoginStateVisitvisitorLoginState
      2visitorTypeVisitvisitorType
      3customerTotalOrdersVisitcustomerTotalOrders
      4customerTotalOrderValueVisitcustomerTotalOrderValue
      5pagePostTypeActionpagePostType
      6pageCategoryActionpageCategory
      7pagePostAuthorActionpagePostAuthor
      8pageAttributesActionpageAttributes

      Matomo assigns IDs in the order they are created and shares them across both scopes. If you create them in this order, the IDs will match those in the container you can download at the end; if not, simply change them in the main tag.

      Figure 36. Custom Dimensions screen, still blank.
      Figure 36. Custom Dimensions screen, still blank.

      If you need more slots

      In my case, I needed two more dimensions to measure the store’s search filters, and I ran out of space. The columns can only be expanded from the Matomo console by connecting to the hosting server via SSH using PowerShell on your computer. From the Matomo folder, one command per scope:

      php console customdimensions:add-custom-dimension --scope=visit --count=5
      php console customdimensions:add-custom-dimension --scope=action --count=5

      Each one requests confirmation and adds five fields to the specified domain. Since this modifies the database schema, do it at the beginning, when the tables are empty. That is why, in the screenshot above, you see 10 dimensions available in each domain instead of 5.

      Figure 37. Viewing the dimensions in detail from the Matomo console.
      Figure 37. Viewing the dimensions in detail from the Matomo console.

      Step 7: Implementation in GTM with CookieYes

      Matomo uses first-party cookies (_pk_id, _pk_ses, _pk_ref) to recognize visitors, so I treat it the same way as GA4: it only loads if the user accepts analytics cookies. Matomo has cookie-free modes and its own consent mechanisms, but whether consent is required for tracking depends on the discretion of each data protection authority, and I preferred not to take any chances.

      The Consent Pattern

      All Matomo tags use the same triggers (including consent) as GA4 in my container:

      • Trigger: the custom event ` cookie_consent_update`, which CookieYes sends to the dataLayer.
      • Exception: A custom event that occurs when the ` cookieyes-consent ` cookie contains ` analytics:no`. If the user opts out of analytics, the tag does not fire.
      Image 38. The Matomo tag in GTM with the custom variables defined, along with the CookieYes trigger and the exception.
      Image 38. The Matomo tag in GTM with the custom variables defined, along with the CookieYes trigger and the exception.

      The parts of the container

      In addition to the triggers, the following variables are required:

      • The ” VAR - const - Matomo subdomain ” constant with your Matomo URL
      • The constant ` VAR - const - ID Matomo ` with the site ID
      • The built-in variable ” Container ID.”

      With these, no label has handwritten information, and the container can be reused as is.

      TagTriggerWhat is sent to Matomo
      Matomo – Generalcookie_consent_updatePage views, user ID, dimensions, clicks on outbound links, and downloads
      Matomo – E-commerce EventsThe ten GA4 e-commerce EventsProduct and category pages, shopping cart, order, and checkout steps
      Matomo – CF7 Submissiongtm4wp.contactForm7SubmittedForm Submission Event
      Matomo – Log Ingtm4wp.userLoggedInLogin Event
      Matomo – Registrationgtm4wp.userRegisteredRegistration Event

      There are a few more in my container: for the WhatsApp chat, stock-restock notifications, pop-ups, the “Share Article” button, and the store filters. They all follow the same pattern as the form and session ones.

      Figure 39. Matomo tags in the GTM workspace.
      Figure 39. Matomo tags in the GTM workspace.

      If you have any questions or need additional customization, you can use both this post and the Matomo documentation to help you with your preferred AI. I’ve done this myself for both the implementation and the writing of this post.

      How Tags Read Data

      The tags are custom HTML and read the dataLayer directly through GTM’s internal data model:

      var gtm = (window.google_tag_manager || {})['{{Container ID}}'];
      var dl = gtm && gtm.dataLayer;
      var ecommerce = dl.get('ecommerce');

      It has two advantages. The first is that window.dataLayer shows only the history of everything that has been pushed, whereas dataLayer.get() returns the current, merged value—the same value that a data layer variable would read. The second is that a value enclosed in quotes—such as a product name—doesn’t break the script, which can happen if you paste {{variables}} directly into the code.

      Another detail that caused me a validation error—and one you should always keep in mind—is that GTM’s custom HTML only supports ES5 JavaScript. No backticks, ` let`, ` const `, or arrow functions—or GTM won’t let you publish.

      E-commerce

      The e-commerce tag maps the GA4 events published by GTM4WP to Matomo functions:

      GA4 EventIn Matomo
      view_itemProduct View
      view_item_listCategory View
      select_item, add_to_cart, remove_from_cartEvent, with the product and the amount
      view_cart, begin_checkout, add_shipping_info, add_payment_infoEvent and Full Cart Update
      purchaseOrder, including products, taxes, and shipping

      For the order, the tag stores the transaction ID in the browser session and does not resend it if the customer refreshes the confirmation page.

      Step 8: Check that everything is working

      Before publishing the container, run a round of tests with the GTM preview and Matomo open in another tab. If you excluded your IP address in step 4, remove it while testing, or you won’t be able to see the results.

      1. GTM preview. The “General” tag fires after cookie_consent_update, and the URL and Matomo ID appear as resolved values in the “Variables” tab.
      2. Accepting the analytics. Under Visitors → Matomo Visit Log, your visit appears within seconds, along with the dimensions and events.
      3. By rejecting it. No requests are received, and no ” _pk_” cookie is created in the browser (Developer Tools → Application → Cookies).
      4. A test order. It appears under E-commerce → Order List, with the correct amount. Compare it with WooCommerce to see if the total includes or excludes taxes and shipping.
      5. A shopping cart with no items in it. If you add items to your cart and then leave, the visit will be recorded as an abandoned cart.
      Figure 40. Test visit in the Matomo visit log, showing its dimensions and events.
      Figure 40. Test visit in the Matomo visit log, showing its dimensions and events.

      Real Time: What I Was Looking For and What I Found

      Let’s go back to the third objective. Here’s what I had before: a Piwik PRO dashboard with cards for the funnel (active users, added to cart, checkout, shipping, payment, and orders), a minute-by-minute chart, and tables for pages, sources, and products—all filterable. And before that, a similar dashboard in Universal Analytics.

      Figure 41. Real-time purchase funnel dashboard in Piwik PRO.
      Figure 41. Real-time purchase funnel dashboard in Piwik PRO.
      Figure 42. Real-time e-commerce dashboard in Universal Analytics.
      Figure 42. Real-time e-commerce dashboard in Universal Analytics.

      Matomo’s real-time features consist of three components: the real-time visitor log, which updates every five seconds and displays each visit along with its pages and source; the real-time map; and visitor counters for the last 30 minutes and the last 24 hours. You can set up a dashboard with these and other widgets, but those other widgets depend on archived data, and there are no minute-by-minute cards or charts filtered by event.

      For what I was looking for, it falls short. I also haven’t thoroughly explored the rest of the Matomo interface, the GA4 importer, or the Data Studio connector: I’ll save those for when I’ve accumulated more data and can dedicate a separate post to them.

      Figure 43. Matomo real-time dashboard.
      Figure 43. Matomo real-time dashboard.

      Before giving up, I looked into other free—or nearly free—options:

      OptionWhat It OffersWhy not, for now
      GA4 + BigQuery Streaming + Data StudioCharts, graphs, and tables with data from just a few minutes agoStreaming exports cost money (not much, but still), you have to write SQL, and the report refreshes every few minutes
      Grafana or Metabase based on the Matomo databaseCustom panels, refreshed every minuteYou must open the MySQL database on the shared hosting account to external connections and have the tool running on your own computer
      PostHog, free planPanels with automatic refresh and one million events per monthIt’s just another tool and another tag, with its own event settings

      PostHog is the next one I want to try, so there will likely be a second part. Even so, Matomo is here to stay: the first two goals—our own data and zero cost—have been met.

      Considerations and limitations

      • The data belongs to you, but the stack still goes through third parties. GTM is loaded from Google’s servers, and CookieYes is another provider. If you want to do without them, Matomo comes with its own tag manager, which is served from your domain.
      • Incomplete abandoned carts. GTM4WP only sends the added product via add_to_cart, and Matomo requires the entire cart for each update. That’s why the cart is updated via view_cart and the checkout steps, and anyone who adds a product and leaves without opening the cart is not counted as an abandoned cart.
      • The order of the product view. Matomo associates the product view with the subsequent page view. If, on your website view_item, the product view occurs after the “General” tag, the tag records it as an event so it isn’t lost.
      • Dimensions do not travel in all events. In GA4, I attached all parameters to each event. In Matomo, visit parameters are carried over throughout the entire visit, and action parameters are associated with the page view.
      • The 1 GB limit. Schedule the deletion of old raw data in Privacy → Anonymize Data, and monitor the database size in Site Tools.
      • You are responsible for maintenance. You are responsible for installing Matomo updates, including security updates. Keep email notifications enabled.
      • Privacy Policy. Mention Matomo and its cookies, and if you use the user ID, note that it is a hash of the email address: it is pseudonymized data, not anonymous.

      Materials for download

      Here’s the GTM container with everything we’ve covered, ready to import:

      • The two Matomo constants, with example values that you should replace with your own.
      • The CookieYes cookie variable and the embedded Container ID variable.
      • Consent triggers, the ten e-commerce event triggers, and the GTM4WP form, login, and registration triggers.
      • The five Matomo tags, grouped into a folder.

      To import it, in GTM go to Admin → Import Container, select a new workspace and choose the ” Merge” option, renaming any conflicting elements. Then change the values of the two constants, verify that the dimension IDs match those in your Matomo, and test it in preview mode before publishing.

      The container assumes that in GTM4WP, you have enabled page and user data, integration with WooCommerce for customer data, integration with Contact Form 7, and tracking for logins and registrations.

      I hope you find this useful. What about you? Do you have your own analytics at home, or do you still rely on Google?

      References

      Official Matomo documentation (in English).

      Installation and Maintenance

      Custom Dimensions

      Consent and GTM

      E-commerce

      Leave a Comment