Matomo
Help for users with high traffic websites
For medium and high traffic websites there are certain optimizations that should be made to help Matomo run faster (such as setting up auto-archiving).
https://matomo.org/docs/optimize/
https://developer.matomo.org/guides/tracking-javascript-guide
Single-Page Application Tracking
JavaScript Tracking Client
You can use the JavaScript tracking client to track any application that supports JavaScript: for example websites!
This guide will explain how you can use the JavaScript tracking client to customize the way some of the web analytics data is recorded in Matomo (formerly Piwik).
Finding the Matomo Tracking Code
To use all the features described in this page, you need to use the latest version of the tracking code. To find the tracking code for your website, follow the steps below:
- log in to Matomo with your admin or Super User account
- click on your username in the top right menu, and click Settings to access the administration area
- click on Tracking Code in the left menu
- copy and paste the JavaScript tracking code into your pages, just after the opening
<body>
tag (or within the<head>
section)
The tracking code looks as follows:
<!-- Matomo -->
<script type="text/javascript">
var _paq = window._paq = window._paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//{$MATOMO_URL}/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', {$IDSITE}]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<!-- End Matomo Code -->
In your tracking code, {$MATOMO_URL}
would be replaced by your Matomo URL and {$IDSITE}
would be replaced by the idsite of the website you are tracking in Matomo.
This code might look a bit strange to those of you familiar with JavaScript, but that is because it is made to run asynchronously. In other words, browsers will not wait for the matomo.js
file to be downloaded in order to show your page.
For asynchronous tracking, configuration and tracking calls are pushed onto the global _paq
array for execution, independent of the asynchronous loading of matomo.js
. The format is:
_paq.push([ 'API_method_name', parameter_list ]);
You can also push functions to be executed. For example:
var visitor_id;
_paq.push([ function() { visitor_id = this.getVisitorId(); }]);
or for example, to fetch a custom variable (name, value) using the asynchronous code:
_paq.push(['setCustomVariable','1','VisitorType','Member']);
_paq.push([ function() { var customVariable = this.getCustomVariable(1); }]);
You can push to the _paq
array even after the matomo.js
file has been loaded and run.
If your Matomo tracking code doesn't look like this one, you may be using the deprecated version. Older versions still work as expected and will track your visitors, but we highly recommend that you update your pages to use the most recent tracking code.
Requirements
Supported browsers
The JavaScript tracker runs on all browsers that support the JSON
API. This includes IE8 and higher. Click here to see a full list of supported browsers.. If you need to support IE7 and older then you could load a polyfill that makes window.JSON
available such as JSON3. This polyfill would need to be loaded before the Matomo JS tracker is loaded.
Known incompatibility issues
- prototype js library overwrites the browser's JSON API and causes issues for example with custom variables resulting in errors (see #16596). Workarounds are to either remove the prototype JS library or to overwrite the JSON object manually (see above e.g. using JSON3).
JavaScript tracker features
Custom page title
By default Matomo uses the title of the HTML page to track the page title, you can customise it by using the function setDocumenTitle
:
_paq.push(['setDocumentTitle', document.title]);
_paq.push(['trackPageView']);
If you track multiple sub-domains in the same website, you may want your page titles to be prefixed by the sub-domain make it easy for you to see the traffic and data for each sub-domain. You can do so simply:
_paq.push(['setDocumentTitle', document.domain + "/" + document.title]);
_paq.push(['trackPageView']);
Advanced users can also dynamically generate the page name, for example, using PHP:
_paq.push(['setDocumentTitle', "<?php echo $myPageTitle ?>"]);
_paq.push(['trackPageView']);
Custom page URL
By default, Matomo uses the URL of the current page as the Page URL in reports. You can customise the page URL to track by using the function setCustomUrl
, learn more in the FAQ How do I set a custom URL using the Matomo Javascript tracker?
Manually trigger events
By default, Matomo tracks page views when the JavaScript tracking code loads and executes on each page view.
However, on modern web applications, user interactions do not necessarily involve loading a new page. For example, when users click on a JavaScript link, or when they click on a tab (which triggers a JS event), or when they interact with elements of the user interface, you can still track these interactions with Matomo.
To track any user interaction or click with Matomo, you can manually call the JavaScript function trackEvent()
. For example, if you wanted to track a click on a JavaScript menu, you could write:
<a href="#" onclick="_paq.push(['trackEvent', 'Menu', 'Freedom']);">Freedom page</a>
You can learn more about Tracking Events in the user guide.
Manually trigger goal conversions
By default, Goals in Matomo are defined as "matching" parts of the URL (starts with, contains, or regular expression matching). You can also track goals for given page views, downloads, or outlink clicks.
In some situations, you may want to register conversions on other types of actions, for example:
- when a user submits a form
- when a user has stayed more than a given amount of time on the page
- when a user does some interaction in your Flash application
- when a user has submitted his cart and has done the payment: you can give the Matomo tracking code to the payment website which will then register the conversions in your Matomo database, with the conversion's custom revenue
To trigger a goal conversion:
// logs a conversion for goal 1
_paq.push(['trackGoal', 1]);
You can also register a conversion for this goal with a custom revenue. For example, you can generate the call to trackGoal()
dynamically to set the revenue of the transaction:
// logs a conversion for goal 1 with the custom revenue set
_paq.push(['trackGoal', 1, <?php echo $cart->getCartValue(); ?>]);
Find more information about goal tracking in Matomo in the documentation.
Accurately measure the time spent on each page
By default, when a user visits only one page view during a visit, Matomo will assume that the visitor has spent 0 second on the website. This has a few consequences:
- when the visitor views only one page view, the "Visit duration" will be 0 second.
- when the visitor views more than one page, then the last page view of the visit will have a "Time spent on page" of 0 second.
It is possible to configure Matomo so that it accurately measures the time spent in the visit. To better measure time spent in the visit, add to your JavaScript code the following:
// accurately measure the time spent in the visit
_paq.push(['enableHeartBeatTimer']);
Matomo will then send requests to count the actual time spent in the visit, as long as the user is actively viewing the page (i.e. when the tab is active and in focus). The heart beat request is executed when:
- switching to another browser tab after the current tab was active for at least 15 seconds (can be configured see below).
- navigating to another page within the same tab.
- closing the tab.
// Change how long a tab needs to be active to be counted as viewed in seconds/
// Requires a page to be actively viewed for 30 seconds for any heart beat request to be sent.
_paq.push(['enableHeartBeatTimer', 30]);
Note: When testing the heart beat timer, remember to make sure the browser tab has focus and not eg. the developer tools or another panel.
Ecommerce tracking
Matomo allows for advanced and powerful Ecommerce tracking. Check out the Ecommerce Analytics documentation for more information about Ecommerce reports and how to set up Ecommerce tracking.
Internal search tracking
Matomo offers advanced Site Search Analytics feature, letting you track how your visitors use your internal website search engine. By default, Matomo can read URL parameters that will contain the search keyword. However, you can also record the site search keyword manually using the JavaScript function trackSiteSearch(...)
In your website, in standard pages, you would typically have a call to record Page views via matomoTracker.trackPageView()
. On your search result page, you would call instead piwikTracker.trackSiteSearch(keyword, category, searchCount)
function to record the internal search request. Note: the 'keyword' parameter is required, but category and searchCount are optional.
_paq.push(['trackSiteSearch',
// Search keyword searched for
"Banana",
// Search category selected in your search engine. If you do not need this, set to false
"Organic Food",
// Number of results on the Search results page. Zero indicates a 'No Result Search Keyword'. Set to false if you don't know
0
]);
// We recommend not to call trackPageView() on the Site Search Result page
// _paq.push(['trackPageView']);
We also highly recommend to set the searchCount parameter, as Matomo will specifically report "No Result Keywords", ie. Keywords that were searched, but did not return any result. It is usually very interesting to know what users search for but can't find (yet?) on your website. Learn more about Site Search Analytics in the User Doc.
Custom variables
Custom variables are a powerful feature that enable you to track custom values for each visit, and/or each page view. Please see the Tracking custom variables documentation page for general information.
You can set up up to 5 custom variables (name and value) for each visit to your website, and/or up to 5 custom variables for each page view. If you set a custom variable to a visitor, when they come back one hour or two days later, it will be a new visit and their custom variables will be empty.
There are two "scopes" which you can set your custom variables to. The "scope" is the 4th parameter of the function setCustomVariable()
.
- when scope = "visit", the custom variable's name and value will be stored in the visit in the database. You can therefore store up to 5 custom variables of scope "visit" for each visit.
- when scope = "page", the custom variable's name and value will be stored for the page view being tracked. You can therefore store up to 5 custom variables of scope "page" for each page view.
The "index" parameter is the custom variable slot index, an integer from 1 to 5. (note: read this FAQ if you need more than the default 5 slots).
Custom variable statistics are reported in Matomo under Visitors > custom variables. Both custom variables of scope "visit" and "page" are aggregated in this report.
Custom variables for visits
setCustomVariable(index, name, value, scope = "visit")
This function is used to create, or update a custom variable name and value. For example, imagine you want to store in each visit the gender of the user. You would store the custom variable with a name = "gender", value = "male" or "female".
Important: a given custom variable name must always be stored in the same "index". For example, if you choose to store the variable name = "Gender" in index = 1 and you record another custom variable in index = 1, then the "Gender" variable will be deleted and replaced with the new custom variable stored in index 1.
_paq.push(['setCustomVariable',
// Index, the number from 1 to 5 where this custom variable name is stored
1,
// Name, the name of the variable, for example: Gender, VisitorType
"Gender",
// Value, for example: "Male", "Female" or "new", "engaged", "customer"
"Male",
// Scope of the custom variable, "visit" means the custom variable applies to the current visit
"visit"
]);
_paq.push(['trackPageView']);
You only need to set a variable with scope "visit" once, and the value will be recorded for the whole visit.
Custom variable for page views
setCustomVariable(index, name, value, scope = "page")
As well as tracking custom variables for "visits", it is sometimes useful to track custom variables for each page view separately. For example, for a "News" website or blog, a given article may be categorized into one or several categories. In this case, you could set one or several custom variables with name="category"
, one with value="Sports"
and another with value="Europe"
if the article is classified in Sports and Europe Categories. The custom variables report will then report on how many visits and page views were in each of your website's categories. This information can be difficult to obtain with standard Matomo reports because they report on "Best Page URLs" and "Best Page Titles" which might not contain the "category" information.
// Track 2 custom variables with the same name, but in different slots.
// You will then access the statistics about your articles' categories in the 'Visitors > custom variables' report
_paq.push(['setCustomVariable', 1, 'Category', 'Sports', 'page']);
// Track the same name but in a different Index
_paq.push(['setCustomVariable', 2, 'Category', 'Europe', 'page']);
// Here you could track other custom variables with scope "page" in Index 3, 4 or 5
// The order is important: first setCustomVariable is called and then trackPageView records the request
_paq.push(['trackPageView']);
Important: It is possible to store a custom variables of scope "visit" in "index" 1, and store a different custom variable of scope "page" in the same "index" 1. Therefore, you can technically track up to 10 custom variables names and values on every page of your website (5 with a "page" scope stored in the actual page view, 5 with a "visit" scope stored in the visit).
_paq.push(['setCustomVariable',
// Index, the number from 1 to 5 where this custom variable name is stored for the current page view
1,
// Name, the name of the variable, for example: Category, Sub-category, UserType
"category",
// Value, for example: "Sports", "News", "World", "Business", etc.
"Sports",
// Scope of the custom variable, "page" means the custom variable applies to the current page view
"page"
]);
_paq.push(['trackPageView']);
Deleting a custom variable
deleteCustomVariable(index, scope)
If you created a custom variable and then decide to remove this variable from a visit or page view, you can use deleteCustomVariable.
To persist the change in the Matomo server, you must call the function before the call to trackPageView();
_paq.push(['deleteCustomVariable', 1, "visit"]); // Delete the variable in index 1 stored for the current visit
_paq.push(['trackPageView']);
Retrieving a custom variable
getCustomVariable(index, scope)
This function can be used to get the custom variable name and value. By default, it will only work for custom variables that were set during the same page load.
Note: it is possible to configure Matomo so that getCustomVariable
will also return the name and value of a custom variable of scope "visit", even when it was set in a previous pageview in the same visit. To enable this behavior, call the JavaScript function storeCustomVariablesInCookie
before the call to trackPageView
. This will enable the storage of Custom Variables of scope "visit" in a first party cookie. The custom variables cookie will be valid for the duration of the visit (30 minutes after the last action). You can then retrieve the custom variable names and values using getCustomVariable
. If there is no custom variable in the requested index, it will return false.
_paq.push([ function() {
var customVariable = this.getCustomVariable( 1, "visit" );
// Returns the custom variable: [ "gender", "male" ]
// do something with customVariable...
}]);
_paq.push(['trackPageView']);
Custom Dimensions
Custom Dimensions are a powerful feature that enable you to track custom values for each visit, and/or each action (page view, outlink, download). This feature is not shipped with Matomo directly but can be installed as a plugin via the Matomo Marketplace (CustomDimensions plugin). Before you can use a Custom Dimension you need to install the plugin and configure at least one dimension, see the Custom Dimensions guide. You will get a numeric ID for each configured Custom Dimension which can be used to set a value for it.
Tracking a Custom Dimension across tracking requests
To track a value simply specify the ID followed by a value:
_paq.push(['setCustomDimension', customDimensionId = 1, customDimensionValue = 'Member']);
Please note once a Custom Dimension is set, the value will be used for all following tracking requests and may lead to inaccurate results if this is not wanted. For example if you track a page view, the Custom Dimension value will be as well tracked for each following event, outlink, download, etc. within the same page load. Calling this method will not actually trigger a tracking request, instead the values will be sent along with the following tracking requests. To delete a Custom Dimension value after a tracking request call _paq.push(['deleteCustomDimension', customDimensionId]);
Setting a custom dimension for the initial page view
To set a custom dimension for the initial page view, make sure to position the method call setCustomDimension
before trackPageView
:
_paq.push(['setCustomDimension', customDimensionId = 1, customDimensionValue = 'Member']);
_paq.push(['trackPageView']);
// _paq.push(['enableLinkTracking']);
// rest of tracking code
Tracking a Custom Dimension for one specific action only
It is possible to set a Custom Dimension for one specific action only. If you want to track a Page view, you can send one or more specific Custom Dimension values along with this tracking request as follows:
_paq.push(['trackPageView', pageTitle, {dimension1: 'DimensionValue'}]);
To define a dimension value pass an object defining one or multiple properties as the last parameter (make sure to specify all parameters as defined in the method, we do not automatically assume the last parameter is customData but instead all parameters that a method defines need to be passed to each method). The property name for a dimension starts with dimension
followed by a Custom Dimension ID, for example dimension1
. The same behaviour applies for several other methods:
_paq.push(['trackEvent', category, action, name, value, {dimension1: 'DimensionValue'}]);
_paq.push(['trackSiteSearch', keyword, category, resultsCount, {dimension1: 'DimensionValue'}]);
_paq.push(['trackLink', url, linkType, {dimension1: 'DimensionValue'}]);
_paq.push(['trackGoal', idGoal, customRevenue, {dimension1: 'DimensionValue'}]);
The advantage is that the set dimension value will be only used for this particular action and you do not have to delete the value after a tracking request. You may set multiple dimension values like this:
_paq.push(['trackPageView', pageTitle, {dimension1: 'DimensionValue', dimension4: 'Test', dimension7: 'Value'}]);
Retrieving a Custom Dimension value
getCustomDimension(customDimensionId)
This function can be used to get the value of a Custom Dimension. It will only work if a Custom Dimension was set during the same page load.
User ID
User ID is a feature in Matomo that lets you connect together a given user's data collected from multiple devices and multiple browsers. There are two steps to implementing User ID:
- You must assign a unique and persistent non-empty string that represents each logged-in user. Typically, this ID will be an email address or a username provided by your authentication system.
- You must set the user ID for each pageview, otherwise the pageview will be tracked without the user ID set.
- You must then pass this User ID string to Matomo via the
setUserId
method call just before calling any of thetrack*
functions (trackPageview
,trackEvent
,trackGoal
,trackSiteSearch
, etc.) for example:
_paq.push(['setUserId', 'USER_ID_HERE']);
_paq.push(['trackPageView']);
Note: USER_ID_HERE
must be a unique and persistent non-empty string that represents a user across devices.
When user is logged in, set the User ID
Let's take an example. Imagine that your website authenticate your users via a login form using a PHP script. Here is what your Matomo JavaScript snippet may look like:
var _paq = window._paq = window._paq || [];
<?php
// If user is logged-in then call 'setUserId'
// $userId variable must be set by the server when the user has successfully authenticated to your app.
if (isset($userId)) {
echo sprintf("_paq.push(['setUserId', '%s']);", $userId);
}
?>
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
When user logs out, reset User ID
When the user has logged out and a User ID is not available anymore, it is recommended to notify Matomo by calling the resetUserId
method before trackPageView
.
If you want to create a new visit when your users logout, then you can also force Matomo to create a new Visit by calling resetUserId
and appendToTrackingUrl
(twice) as below:
// User has just logged out, we reset the User ID
_paq.push(['resetUserId']);
// we also force a new visit to be created for the pageviews after logout
_paq.push(['appendToTrackingUrl', 'new_visit=1']);
_paq.push(['trackPageView']);
// we finally make sure to not again create a new visit afterwards (important for Single Page Applications)
_paq.push(['appendToTrackingUrl', '']);
Content Tracking
There are several ways to track content impressions and interactions manually, semi-automatically and automatically. Please be aware that content impressions will be tracked using bulk tracking which will always send a POST
request, even if GET
is configured which is the default. For more details have a look at the in-depth guide to Content Tracking.
Track all content impressions within a page
You can use the method trackAllContentImpressions()
to scan the entire DOM for content blocks. For each content block we will track a content impression immediately. If you only want to track visible content impression have a look at trackVisibleContentImpressions()
.
_paq.push(['trackPageView']);
_paq.push(['trackAllContentImpressions']);
We won't send an impression of the same content block twice if you call this method multiple times unless trackPageView()
is called meanwhile. This is useful for single page applications.
Track only visible content impressions within a page.
Enable to track only visible content impressions via trackVisibleContentImpressions(checkOnScroll, timeIntervalInMs)
. With visible we mean the content block has been in the view port and is not hidden (opacity, visibility, display, …).
-
Optionally you can tell us to not rescan the DOM after each scroll by passing
checkOnScroll=false
. Otherwise, we will check whether the previously hidden content blocks became visible meanwhile after a scroll and if so track the impression.
- Limitation: If a content block is placed within a scrollable element (
overflow: scroll
), we do currently not detect when such an element becomes visible.
- Limitation: If a content block is placed within a scrollable element (
-
Optionally you can tell us to rescan the entire DOM for new content impressions every X milliseconds by passing
timeIntervalInMs=500
. By default, we will rescan the DOM every 750ms. To disable it pass
timeIntervalInMs=0
.
- Rescanning the entire DOM and detecting the visible state of content blocks can take a while depending on the browser, hardware and amount of content. In case your frames per second goes down you might want to increase the interval or disable it completely. In case you disable it you can still rescan the DOM manually at any time by calling this method again or
trackContentImpressionsWithinNode()
.
- Rescanning the entire DOM and detecting the visible state of content blocks can take a while depending on the browser, hardware and amount of content. In case your frames per second goes down you might want to increase the interval or disable it completely. In case you disable it you can still rescan the DOM manually at any time by calling this method again or
Both checkOnScroll
and timeIntervalInMs
cannot be changed after this method was called the first time.
_paq.push(['trackPageView']);
_paq.push(['trackVisibleContentImpressions', true, 750]);
Track content impressions only for a part of the page
Use the method trackContentImpressionsWithinNode(domNode, contentTarget)
if you are adding elements to your DOM after we have tracked the initial impressions. Calling this method will make sure an impression will be tracked for all content blocks contained within this node.
Example
var div = $('<div>...<div data-track-content>...</div>...<div data-track-content>...</div></div>');
$('#id').append(div);
_paq.push(['trackContentImpressionsWithinNode', div[0]]);
We would detect two new content impressions in this example. In case you have enabled to track only visible content blocks we will respect this.
Track an interaction semi-automatic
Interactions with content blocks are usually tracked automatically as soon as a visitor is clicking on it. Sometimes you might want to trigger an interaction manually for instance in case you want to trigger an interaction based on a form submit or a double click. To do so call the method trackContentInteractionNode(domNode, contentInteraction)
.
Example
formElement.addEventListener('submit', function () {
_paq.push(['trackContentInteractionNode', this, 'submittedForm']);
});
- The passed
domNode
can be any node within a content block or the content block element itself. Nothing will be tracked in case there is no content block found. - Optionally you can set the name of the content interaction, for instance
click
orsubmit
. If none is provided, the valueUnknown
will be used. - You should disable the automatic interaction tracking of that content block by setting the CSS class
piwikContentIgnoreInteraction
or the attributedata-content-ignoreinteraction
. Otherwise an interaction might be tracked on top of it as soon as a visitor performs a click.
We call this kind of tracking semi-automatic as you triggered the interaction manually but the content name, piece and target is detected automatically. Detecting the content name and piece automatically makes sure we can map the interaction with a previously tracked impression.
Tracking content impressions and interactions manually
You should use the methods trackContentImpression(contentName, contentPiece, contentTarget)
and trackContentInteraction( contentInteraction, contentName, contentPiece, contentTarget)
only in conjunction together. It is not recommended to use trackContentInteraction()
after an impression was tracked automatically as we can map an interaction to an impression only if you do set the same content name and piece that was used to track the related impression.
Example
_paq.push(['trackContentImpression', 'Content Name', 'Content Piece', 'https://www.example.com']);
div.addEventListener('click', function () {
_paq.push(['trackContentInteraction', 'tabActivated', 'Content Name', 'Content Piece', 'https://www.example.com']);
});
Be aware that each call to those methods will send one request to your Matomo tracker instance. Doing this too many times can cause performance problems.
Measuring domains and/or sub-domains
Whether you are tracking one domain, or a subdomain, or both at the same time, etc. you may need to configure the Matomo JavaScript tracking code. There are two things that may need to be configured: 1) how tracking cookies are created and shared, and 2) which clicks should be tracked as 'Outlinks'.
Tracking one domain
This is the standard use case. Matomo tracks the visits of one domain name with no subdomain, in a single Matomo website.
// Default Tracking code
_paq.push(['setSiteId', 1]);
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['trackPageView']);
If you are tracking one specific subdomain, this default tracking code also works.
Tracking one domain and its subdomains in the same website
To record users across the main domain name and any of its subdomains, we tell Matomo to share the cookies across all subdomains. setCookieDomain()
is called in the Matomo tracking code in example.com/* and all subdomains.
_paq.push(['setSiteId', 1]);
_paq.push(['setTrackerUrl', u+'matomo.php']);
// Share the tracking cookie across example.com, www.example.com, subdomain.example.com, ...
_paq.push(['setCookieDomain', '*.example.com']);
// Tell Matomo the website domain so that clicks on these domains are not tracked as 'Outlinks'
_paq.push(['setDomains', '*.example.com']);
_paq.push(['trackPageView']);
Tracking your visitors across multiple domain names in the same website
To accurately track a visitor across different domain names into a single visit within one Matomo website, we need to set up what is called Cross Domain linking. Cross domain tracking in Matomo makes sure that when the visitor visits multiple websites and domain names, the visitor data will be stored in the same visit and that the visitor ID is reused across domain names. A typical use case where cross domain is needed is, for example, when an ecommerce online store is on www.awesome-shop.com
and the ecommerce shopping cart technology is on another domain such as secure.cart.com
.
Cross domain linking uses a combination of the two tracker methods setDomains
and enableCrossDomainLinking
. Learn how to set up cross-domain linking in our guide: How do I accurately measure a same visitor across multiple domain names (cross domain linking)?
Tracking subdirectories of a domain in separate websites
When tracking subdirectories of a domain in their own separate Matomo website, it is recommended to customise the tracking code to ensure optimal data accuracy and performance.
For example, if your website offers a 'User profile' functionality, you may wish to track each user profile pages in a separate website in Matomo. In the main domain homepage, you would use the default tracking code:
// idSite = X for the Homepage
// In Administration > Websites for idSite=X, the URL is set to `example.com/`
_paq.push(['setSiteId', X]);
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['trackPageView']);
In the example.com/user/MyUsername
page (and in every other user profile), you would construct calls to custom setSiteId
, setCookiePath
and setDomains
:
// The idSite Y will be different from other user pages
// In Administration > Websites for idSite=Y, the URL is set to `example.com/user/MyUsername`
_paq.push(['setSiteId', Y]);
// Create the tracking cookie specifically in `example.com/user/MyUsername`
_paq.push(['setCookiePath', '/user/MyUsername']);
// Tell Matomo the website domain so that clicks on other pages (eg. /user/AnotherUsername) will be tracked as 'Outlinks'
_paq.push(['setDomains', 'example.com/user/MyUsername']);
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['trackPageView']);
When tracking many subdirectories in separate websites, the function setCookiePath
prevents the number of cookies to quickly increase and prevent browser from deleting some of the cookies. This ensures optimal data accuracy and improves performance for your users (fewer cookies are sent with each request).
The functionsetDomains
ensures that clicks of users leaving your website (subdirectory example.com/user/MyUsername
) are correctly tracked as 'Outlinks'.
Tracking a group of pages in a separate website
(available since Matomo 2.16.1)
In some rare cases, you may want to track all pages matching a wildcard in a particular website, and track clicks on other pages (not matching the wildcard) as 'Outlinks'.
In the pages /index_fr.htm
or /index_en.htm
write:
// clicks on links not starting with example.com/index will be tracked as 'Outlinks'
_paq.push(['setDomains', 'example.com/index*']);
// when using a wildcard *, we do not need to configure cookies with `setCookieDomain`
// or `setCookiePath` as cookies are correctly created in the main domain by default
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['trackPageView']);
Notes:
- the wildcard
*
is supported only when specified at the end of the string. - since the wildcard can match several paths, calls to
setCookieDomain
orsetCookiePath
are omitted to ensure tracking cookie is correctly shared for all pages matching the wildcard.
For more information about tracking websites and subdomains in Matomo, see the FAQ: How to configure Matomo to monitor several websites, domains and sub-domains
Download and Outlink tracking
Enabling Download & Outlink tracking
The default Matomo JavaScript tracker code automatically enables the download & outlink tracking automatically, which is done by calling the enableLinkTracking
function:
// Enable Download & Outlink tracking
_paq.push(['enableLinkTracking']);
It is recommended to add this line just after the first call to trackPageView
or trackEvent
.
Outlinks are tracked automatically
By default all links to domains other than the current domain have click tracking enabled, and each click will be counted as an outlink. If you use multiple domains and subdomains, you may see clicks on your subdomains appearing in the Pages > Outlinks report.
Tracking outlinks and ignore alias domains
If you only want clicks to external websites to appear in your outlinks report, you can use the function setDomains()
to specify the list of alias domains or subdomains. Wildcard domains (*.example.org) are supported to let you easily ignore clicks to all subdomains.
// Don't track Outlinks on all clicks pointing to *.hostname1.com or *.hostname2.com
// Note: the currently tracked website is added to this array automatically
_paq(['setDomains', ["*.hostname1.com", "hostname2.com"]]);
_paq.push(['trackPageView']);
Since Matomo 2.15.1 you may also append a path to a domain and Matomo will correctly detect links to the same domain but different path as an outlink.
// Don't track Outlinks on all clicks pointing to *.hostname1.com/product1/* or *.hostname2.com/product1/*
// Track all clicks not pointing to *.hostname1.com/product1/* or *.hostname2.com/product1/* as outlink.
_paq(['setDomains', ["*.hostname1.com/product1", "hostname2.com/product1"]]);
Learn more about this use case Tracking subdirectories of a domain in separate websites.
Tracking a click as an outlink via CSS or JavaScript
If you want to force Matomo to consider a link as an outlink (links to the current domain or to one of the alias domains), you can add the 'piwik_link' css class to the link:
<a href='https://mysite.com/partner/' class='piwik_link'>Link I want to track as an outlink</a>
Note: you can customize and rename the CSS class used to force a click to be recorded as an outlink:
// now all clicks on links with the css class "external" will be counted as outlinks
// you can also pass an array of strings
_paq.push(['setLinkClasses', "external"]);
_paq.push(['trackPageView']);
Alternatively, you can use JavaScript to manually trigger a click on an outlink (it will work the same for page views or file downloads). In this example, custom outlink is trigged when the email address is clicked:
<a href="mailto:namexyz@mydomain.co.uk" target="_blank" onClick="_paq.push(['trackLink', 'https://mydomain.co.uk/mailto/Agent namexyz', 'link']);">namexyz@mydomain.co.uk </a>
Tracking file downloads
By default, any file ending with one of these extensions will be considered a 'download' in the Matomo interface:
7z|aac|arc|arj|apk|asf|asx|avi|bin|bz|bz2|csv|deb|dmg|doc|
exe|flv|gif|gz|gzip|hqx|jar|jpg|jpeg|js|mp2|mp3|mp4|mpg|
mpeg|mov|movie|msi|msp|odb|odf|odg|odp|ods|odt|ogg|ogv|
pdf|phps|png|ppt|qt|qtm|ra|ram|rar|rpm|sea|sit|tar|
tbz|tbz2|tgz|torrent|txt|wav|wma|wmv|wpd||xls|xml|z|zip
Customise the type of files tracked as downloaded
To replace the list of extensions you want to track as file downloads, you can use setDownloadExtensions( string )
:
// we now only track clicks on images
_paq.push(['setDownloadExtensions', "jpg|png|gif"]);
_paq.push(['trackPageView']);
If you want to track a new file type, you can just add it to the list by using addDownloadExtensions( filetype )
:
// clicks on URLs finishing by mp5 or mp6 will be counted as downloads
_paq.push(['addDownloadExtensions', "mp5|mp6"]);
_paq.push(['trackPageView']);
If you want to ignore a special file type, you can just remove it from the list by using removeDownloadExtensions( filetype )
:
// clicks on URLs ending in png or mp4 will not be counted as downloads
_paq.push(['removeDownloadExtensions', "png|mp4"]);
_paq.push(['trackPageView']);
Recording a click as a download
If you want to force Matomo to consider a link as a download, you can add the matomo_download
or piwik_download
css class to the link:
<a href='last.php' class='matomo_download'>Link I want to track as a download</a>
Note: you can customize and rename the CSS class used to force a click to be recorded as a download:
// now all clicks on links with the css class "download" will be counted as downloads
// you can also pass an array of strings
_paq.push(['setDownloadClasses', "download"]);
_paq.push(['trackPageView']);
Alternatively, you can use JavaScript to manually trigger a click on a download. In this example, custom download is trigged when the link is clicked:
<a href="https://secure.example.com/this-is-a-file-url" target="_blank" onClick="_paq.push(['trackLink', 'https://mydomain.co.uk/mailto/Agent namexyz', 'download']);">Download</a>
Changing the Pause Timer
When a user clicks to download a file, or clicks on an outbound link, Matomo records it. In order to do so, it adds a small delay before the user is redirected to the requested file or link. The default value is 500ms, but you can set it to a shorter length of time. It should be noted, however, that doing so results in the risk that this period of time is not long enough for the data to be recorded in Matomo.
_paq.push(['setLinkTrackingTimer', 250]); // 250 milliseconds
_paq.push(['trackPageView']);
Disabling Download & Outlink tracking
By default, the Matomo tracking code enables clicks and download tracking. To disable all automatic download and outlink tracking, you must remove the call to the enableLinkTracking()
function:
_paq.push(['trackPageView']);
// we comment out the function that enables link tracking
// _paq.push(['enableLinkTracking']);
Disabling for specific CSS classes
You can disable automatic download and outlink tracking for links with specific CSS classes:
// you can also pass an array of strings
_paq.push(['setIgnoreClasses', "no-tracking"]);
_paq.push(['trackPageView']);
This will result in clicks on a link <a href='https://example.com' class='no-tracking'>Test</a>
not being counted.
Disabling for a specific link
If you want to ignore download or outlink tracking on a specific link, you can add the matomo_ignore
or 'piwik_ignore' css class to it:
<a href='https://builds.matomo.org/latest.zip' class='matomo_ignore'>File I don't want to track as a download</a>
Asking for consent
View our integration guide for implementing tracking or cookie consent.
Optional: creating a custom opt-out form
If you'd like to provide your users with the ability to opt-out entirely from tracking, you can use an opt-out form. Matomo ships with an opt-out form implementation that uses third-party cookies (which you can configure within Matomo on the Matomo > Administration > Privacy page).
This form is simple to embed since it only requires that you add an iframe to your website, but it is not always ideal. Some users block third-party cookies so the opt-out form wouldn't work for them. You may also want to display custom text or graphics in the opt-out form, or you may want to allow users to opt-out of your sites individually instead of altogether.
In such a case, you may want to consider creating a custom opt-out form. The specifics of creating an HTML/JS form are out of scope for this document, but there are some things every custom opt-out form will have to do: check if the user is currently opted out, opt a user out and opt a user in. Here is how to do those things:
check if the user is currently opted out
Use the isUserOptedOut()
method like so:
_paq.push([function () {
if (this.isUserOptedOut()) {
// ... change form to say user is currently opted out ...
} else {
// ... change form to say user is currently opted in ...
}
}])
opt a user out
Use the optUserOut()
method:
_paq.push(['optUserOut']);
opt a user in
Use the forgetUserOptOut()
method:
_paq.push(['forgetUserOptOut']);
Below is an example opt-out form that replicates the built in Matomo opt-out form:
<div id="optout-form">
<p>You may choose not to have a unique web analytics cookie identification number assigned to your computer to avoid the aggregation and analysis of data collected on this website.</p>
<p>To make that choice, please click below to receive an opt-out cookie.</p>
<p>
<input type="checkbox" id="optout" />
<label for="optout"><strong></strong></label>
</p>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
function setOptOutText(element) {
_paq.push([function() {
element.checked = !this.isUserOptedOut();
document.querySelector('label[for=optout] strong').innerText = this.isUserOptedOut()
? 'You are currently opted out. Click here to opt in.'
: 'You are currently opted in. Click here to opt out.';
}]);
}
var optOut = document.getElementById("optout");
optOut.addEventListener("click", function() {
if (this.checked) {
_paq.push(['forgetUserOptOut']);
} else {
_paq.push(['optUserOut']);
}
setOptOutText(optOut);
});
setOptOutText(optOut);
});
</script>
Multiple Matomo trackers
By default, the Matomo JavaScript Tracking code collects your analytics data into one Matomo server. The Matomo service URL is specified in your JavaScript Tracking code (for example: var u="//matomo.example.org";
). In some cases, you may want to track your analytics data into more than just one Matomo server or into multiple websites on the same Matomo server.
If you haven't upgraded yet to Matomo 2.16.2 or later, please upgrade now! (Instructions for 2.16.1 or older versions are found below.)
Duplicate your data into different websites in one Matomo server
You may need to collect a duplicate of your web analytics data into the same Matomo server, but in another website.
Recommended solution: use RollUp Reporting plugin
When you need to duplicate data into another website, or consolidate several websites into one or more groups (called RollUps) the recommended solution is to use the RollUp Reporting premium plugin. Using this plugin has several advantages over the other solution as you can easily group one or more websites together, and the RollUps do not cause the tracking data to be duplicated which improves overall performance.
Alternative solution: duplicate the tracking data
Alternatively to using the RollUp Reporting plugin you can duplicate the tracking data. To duplicate the data you can call addTracker
with a Matomo URL and your website ID where to duplicate the data:
var u="//matomo.example.org/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
// We will also collect the website data into Website ID = 7
var websiteIdDuplicate = 7;
// The data will be duplicated into `piwik.example.org/matomo.php`
_paq.push(['addTracker', u+'matomo.php', websiteIdDuplicate]);
// Your data is now tracked in both website ID 1 and website 7 into your piwik.example.org server!
As this solution causes every visitor's event, pageview, etc. to be tracked twice in your Matomo server, we generally do not recommend it.
Collect your analytics data into two or more Matomo servers
The example below shows how to use addTracker
method to track the same analytics data into a second Matomo server. The main Matomo server is piwik.example.org/matomo.php
where the data is stored into website ID 1
. The second Matomo server is analytics.example.com/matomo.php
where the data is stored into website ID 77
. When you implement this in your website, please replace these two Matomo URLs and Matomo website IDs with your own Matomo URLs and website IDs.
<script type="text/javascript">
var _paq = window._paq = window._paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//matomo.example.org/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
// Add this code below within the Matomo JavaScript tracker code
// Important: the tracker url includes the /matomo.php
var secondaryTrackerUrl = 'https://analytics.example.com/matomo.php';
var secondaryWebsiteId = 77;
// Also send all of the tracking data to this other Matomo server, in website ID 77
_paq.push(['addTracker', secondaryTrackerUrl, secondaryWebsiteId]);
// That's it!
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
Customise one of the tracker object instances
Note: by default any tracker added via addTracker
is configured the same as the main default tracker object (regarding cookies, custom dimensions, user id, download & link tracking, domains and sub-domains, etc.). If you want to configure one of the Matomo tracker object instances that was added via addTracker
, you may call the Matomo.getAsyncTracker(optionalMatomoUrl, optionalPiwikSiteId)
method. This method returns the tracker instance object which you can configure differently than the main JavaScript tracker object instance.
Duplicate the tracking data when calling the JavaScript API directly (not via _paq.push
)
It is possible to track your analytics data into either a different website ID on the same server or you may record a copy of your data into another Matomo server altogether. Each call to Piwik.getTracker()
returns a unique Matomo Tracker object (instance) which can be configured.
<script type="text/javascript">
window.matomoAsyncInit = function () {
try {
var matomoTracker = Matomo.getTracker("https://URL_1/matomo.php", 1);
matomoTracker.trackPageView();
var piwik2 = Matomo.getTracker("https://URL_2/matomo.php", 4);
piwik2.trackPageView();
} catch( err ) {}
};
</script>
The matomoAsyncInit()
method will be executed once the Matomo tracker is loaded and initialized. In earlier versions you must load Matomo synchronous.
JavaScript Tracker Reference
View all features of the Tracking client in the JavaScript Tracker Reference.
Frequently Asked Questions
If you have any question about JavaScript Tracking in Matomo, please search the website, or ask in the forums.
- How do I enable tracking for users without JavaScript?
- How does Matomo track downloads?
- How to track single-page websites and web applications
- How to track error pages and get the list of 404 and referrers urls.
- How can I set custom groups of pages (structure) so that page view are aggregated by categories?
- How do I set up Matomo to track multiple websites without revealing the Matomo server URL footprint in JS?
- How do I customise the matomo.js being loaded on all my websites?
- How do I disable all tracking cookies used by Matomo in the javascript code?
https://matomo.org/log-analytics/
Stay compliant with strict data privacy and security policies with Log Analytics
Don’t want to insert a JavaScript tracking code to your website for privacy reasons? Log Analytics is the most secure way to get the insights you need to make smarter data-driven decisions, without compromising the integrity of your organisation.
Peace of mind for even the most data sensitive industries:
Do you work in an industry that’s highly sensitive about user data? We understand how crucial it is that sensitive information is protected, that’s why specific industries choose the Log Analytics feature. An alternative solution to the standard method of embedding the JavaScript tracking code on your website.
This gives you and your users a higher level of security with the ability to generate reports by importing web server logs.
NOTE: This doesn’t include e-commerce sites that use a payment gateway for transactions as that is protected by the payment provider.
- Government agencies: Serving the public means protecting the public’s identity that’s provided when they sign in to personal portals for government payments, documents etc.
- Financial institutions: When customers use online banking services or communication portals that hold delicate information, it’s even more important to be vigilant. Don’t risk data falling into the wrong hands.
- Healthcare: Patient confidentiality could be compromised if you aren’t fully protecting their records through an online service.
- Education institutions: How students and faculty members communicate through online portals, like Moodle, or how they access their grades and online resources should be protected by a highly secure tracking method.
No waiting around – actionable insights the second you setup Log Analytics
Unlike the JavaScript tracking method which begins gathering valuable insights from the moment you insert the tracking code on your website, Log Analytics gives you back data through all your historical visitor sessions.
This way you get a head start in learning about who your visitors and customers are to grow your business faster.
NOTE: While there are many benefits to using Log Analytics, some features are unavailable using this tracking method, including:
- Screen resolution and page titles
- Events
- Content tracking
- Heatmaps and Session recordings
- Form analytics
Features of Matomo Log Analytics
- 100% data ownership
- Protect user privacy with IP anonymisation
- Recognises most server log formats (Apache, Nginx, IIS, etc.)
- Easily migrate from AWStats and Urchin by importing your historical logs into Matomo
- Track people who use ad blocker
- Sarbanes-Oxley and PCI compliant
- Automatically exclude bots (search engines, spam bots, etc.) from reports. There is an option to track bots and assign them a custom variable to differentiate them from human visitors
How it works:
All web servers generate access log files which contain all of the requests made to the server i.e information from each user on your website. This means valuable data from your website visitors becomes available without the need for a JavaScript tracking code, this includes – location, device, browser, referrer site etc.
>> Learn how to run Log Analytics
HOW TO RUN LOG ANALYTICS
HOW TO USE LOG ANALYTICS TOOL
Table of contentsRequirementsDifferences using Log Analytics VS using Javascript clientHow to: run the Log File analysis script with default optionsHow to: import more data including bots, static files, and HTTP errors trackingHow to: exclude some particular log linesUsing Log AnalyticsFrequently Asked Questions
This page explains the requirements and how to run the Matomo (Piwik) Log Analytics tool to import your server logs in Matomo.
Requirements
- Install Matomo (or update). This should take around 5 minutes.
- To execute the script you need access to a server via SSH or some way of executing scripts on your server
- Python 3.5 or newer required (Matomo 3 supports Python 2.6 and 2.7). Note: the script that loads and parses the log files is written in Python, but Matomo itself behind the API is written in PHP.
- You will also need one or more log files to parse and analyze with Matomo (inside each log file the log lines must be ordered by date)
- Note: we recommend that you use the extended log format which includes user agent, referrer URL, an full URLs (including hostnames) in the logs. If these fields are missing from the logs, analytics data in Matomo will be less accurate.
- Setup Geo Location for accurate country and city detection. Matomo guesses visitors’ countries based on the visitor’s browser language, but this information is not available in the access logs, so Geo Location is a must have.
Differences using Log Analytics VS using Javascript client
When using the server logs import (compared to JavaScript Tracking) there are be a few user data points missing: screen resolutions, browser plugins, and page titles are not available (report Behavior > Page Titles will be mostly empty). Tracking cookies cannot be used resulting in a
few missing data points. See also this faq.
How to: run the Log File analysis script with default options
Once you have Matomo running, you will find the script in misc/log-analytics/import_logs.py
$ python /path/to/piwik/misc/log-analytics/import_logs.py
This will display the help information. The only required parameter is
--url=https://analytics.example.com
to specify the Matomo base URL. Then, you can specify one or many log files to import.
If you run the script on a server other than your Matomo server, then you will also need to specify the --token-auth=SECRET_TOKEN_HERE
parameter (learn more in our FAQ: where do I find token_auth?).
There are many more options available. See the help output, and the README for more information and explanations about available parameters.
For example, if you wish to track all requests (static files, bot requests, http errors, http redirects) the following command would be used:
python /path/to/piwik/misc/log-analytics/import_logs.py --url=https://analytics.example.com
--idsite=1234 --recorders=4 --enable-http-errors --enable-http-redirects --enable-static
--enable-bots access.log
How to: import more data including bots, static files, and HTTP errors tracking
By default, the script does not track static files (JS, CSS, images, etc.) and excludes all bot traffic.
You can enable these using the following commands:
--enable-bots
will track search/spam bots in Matomo, using a custom variable with the name of the bot. When enabled, the log file will take longer to process since all bot page views are sent to Matomo. Matomo detects whether a log line is a from a bot by looking at the User-agent field.
Example of Custom Variables reporting Bots user agents:
--enable-static
will specify tracking of all static files (images, JS, CSS) in Matomo. This will add some time to the general log file processing.
--enable-http-errors
will specify tracking of HTTP errors (4xx, 5xx status) as a page view in Matomo, with a custom variable HTTP-code set to 404, 500, etc. The page title for this page view will show the URL referrer if it is specified in the log file (which can help finding out which pages have a link to a 404 for example).
--enable-http-redirects
will track HTTP redirect (302,301,3xx) as a page view, with a custom title, and a custom variable. Note: HTTP status 304 responses (“Not modified”) are tracked as page views.
--enable-reverse-dns
will enable the reverse DNS (used to generate the Visitors > Providers report), expect a big performance hit as reverse DNS is very slow.
--recorders=N
specifies the number of threads: we recommend setting it to the number of CPU cores in the system (or slightly more or less depending on your server configuration)
--recorder-max-payload-size=N
The importer uses the bulk tracking feature of Matomo to achieve greater speed. By default, 300 pageviews (or log lines) will be sent to Matomo at once. You can experiment with this number to try and achieve better performance, but there is an upper limit to the speed you can get.
How to: exclude some particular log lines
There are several ways to exclude particular log lines or visitors from being tracked.
-
you can exclude specific IP addresses or IP ranges from being tracked. To configure excluded IPs, log into Matomo as Super User, then click Administration > Websites.
-
the script provides an option to exclude visits with specific User Agent HTTP headers — via
--useragent-exclude
-
the script provides an option to enforce a whitelist of all URL hostnames that should be considered — all other log lines with a hostname not in the list will not be imported. See the option
--hostname
-
it is also possible to exclude specific log lines where the URL path matches a particular URL path. See the option
--exclude-path
For example to exclude all files from the URL example.org/assets/ you would write --exclude-path="/assets*"
To exclude two paths you would write: --exclude-path="path2/here*" --exclude-path="/sub/path2*"
Using Log Analytics
Learn more about how to use the script, how to import logs automatically every day, and advanced setups in our Log Analytics Readme.
Frequently Asked Questions
For more information and guides, check out our Log Analytics tool FAQs
If you have feature requests for better Server Log processing with Matomo, please let us know using the feedback form below. We look forward to your feedback and hope Matomo will deliver huge value for all server logs.
Tracking HTTP API
https://developer.matomo.org/api-reference/tracking-api
Tracking HTTP API
To track page views, events, visits, you have to send a HTTP request (GET or POST) to your Tracking HTTP API endpoint, for example, https://your-matomo-domain.example/matomo.php with the correct query parameters set.
Supported Query Parameters
This section lists the various query parameters that are supported by the Tracking API. The data for some of these fields will not be available in your app / software which is expected, but you should provide as much information as you can.
Note: all parameters values that are strings (such as 'url', 'action_name', etc.) must be URL encoded.
Required parameters
idsite
(required) — The ID of the website we're tracking a visit/action for.rec
(required) — Required for tracking, must be set to one, eg,&rec=1
.
Recommended parameters
action_name
(recommended) — The title of the action being tracked. It is possible to use slashes / to set one or several categories for this action. For example, Help / Feedback will create the Action Feedback in the category Help.url
(recommended) — The full URL for the current action._id
(recommended) — The unique visitor ID, must be a 16 characters hexadecimal string. Every unique visitor must be assigned a different ID and this ID must not change after it is assigned. If this value is not set Matomo (formerly Piwik) will still track visits, but the unique visitors metric might be less accurate.rand
(recommended) — Meant to hold a random value that is generated before each request. Using it helps avoid the tracking request being cached by the browser or a proxy.apiv
(recommended) — The parameter &apiv=1 defines the api version to use (currently always set to 1)
Optional User info
(We recommend that these parameters be used if the information is available and relevant to your use case.)
urlref
— The full HTTP Referrer URL. This value is used to determine how someone got to your website (ie, through a website, search engine or campaign)._cvar
— Visit scope custom variables. This is a JSON encoded string of the custom variable array (see below for an example value)._idvc
— The current count of visits for this visitor. To set this value correctly, it would be required to store the value for each visitor in your application (using sessions or persisting in a database). Then you would manually increment the counts by one on each new visit or "session", depending on how you choose to define a visit. This value is used to populate the report Visitors > Engagement > Visits by visit number._viewts
— The UNIX timestamp of this visitor's previous visit. This parameter is used to populate the report Visitors > Engagement > Visits by days since last visit._idts
— The UNIX timestamp of this visitor's first visit. This could be set to the date where the user first started using your software/app, or when he/she created an account. This parameter is used to populate the Goals > Days to Conversion report._rcn
— The Campaign name (see Tracking Campaigns). Used to populate the Referrers > Campaigns report. Note: this parameter will only be used for the first pageview of a visit._rck
— The Campaign Keyword (see Tracking Campaigns). Used to populate the Referrers > Campaigns report (clicking on a campaign loads all keywords for this campaign). Note: this parameter will only be used for the first pageview of a visit.res
— The resolution of the device the visitor is using, eg 1280×1024.h
— The current hour (local time).m
— The current minute (local time).s
— The current second (local time).- plugins used by the visitor can be specified by setting the following parameters to 1:
fla
(Flash),java
(Java),dir
(Director),qt
(Quicktime),realp
(Real Player),pdf
(PDF),wma
(Windows Media),gears
(Gears),ag
(Silverlight). cookie
— when set to 1, the visitor's client is known to support cookies.ua
— An override value for the User-Agent HTTP header field. The user agent is used to detect the operating system and browser used.lang
— An override value for the Accept-Language HTTP header field. This value is used to detect the visitor's country if GeoIP is not enabled.uid
— defines the User ID for this request. User ID is any non-empty unique string identifying the user (such as an email address or an username). To access this value, users must be logged-in in your system so you can fetch this user ID from your system, and pass it to Matomo. The User ID appears in the visits log, the Visitor profile, and you can Segment reports for one or several User ID (userId
segment). When specified, the User ID will be "enforced". This means that if there is no recent visit with this User ID, a new one will be created. If a visit is found in the last 30 minutes with your specified User ID, then the new action will be recorded to this existing visit.cid
— defines the visitor ID for this request. You must set this value to exactly a 16 character hexadecimal string (containing only characters 01234567890abcdefABCDEF). We recommended setting the User ID viauid
rather than use thiscid
.new_visit
— If set to 1, will force a new visit to be created for this action. This feature is also available in JavaScript.dimension[0-999]
— A Custom Dimension value for a specific Custom Dimension ID (requires Matomo 2.15.1 + Custom Dimensions plugin see the Custom Dimensions guide). If Custom Dimension ID is2
usedimension2=dimensionValue
to send a value for this dimension. The configured Custom Dimension has to be in scope "Visit".
Optional Action info (measure Page view, Outlink, Download, Site search)
cvar
— Page scope custom variables. This is a JSON encoded string of the custom variable array (see below for an example value).link
— An external URL the user has opened. Used for tracking outlink clicks. We recommend to also set the url parameter to this same value.download
— URL of a file the user has downloaded. Used for tracking downloads. We recommend to also set the url parameter to this same value.search
— The Site Search keyword. When specified, the request will not be tracked as a normal pageview but will instead be tracked as a Site Search request.search_cat
— when search is specified, you can optionally specify a search category with this parameter.search_count
— when search is specified, we also recommend setting the search_count to the number of search results displayed on the results page. When keywords are tracked with &search_count=0 they will appear in the "No Result Search Keyword" report.pv_id
— Accepts a six character unique ID that identifies which actions were performed on a specific page view. When a page was viewed, all following tracking requests (such as events) during that page view should use the same pageview ID. Once another page was viewed a new unique ID should be generated. Use[0-9a-Z]
as possible characters for the unique ID.idgoal
— If specified, the tracking request will trigger a conversion for the goal of the website being tracked with this ID.revenue
— A monetary value that was generated as revenue by this goal conversion. Only used if idgoal is specified in the request.gt_ms
— The amount of time it took the server to generate this action, in milliseconds. This value is used to process the Page speed report Avg. generation time column in the Page URL and Page Title reports, as well as a site wide running average of the speed of your server. Note: when using the JavaScript tracker this value is set to the time for server to generate response + the time for client to download response.cs
— The charset of the page being tracked. Specify the charset if the data you send to Matomo is encoded in a different character set than the defaultutf-8
.dimension[0-999]
— A Custom Dimension value for a specific Custom Dimension ID (requires Matomo 2.15.1 + Custom Dimensions plugin see the Custom Dimensions guide). If Custom Dimension ID is2
usedimension2=dimensionValue
to send a value for this dimension. The configured Custom Dimension has to be in scope "Action".ca
— Stands for custom action.&ca=1
can be optionally sent along any tracking request that isn't a page view. For example it can be sent together with an event tracking requeste_a=Action&e_c=Category&ca=1
. The advantage being that should you ever disable the event plugin, then the event tracking requests will be ignored vs if the parameter is not set, a page view would be tracked even though it isn't a page view. For more background information check out #16570. Do not use this parameter together with aping=1
tracking request.
Optional Page Performance info
For pageviews the following page performance metrics can be tracked:
pf_net
— Network time. How long it took to connect to server.pf_srv
— Server time. How long it took the server to generate page.pf_tfr
— Transfer time. How long it takes the browser to download the response from the serverpf_dm1
— Dom processing time. How long the browser spends loading the webpage after the response was fully received until the user can starting interacting with it.pf_dm2
— Dom completion time. How long it takes for the browser to load media and execute any Javascript code listening for the DOMContentLoaded event.pf_onl
— Onload time. How long it takes the browser to execute Javascript code waiting for the window.load event.
All page performance metrics expect a value in milliseconds.
Optional Event Tracking info
e_c
— The event category. Must not be empty. (eg. Videos, Music, Games…)e_a
— The event action. Must not be empty. (eg. Play, Pause, Duration, Add Playlist, Downloaded, Clicked…)e_n
— The event name. (eg. a Movie name, or Song name, or File name…)e_v
— The event value. Must be a float or integer value (numeric), not a string.
Note: Trailing and leading whitespaces will be trimmed from parameter values for e_c
, e_a
and e_n
. Strings filled with whitespaces will be considered as (invalid) empty values.
Optional Content Tracking info
c_n
— The name of the content. For instance 'Ad Foo Bar'c_p
— The actual content piece. For instance the path to an image, video, audio, any textc_t
— The target of the content. For instance the URL of a landing pagec_i
— The name of the interaction with the content. For instance a 'click'
To track a content impression set c_n
and optionally c_p
and c_t
. To track a content interaction set c_i
and c_n
and optionally c_p
and c_t
. To map an interaction to an impression make sure to set the same value for c_n
and c_p
. It is recommended to set a value for c_p
.
Optional Ecommerce info
Use the following values to record a cart and/or an ecommerce order.
-
you must set
&idgoal=0
in the request to track an ecommerce interaction: cart update or an ecommerce order. -
ec_id
— The unique string identifier for the ecommerce order (required when tracking an ecommerce order) -
ec_items
— Items in the Ecommerce order. This is a JSON encoded array of items. Each item is an array with the following info in this order:- item sku (required),
- item name (or if not applicable, set it to an empty string),
- item category (or if not applicable, set it to an empty string),
- item price (or if not applicable, set it to 0),
- item quantity (or if not applicable, set it to 1).
An example value of
ec_items
would be:%5B%5B%22item1%20SKU%22%2C%22item1%20name%22%2C%22item1%20category%22%2C11.1111%2C2%5D%2C%5B%22item2%20SKU%22%2C%22item2%20name%22%2C%22%22%2C0%2C1%5D%5D
(URL decoded version is:[["item1 SKU","item1 name","item1 category",11.1111,2],["item2 SKU","item2 name","",0,1]]
). -
revenue
— The grand total for the ecommerce order (required when tracking an ecommerce order) -
ec_st
— The sub total of the order; excludes shipping. -
ec_tx
— Tax Amount of the order -
ec_sh
— Shipping cost of the Order -
ec_dt
— Discount offered -
_ects
— The UNIX timestamp of this customer's last ecommerce order. This value is used to process the "Days since last order" report.
Other parameters (require authentication via token_auth
)
The following parameters require that you set &token_auth=
to the token_auth value of the Super User, or a user with write or admin permission to the website visits are being tracked for.
token_auth
— 32 character authorization key used to authenticate the API request. We recommend to create a user specifically for accessing the Tracking API, and give the user only write permission on the website(s).cip
— Override value for the visitor IP (both IPv4 and IPv6 notations supported).cdt
— Override for the datetime of the request (normally the current time is used). This can be used to record visits and page views in the past. The expected format is either a datetime such as:2011-04-05 00:11:42
(remember to URL encode the value!), or a valid UNIX timestamp such as1301919102
. The datetime must be sent in UTC timezone. Note: if you record data in the past, you will need to force Matomo to re-process reports for the past dates. If you setcdt
to a datetime older than 24 hours thentoken_auth
must be set. If you setcdt
with a datetime in the last 24 hours then you don't need to passtoken_auth
.country
— An override value for the country. Should be set to the two letter country code of the visitor (lowercase), eg fr, de, us.region
— An override value for the region. Should be set to a ISO 3166-2 region code, which are used by MaxMind's and DB-IP's GeoIP2 databases. See here for a list of them for every country.city
— An override value for the city. The name of the city the visitor is located in, eg, Tokyo.lat
— An override value for the visitor's latitude, eg 22.456.long
— An override value for the visitor's longitude, eg 22.456.
Media Analytics parameters
Analytics for your Media content (video players and audio players) can be recorded using the premium Media Analytics plugin's HTTP Tracking API parameters.
Activity and consumption of your videos and audios can be measured via the parameters ma_id
, ma_ti
, ma_re
, ma_mt
, ma_pn
, ma_st
, ma_le
, ma_ps
, ma_ttp
, ma_w
, ma_h
, ma_fs
, ma_se
.
Learn more in the Media Analytics HTTP Tracking API Reference.
Queued Tracking parameters
Queued Tracking can scale your large traffic Matomo (Piwik) service by queuing tracking requests in Redis or Mysql for better performance and reliability when you experience peaks.
queuedtracking
— When set to0
(zero), the queued tracking handler won't be used and instead the tracking request will be executed directly. This can be useful when you need to debug a tracking problem or want to test that the tracking works in general.
Other parameters
send_image
— If set to 0 (send_image=0
) Matomo will respond with a HTTP 204 response code instead of a GIF image. This improves performance and can fix errors if images are not allowed to be obtained directly (eg Chrome Apps). Available since Matomo 2.10.0ping
— If set to 1 (ping=1
), the request will be a Heartbeat request which will not track any new activity (such as a new visit, new action or new goal). The heartbeat request will only update the visit's total time to provide accurate "Visit duration" metric.
Tracking Bots
By default Matomo does not track bots. If you use the Tracking HTTP API directly, you may be interested in tracking bot requests. To enable Bot Tracking in Matomo, set the parameter &bots=1
in your requests to matomo.php
.
Example Tracking Request
Here is an example of a real tracking request used by the Matomo Mobile app when anonymously tracking Mobile App usage:
https://matomo-server/matomo.php?_cvar={"1":["OS","iphone 5.0"],"2":["Matomo Mobile Version","1.6.2"],"3":["Locale","en::en"],"4":["Num Accounts","2"]}&action_name=View settings&url=http://mobileapp.matomo.org/window/settings &idsite=8876&rand=351459&h=18&m=13&s=3 &rec=1&apiv=1&cookie=1&urlref=https://iphone.mobileapp.piwik.org&_id=af344a398df83874 &_idvc=19&res=320×480&
Note: for clarity, parameter values are not URL encoded in this example.
Explanation: this URL has custom variables for the OS, Matomo version, number of accounts created. It tracks an event named View settings with a fake URL, records the screen resolution and also includes a custom unique ID generated to ensure all requests for the same Mobile App user will be recorded for the same visit in Matomo.
Bulk Tracking
Some applications such as the Matomo log importer, have to track many visits, sometimes tens, hundreds, thousands or even more all at once. Tracking these requests with one HTTP request per visit or action can result in enormous delays due to the amount of time it takes to send an HTTP request, Using the bulk tracking feature, however, these requests can be sent all at once making the application far more efficient.
To send a bulk tracking request, an HTTP POST must be made with a JSON object to the Matomo tracking endpoint. The object must contain the following properties:
-
requests
— an array of individual tracking requests. Each tracking request should be the query string you'd send if you were going to track that action individually.
- Note that for Matomo to store your tracking data accurately, your tracking requests should be sent in chronological order (the oldest requests should appear first).
-
token_auth
— (optional) token_auth which is found in the API page. Specify this only needed if you use any of the parameters that requiretoken_auth
Example Bulk Requests
This is an example of the payload of a bulk tracking request:
{
"requests": [
"?idsite=1&url=https://example.org&action_name=Test bulk log Pageview&rec=1",
"?idsite=1&url=https://example.net/test.htm&action_name=Another bulk page view&rec=1"
],
"token_auth": "33dc3f2536d3025974cccb4b4d2d98f4"
}
Here is the command to send this request to Matomo using curl (without token_auth
which is optional in this case):
curl -i -X POST -d '{"requests":["?idsite=1&url=https://example.org&action_name=Test bulk log Pageview&rec=1","?idsite=1&url=http://example.net/test.htm&action_name=Another bulk page view&rec=1"]}' https://matomo.example.com/matomo.php
This will track two actions using only one HTTP request to Matomo.
Debugging the Tracker
To verify that your data is being tracked properly, you can enable debug logging in the Matomo tracking file, matomo.php.
Tracking requests will then output the tracking log messages rather than displaying a 1*1 transparent GIF beacon. For security reasons, this should not be done in production or only for a very short time frame.
Follow these steps to enable and view debug logging for the tracker:
-
In your config file
path/to/matomo/config/config.ini.php
, write the following:[Tracker] debug = 1
Since Matomo 3.10 to enable the profiling of SQL queries you additionally need to enable:
[Tracker]
enable_sql_profiler = 1
-
Look at the HTTP requests that are sent to Matomo.
- If the requests take place in a browser, you can use a tool like the Firebug to see all requests to matomo.php.
- If the requests are triggered from your app or software directly, you can output or log the output of tracking requests and to view the debug messages.
- You can also log messages to file or database (requires at least Matomo 2.15.0).
If you receive too many tracking requests and the log gets spammed by these requests or if you want to only debug some specific requests you can alternatively enable debug_on_demand
in config.ini.php
:
[Tracker]
debug_on_demand = 1
In this case messages will be only logged for Tracker requests that have a URL parameter &debug=1
set. This is considered more secure but should be still only enabled for a short time frame.
Learn more
- For a list of tracking clients see this page.
- To learn more about geolocation read the GeoIP user docs.
- To learn about Matomo's JavaScript tracker read our documentation for the tracker.