Yes, Matomo (Piwik) 2.15.0 and newer can be used with CSP. However, you cannot use the standard tracking code generated by the Tracking Code Generator in the Matomo UI as it is not allowed to use inline scripts when having CSP enabled. CSP is a security concept to prevent cross-site scripting (XSS) attacks as well as related attacks.

Setting up the JavaScript Tracker

Instead make sure to put the tracking code into files like this:

<script src="http://example.com/piwik/piwik.js" async defer></script>
<script src="http://example.com/tracking.js"></script>

The file piwik.js should be loaded from your Matomo (Piwik) server and tracking.js should contain the actual tracking calls like this:

var idSite = 1;
var piwikTrackingApiUrl = 'http://example.com/piwik/piwik.php';

var _paq = _paq || [];  
_paq.push(['setTrackerUrl', piwikTrackingApiUrl]);
_paq.push(['setSiteId', idSite]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);  

Make sure to specify the correct idSite if needed and to replace the Matomo (Piwik) Tracking API URL. You can build this URL by appending /piwik.php to your Matomo domain.

Configuring Content-Security-Policy

If you load piwik.js from a different domain make sure to allow the Matomo (Piwik) domain like this: script-src 'self' http://example.com. If you load third party JavaScript files or if you have a CDN you might have to add even more domains to the whitelist.

An example response header looks like this:

Header set Content-Security-Policy "default-src 'self'; script-src 'self' http://example.com; style-src 'self'; frame-ancestors 'self'; frame-src 'self';"

If CSP should work in all browsers you might have to add further headers. At the time of writing this article you might as well need to set X-WebKit-CSP for Safari and X-Content-Security-Policy for Internet Explorer support. Read more about Content Security Policy.

Any questions?

Many answers and more information about Matomo you can find here:

We are social

Follow us: