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.
- ✅ Automatic Page View Tracking with any router via the
pathprop - ✅ Custom Event Tracking via
useMatomo()hook - ✅ Matomo Initialization via
MatomoProvider - ✅ Cookie Control: enable/disable cookies with a boolean
- ✅ Opt-out & Opt-in Support via
optUserOut()/forgetUserOptOut() - ✅ User ID Reset via
resetUserId() - ✅ Site Search Tracking via
trackSiteSearch() - ✅ TypeScript-first, JavaScript-friendly
- ✅ Tree-shakeable ESM/CJS output
npm install matomo-tracker-for-reactVersion 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.
You can use MatomoProvider with any router by passing the current path to the path prop.
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>
);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>
);
};"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>
);
};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.
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>;
};import { useMatomo } from "matomo-tracker-for-react";
const MyComponent = () => {
const { trackEvent } = useMatomo();
const handleClick = () => {
trackEvent("Button", "Click", "Pricing CTA", undefined, {
dimension1: "pro",
dimension2: "A/B-test-variant-b",
});
};
return <button onClick={handleClick}>Click Me</button>;
};customDimensions are hit-scoped in these helpers, so they are automatically removed after each call.
You can track events without writing any JavaScript by adding data attributes to
your HTML elements. The MatomoTracker automatically picks up elements with
data-matomo-event="click" and listens for click events:
<button
data-matomo-event="click"
data-matomo-category="Video"
data-matomo-action="Play"
data-matomo-name="Getting Started"
data-matomo-value="42"
>
Play Tutorial
</button>| Attribute | Required | Description |
|---|---|---|
data-matomo-event |
✅ | Must be "click" |
data-matomo-category |
✅ | Event category (e.g. "Video") |
data-matomo-action |
✅ | Event action (e.g. "Play") |
data-matomo-name |
❌ | Event name (e.g. "Getting Started") |
data-matomo-value |
❌ | Numeric value (e.g. "42") |
This also works for elements dynamically added to the DOM — the tracker uses
a MutationObserver under the hood.
| 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. |
linkTracking? |
boolean |
❌ | If false, disables Matomo's automatic link click tracking. Useful for SPAs where it interferes with client-side routing. Default: true. |
disabled? |
boolean |
❌ | If true, disables all tracking. Default: false. |
Returns an object with:
-
customDimensionsbelow accepts an object like{ dimension1: "value", dimension2: "value" }. -
trackEvent(category: string, action: string, name?: string, value?: number, customDimensions?): Tracks a custom event. -
trackPageView(customTitle?: string, customDimensions?): 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, customDimensions?): 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', customDimensions?): Tracks an outbound link click or a download. -
trackSiteSearch(keyword: string, category?: string, count?: number, customDimensions?): Tracks an internal site search. -
resetUserId(): Clears the currently set User ID (useful on logout). -
optUserOut(): Opts the current user out of tracking. -
forgetUserOptOut(): Reverses a previous opt-out, allowing tracking again. -
pushInstruction(instruction: any[]): Allows pushing any raw instruction to the Matomo_paqarray for advanced use cases (e.g.,pushInstruction(['setUserId', 'USER_ID_HERE'])).
If you see each page view tracked twice while developing, your app wraps the
provider in <React.StrictMode>: Strict Mode intentionally mounts effects
twice in development. Production builds track each page view exactly once —
this is a dev-only artifact and requires no action.
If you see an error in your browser console like "Laden fehlgeschlagen für das <script> 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:
-
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-Originheader, allowing requests from your React app's domain. For example,Access-Control-Allow-Origin: http://localhost:3000.
- Problem: Your React app (e.g.,
-
Mixed Content:
- Problem: Your React app is on
httpsbutmatomo.jsis requested viahttp. - Solution: Ensure both your app and Matomo (and the
urlBase/srcUrlprovided) usehttps.
- Problem: Your React app is on
-
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;).
-
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.
npm testBuilds the package and runs the tracker/provider unit tests against the compiled output.
npm run test:e2e drives the example app in headless Chrome, performs real tracking
interactions, and asserts the results via the Matomo Reporting API. It verifies page
views, events, manual link tracking, automatic link tracking, and that linkTracking={false}
disables automatic link clicks while keeping everything else working.
Setup (the token stays local — tests/e2e/.env is gitignored):
cp tests/e2e/.env.example tests/e2e/.env
# fill in MATOMO_URL, MATOMO_SITE_ID, MATOMO_TOKEN
npm run test:e2eThe suite boots its own dev server (port 3100) and uses the system Chromium by default
(override with PUPPETEER_EXECUTABLE_PATH). The example app must be installed and the
local package build must be copied into its node_modules (see examples/).
- Fully respects user privacy: cookies and tracking can be disabled.
- Compatible with GDPR if configured appropriately in Matomo and your application.
- Add goal tracking (
trackGoal) - Add user ID support (
setUserId) - Add link/interaction tracking (
trackLink) - Basic React Router integration for page views
- Next.js support
- TanStack Router support
- Add site search tracking (
trackSiteSearch) - Add opt-out / opt-in support (
optUserOut,forgetUserOptOut) - Add user ID reset (
resetUserId) - Declarative data-attribute tracking
- Add more helper hooks
- Add React component tests
If you find this package helpful, consider supporting its development:
Inspired by:
- Matomo docs on React integration
@datapunt/matomo-tracker-react(now deprecated)
MPL-2.0
