pickstack

React + Matomo

Open-source, self-hostable analytics with Matomo; client-side navigations count too. This page shows exactly what pickstack adds to a React project for Matomo: the packages, the new files and the changes to existing ones. Every combination is installed, built, linted and tested in CI.

$ npm create pickstack@latest my-app -- --framework react --modules matomo --yes
Customize in the configurator

New files

.env.example
VITE_MATOMO_URL=
VITE_MATOMO_SITE_ID=
src/analytics.ts
declare global {
  interface Window {
    _paq?: unknown[][];
  }
}

/** Matomo's tracking code; off until the Matomo URL and site ID are set (see .env.example). */
export function initAnalytics() {
  const url = import.meta.env.VITE_MATOMO_URL;
  const siteId = import.meta.env.VITE_MATOMO_SITE_ID;
  if (!url || !siteId) return;
  const base = url.endsWith("/") ? url : `${url}/`;
  const paq = window._paq ?? [];
  window._paq = paq;
  paq.push(["trackPageView"]);
  paq.push(["enableLinkTracking"]);
  paq.push(["setTrackerUrl", `${base}matomo.php`]);
  paq.push(["setSiteId", siteId]);
  const script = document.createElement("script");
  script.async = true;
  script.src = `${base}matomo.js`;
  document.head.append(script);

  // Matomo can't see client-side navigations: report each URL the router moves to.
  let previous = location.href;
  const trackNavigation = () => {
    if (location.href === previous) return;
    paq.push(["setReferrerUrl", previous]);
    previous = location.href;
    paq.push(["setCustomUrl", location.href]);
    paq.push(["setDocumentTitle", document.title]);
    paq.push(["trackPageView"]);
  };
  const pushState = history.pushState.bind(history);
  history.pushState = (...args: Parameters<History["pushState"]>) => {
    pushState(...args);
    trackNavigation();
  };
  window.addEventListener("popstate", trackNavigation);
}

Changes to existing files

src/main.tsx (changed)
 import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import App from "./App";+import { initAnalytics } from "./analytics"; import "./index.css";  +initAnalytics();+  createRoot(document.getElementById("root")!).render(   <StrictMode>     <App />⋯ 3 unchanged lines

Project files

Related templates