Vue + Matomo
Open-source, self-hostable analytics with Matomo; client-side navigations count too. This page shows exactly what pickstack adds to a Vue 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 vue --modules matomo --yesCustomize in the configurator
New files
VITE_MATOMO_URL= VITE_MATOMO_SITE_ID=
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
import { createApp } from "vue"; import App from "./App.vue";+import { initAnalytics } from "./analytics"; import "./assets/main.css"; +initAnalytics();+ createApp(App).mount("#app");
Project files
.env.example.gitignoreREADME.mdenv.d.tsindex.htmlpackage.jsonsrc/App.vuesrc/analytics.tssrc/assets/main.csssrc/components/CounterCard.vuesrc/main.tstsconfig.app.jsontsconfig.jsontsconfig.node.jsonvite.config.ts