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

matomo-tracker-for-react

v2.0.0

Published

A minimal yet powerful React package that integrates Matomo analytics with any React router.

Readme

Matomo React Tracker

📦 Overview

A minimal yet powerful React package that integrates Matomo analytics with any React router, including React Router, TanStack Router, and Next.js, enabling automatic page tracking and custom event tracking out of the box.

Written in TypeScript but designed to be fully compatible with JavaScript projects as well.


🚀 Features

  • Automatic Page View Tracking with any router via the path prop
  • Custom Event Tracking via useMatomo() hook
  • Matomo Initialization via MatomoProvider
  • Cookie Control: enable/disable cookies with a boolean
  • Opt-out Support
  • Opt-in Support
  • TypeScript-first, JavaScript-friendly
  • Tree-shakeable ESM/CJS output

🔧 Installation

npm install matomo-tracker-for-react

⚠️ Upgrading from v1 to v2

Version 2.0 introduces a breaking change to support any router (Next.js, TanStack Router, React Router, etc.).

The package no longer has a hard dependency on react-router-dom. Instead, you must pass the current route path to the path prop of <MatomoProvider>. If you do not provide the path prop, automatic page view tracking will be disabled.


🧱 Basic Usage

Wrap your app with MatomoProvider

You can use MatomoProvider with any router by passing the current path to the path prop.

Example with React Router

import { MatomoProvider } from "matomo-tracker-for-react";
import { BrowserRouter, useLocation } from "react-router-dom";

const AppWithTracking = () => {
  const location = useLocation();
  const currentPath = location.pathname + location.search + location.hash;

  return (
    <MatomoProvider
      urlBase="https://matomo.example.com"
      siteId="1"
      path={currentPath}
    >
      <App />
    </MatomoProvider>
  );
};

const Root = () => (
  <BrowserRouter>
    <AppWithTracking />
  </BrowserRouter>
);

Example with TanStack Router

import { MatomoProvider } from "matomo-tracker-for-react";
import {
  RouterProvider,
  createRouter,
  useRouterState,
} from "@tanstack/react-router";

const router = createRouter({ routeTree });

const AppWithTracking = () => {
  const location = useRouterState({ select: (s) => s.location });
  const currentPath = location.pathname + location.search + location.hash;

  return (
    <MatomoProvider
      urlBase="https://matomo.example.com"
      siteId="1"
      path={currentPath}
    >
      <RouterProvider router={router} />
    </MatomoProvider>
  );
};

Example with Next.js (App Router)

"use client";

import { MatomoProvider } from "matomo-tracker-for-react";
import { usePathname, useSearchParams } from "next/navigation";
import { Suspense } from "react";

const TrackingContent = ({ children }: { children: React.ReactNode }) => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // Construct the full path including search parameters
  const currentPath = `${pathname}${searchParams.toString() ? `?${searchParams.toString()}` : ""}`;

  return (
    <MatomoProvider
      urlBase="https://matomo.example.com"
      siteId="1"
      path={currentPath}
    >
      {children}
    </MatomoProvider>
  );
};

const AppWithTracking = ({ children }: { children: React.ReactNode }) => {
  return (
    <Suspense fallback={children}>
      <TrackingContent>{children}</TrackingContent>
    </Suspense>
  );
};

Example with Next.js (Pages Router)

import { MatomoProvider } from "matomo-tracker-for-react";
import { useRouter } from "next/router";

const AppWithTracking = ({ children }: { children: React.ReactNode }) => {
  const router = useRouter();
  const currentPath = router.asPath;

  return (
    <MatomoProvider
      urlBase="https://matomo.example.com"
      siteId="1"
      path={currentPath}
    >
      {children}
    </MatomoProvider>
  );
};

The library will detect page changes automatically when the path prop changes.

Track Custom Events

import { useMatomo } from "matomo-tracker-for-react";

const MyComponent = () => {
  const { trackEvent } = useMatomo();

  const handleClick = () => {
    trackEvent("Button", "Click", "My CTA Button");
  };

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

⚙️ API

<MatomoProvider> Props

| Prop | Type | Required | Description | | --------------- | -------------------- | -------- | -------------------------------------------------------------------------- | | children | ReactNode | ✅ | Your application components. | | urlBase | string | ✅ | Base URL of your Matomo instance (e.g., https://your-matomo-domain.com). | | siteId | string or number | ✅ | Your Matomo website ID. | | path | string | ❌ | The current path of the router. Used for automatic page view tracking. | | trackCookies? | boolean | ❌ | If false, disables cookies (disableCookies: true). Default: true. | | disabled? | boolean | ❌ | If true, disables all tracking. Default: false. |

useMatomo() Hook

Returns an object with:

  • trackEvent(category: string, action: string, name?: string, value?: number): Tracks a custom event.
  • trackPageView(customTitle?: string): Tracks a page view. Useful for SPAs if automatic tracking needs fine-tuning or if you want to set a custom title.
  • trackGoal(goalId: number | string, revenue?: number): Tracks a conversion for a specific goal.
  • setUserId(userId: string): Sets or updates a User ID for the current visitor.
  • trackLink(url: string, linkType: 'link' | 'download'): Tracks an outbound link click or a download.
  • pushInstruction(instruction: any[]): Allows pushing any raw instruction to the Matomo _paq array for advanced use cases (e.g., pushInstruction(['setUserId', 'USER_ID_HERE'])).

Troubleshooting

matomo.js script fails to load

If you see an error in your browser console like "Laden fehlgeschlagen für das mit der Quelle..." or "Failed to load resource..." for matomo.js, even if you can access the matomo.js URL directly in your browser, consider these common causes:

  1. CORS (Cross-Origin Resource Sharing):

    • Problem: Your React app (e.g., http://localhost:3000) and your Matomo instance (e.g., https://matomo.example.com) are on different origins.
    • Solution: Configure your Matomo server to send the Access-Control-Allow-Origin header, allowing requests from your React app's domain. For example, Access-Control-Allow-Origin: http://localhost:3000.
  2. Mixed Content:

    • Problem: Your React app is on https but matomo.js is requested via http.
    • Solution: Ensure both your app and Matomo (and the urlBase/srcUrl provided) use https.
  3. Content Security Policy (CSP):

    • Problem: Your app's CSP might be blocking scripts from the Matomo domain.
    • Solution: Update your CSP to include your Matomo domain in script-src (e.g., script-src 'self' https://matomo.example.com;).
  4. Ad Blockers/Browser Extensions:

    • Problem: Extensions might block the script when loaded by your app.
    • Solution: Temporarily disable extensions to test. If an extension is the cause, consider whitelisting.

🔒 Privacy & Compliance

  • Fully respects user privacy: cookies and tracking can be disabled.
  • Compatible with GDPR if configured appropriately in Matomo and your application.

🔜 Roadmap

  • [x] Add goal tracking (trackGoal)
  • [x] Add user ID support (setUserId)
  • [x] Add link/interaction tracking (trackLink)
  • [x] Basic React Router integration for page views
  • [x] Next.js support
  • [x] TanStack Router support
  • [ ] Add more helper hooks
  • [ ] Add tests with Vitest or Jest

💖 Support

If you find this package helpful, consider supporting its development:

Buy Me A Coffee


🙌 Credits

Inspired by:


💬 License

MPL-2.0