npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@adam20054/react-matomo

v1.1.5

Published

Advanced React integration for Matomo analytics.

Readme

What is Matomo React?

Matomo React is a comprehensive TypeScript library that seamlessly integrates Matomo analytics into your React applications. It provides a simple, yet powerful API for tracking user interactions, page views, events, and more, while maintaining full type safety.

Table of Contents

Quick Start

Get started quickly with Matomo React by following this simple example:

import { MatomoProvider, useMatomo } from "@adam20054/react-matomo";

// Basic configuration
const config = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1
};

// App component with provider
function App() {
  return (
    <MatomoProvider config={config}>
      <YourApp />
    </MatomoProvider>
  );
}

// Component using tracking
function HomePage() {
  const { tracker } = useMatomo();

  // Track page view when component mounts
  React.useEffect(() => {
    tracker.trackPageView();
  }, [tracker]);

  return <h1>Welcome to my site</h1>;
}

Installation

Install the module from NPM registry:

npm:

npm i --save @adam20054/react-matomo

yarn:

yarn add @adam20054/react-matomo

Basic Usage

  1. Set up the provider in your app's root component:
import { MatomoProvider } from "@adam20054/react-matomo";

const config = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1
};

function App() {
  return (
    <MatomoProvider config={config}>
      <YourApp />
    </MatomoProvider>
  );
}
  1. Use the tracker in your components:
import { useMatomo } from "@adam20054/react-matomo";

function YourComponent() {
  const { tracker } = useMatomo();

  // Track page view
  React.useEffect(() => {
    tracker.trackPageView();
  }, [tracker]);

  // Track an event
  const handleButtonClick = () => {
    tracker.trackEvent({
      category: "User Interaction",
      action: "Button Click",
      name: "Get Started"
    });
  };

  return (
    <div>
      <h1>Your Component</h1>
      <button onClick={handleButtonClick}>Get Started</button>
    </div>
  );
}
  1. Use the optimized event tracking hook for better performance:
import { useMatomoEvent } from "@adam20054/react-matomo";

function YourComponent() {
  const { trackPageView, trackEvent } = useMatomoEvent();

  // Track page view
  React.useEffect(() => {
    trackPageView();
  }, [trackPageView]);

  // Track an event (memoized function)
  const handleButtonClick = () => {
    trackEvent({
      category: "User Interaction",
      action: "Button Click",
      name: "Get Started"
    });
  };

  return (
    <div>
      <h1>Your Component</h1>
      <button onClick={handleButtonClick}>Get Started</button>
    </div>
  );
}

Configuration Options

For a comprehensive guide on Matomo JavaScript tracking, see the Matomo JavaScript Tracking Guide.

| Option | Type | Required? | Description | Default | | --- | --- | --- | --- | --- | | siteId | String/Number | ✅ | The site identifier from your Matomo dashboard | - | | trackerBaseUrl | String | ✅ | Base URL of your Matomo installation. Can be: 1) Domain only (e.g., "https://analytics.example.com"), or 2) Path without file extension (e.g., "https://example.com/api/"). Matomo will assume you're using matamo.js/php as the filename unless matomo(Js/Php)FileName is specified in your config | - | | userId | String | - | User identifier for cross-device tracking | - | | disableTracking | Boolean | - | When true, disables all tracking | false | | deferTracking | Boolean | - | Defers tracking until after critical content loads | false | | debug | Boolean | - | Enables debug mode with console logging | false | | enableJSErrorTracking | Boolean | - | Tracks JavaScript errors as events | false | | urlTransformer | Function | - | Transforms URLs before tracking | - | | heartBeat | Object | - | Configuration for heartbeat feature | { active: true, seconds: 15 } | | disableLinkTracking | Boolean | - | Disables automatic link tracking | false | | matomoJsFileName | String | - | Custom filename for Matomo JS (required if you need to use a custom filename) | "matomo.js" | | matomoPhpFileName | String | - | Custom filename for Matomo PHP (required if you need to use a custom filename) | "matomo.php" | | requestMethod | RequestMethod | - | HTTP method for tracking requests | RequestMethod.GET | | configurations | Object | - | Additional Matomo configurations. For options not specifically built into the config options but still supported by Matomo. See Matomo JavaScript Tracking Guide for available options. | - |

TrackerBaseUrl Examples

The trackerBaseUrl option can be used in two different ways:

// 1. Domain only - standard matomo.js/php files at the root
const config1 = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1
};

// 2. Path without file extension - standard matomo.js/php files at that path
const config2 = {
  trackerBaseUrl: "https://example.com/api/",
  siteId: 1
};

Custom Filenames

If you need to use custom filenames instead of the default "matomo.js" and "matomo.php", you must specify them explicitly:

const config = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1,
  matomoJsFileName: "custom.js",
  matomoPhpFileName: "custom.php"
};

URL Transformer

The urlTransformer option allows you to modify URLs before they are sent to Matomo:

const urlTransformer = (url: string) => {
  // Remove UUIDs from the URL
  const UUIDV4_REGEX = /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/g;
  return url.replaceAll(UUIDV4_REGEX, "**MASKED**");
};

const config = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1,
  urlTransformer
};

Tracking Methods

This section covers the core tracking functionality provided by the library. These methods allow you to track various user interactions and behaviors in your React application. Click on each example to see the code.

Tracking Page Views

// Basic page view tracking
tracker.trackPageView();

// With custom parameters
tracker.trackPageView({
  documentTitle: "Custom Page Title",
  href: "https://example.com/custom-path",
  customDimensions: [
    { id: 1, value: "Premium" }
  ]
});

Tracking Events

tracker.trackEvent({
  category: "User Interaction",
  action: "Button Click",
  name: "Sign Up Button",
  value: 1
});

Tracking Site Searches

tracker.trackSiteSearch({
  keyword: "react analytics",
  category: "Documentation",
  count: 5
});

Custom Dimensions

Custom dimensions can be included with any tracking call:

tracker.trackPageView({
  customDimensions: [
    { id: 1, value: "Premium" },
    { id: 2, value: "Europe" }
  ]
});

Advanced Features

This section covers advanced Matomo tracking capabilities that can be implemented with this library. Each feature includes example code that can be expanded by clicking on it.

Custom Instructions

You can use any Matomo tracking feature through the addCustomInstruction method:

// Track a goal conversion
tracker.addCustomInstruction('trackGoal', 1, 50.0);

// Enable cross-domain linking
tracker.addCustomInstruction('enableCrossDomainLinking');

// Set a custom variable
tracker.addCustomInstruction('setCustomVariable', 1, 'Category', 'Sports', 'page');

Ecommerce Tracking

// Add an item to the cart
tracker.addCustomInstruction('addEcommerceItem', 
  'SKU123',         // Product SKU
  'Product Name',   // Product name
  'Product Category', // Product category
  99.99,            // Product price
  2                 // Quantity
);

// Track a cart update
tracker.addCustomInstruction('trackEcommerceCartUpdate', 199.98);

// Track an order
tracker.addCustomInstruction('trackEcommerceOrder',
  'ORDER123',       // Order ID
  199.98,           // Grand total
  180.00,           // Subtotal
  19.98,            // Tax
  0,                // Shipping
  0                 // Discount
);

Goal Tracking

// Track a goal conversion
tracker.addCustomInstruction('trackGoal', 1);

// Track a goal conversion with revenue
tracker.addCustomInstruction('trackGoal', 1, 50.0);

Content Tracking

// Track all content impressions on the page
tracker.addCustomInstruction('trackAllContentImpressions');

// Track only visible content impressions
tracker.addCustomInstruction('trackVisibleContentImpressions', true, 750);

// Track a content impression manually
tracker.addCustomInstruction('trackContentImpression', 
  'Content Name', 
  'Content Piece', 
  'https://example.com'
);

// Track a content interaction manually
tracker.addCustomInstruction('trackContentInteraction',
  'click',
  'Content Name',
  'Content Piece',
  'https://example.com'
);

User Consent Management

// Require consent before tracking
tracker.addCustomInstruction('requireConsent');

// Set consent for the current user
tracker.addCustomInstruction('setConsentGiven');

// Remember consent for the current user
tracker.addCustomInstruction('rememberConsentGiven', 30); // 30 days

// Forget consent for the current user
tracker.addCustomInstruction('forgetConsentGiven');

Download and Outlink Tracking

// Set custom file extensions to be recognized as downloads
tracker.addCustomInstruction('setDownloadExtensions', 'zip|rar|pdf');

// Add additional file extensions to be recognized as downloads
tracker.addCustomInstruction('addDownloadExtensions', 'docx|xlsx');

// Manually track a download
tracker.addCustomInstruction('trackLink', 'https://example.com/file.pdf', 'download');

// Manually track an outlink
tracker.addCustomInstruction('trackLink', 'https://external-site.com', 'link');

Cross-Domain Tracking

// Enable cross-domain linking
tracker.addCustomInstruction('enableCrossDomainLinking');

// Set the domains to be treated as local
tracker.addCustomInstruction('setDomains', ['example.com', '*.example.org']);

Custom Variables

// Set a custom variable for the current visit
tracker.addCustomInstruction('setCustomVariable', 1, 'Gender', 'Male', 'visit');

// Set a custom variable for the current page view
tracker.addCustomInstruction('setCustomVariable', 2, 'Category', 'Sports', 'page');

Multiple Tracker Instances

// Add a second tracker to track data to another Matomo instance
tracker.addCustomInstruction('addTracker', 'https://another-matomo.com/matomo.php', 2);

Performance Optimization

This section provides techniques to optimize the performance impact of Matomo tracking in your React application. These optimizations help ensure that analytics tracking doesn't negatively affect your application's user experience.

Deferred Tracking

You can defer tracking until after critical page content has loaded:

const config = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1,
  deferTracking: true
};

This improves initial page load performance by loading the Matomo script with lower priority.

Optimized Event Tracking

Use the useMatomoEvent hook for optimized event tracking with memoized functions:

import { useMatomoEvent } from "@adam20054/react-matomo";

function YourComponent() {
  const { trackEvent } = useMatomoEvent();

  // This function won't cause unnecessary re-renders
  const handleClick = () => {
    trackEvent({
      category: "User Interaction",
      action: "Button Click"
    });
  };

  return <button onClick={handleClick}>Click Me</button>;
}

Debugging

When implementing Matomo tracking, it's helpful to verify that events are being tracked correctly. The debug mode provides detailed logging to help you troubleshoot any issues:

Enable debug mode to log tracking information to the console:

const config = {
  trackerBaseUrl: "https://analytics.example.com",
  siteId: 1,
  debug: true
};

This will log:

  • All tracking commands sent to Matomo
  • Warnings about deprecated or misconfigured options
  • Information about tracking being disabled or skipped

Contributing

Contributions are welcome! If you'd like to contribute to this project, please follow these steps:

  1. Fork the repository
  2. Create a new branch for your feature or bugfix
  3. Make your changes
  4. Add or update tests as necessary
  5. Run the tests to make sure everything passes
  6. Submit a pull request

Please make sure your code follows the existing style and includes appropriate tests.

License

This project is licensed under the MIT Licence.


Project Background

This project builds upon the foundations of React Matomo Tracker and Matomo-Tracker, enhancing them with advanced customization options, improved TypeScript support, and modern React patterns.

Originally created to enable custom Matomo tracker URLs (beyond the standard Matomo.js/php), the library has evolved into a complete solution for React analytics with an emphasis on developer experience and flexibility.