Skip to content

Instantly share code, notes, and snippets.

@elreco
Last active February 5, 2025 12:52
Show Gist options
  • Save elreco/04e69677f95f3d89e26328e1166dfa49 to your computer and use it in GitHub Desktop.
Save elreco/04e69677f95f3d89e26328e1166dfa49 to your computer and use it in GitHub Desktop.
Integrate Matomo in a Nuxt 3 Application
// ~/plugins/matomo.client.ts
const loadMatomoScript = () => {
const script = document.createElement('script');
script.async = true;
script.src = 'https://your-matomo-instance.com/js/container.js'; // Replace with your Matomo instance URL
document.getElementsByTagName('script')[0].parentNode?.insertBefore(script, null);
};
const setInitTracking = () => {
if (window._paq) {
// You can add custom dimensions here
// like the authenticated user details
window._paq.push(['trackPageView']);
}
};
export default defineNuxtPlugin((nuxtApp) => {
if (import.meta.client) {
const _mtm = (window._mtm = window._mtm || []);
const router = nuxtApp.$router;
_mtm.push({ 'mtm.startTime': new Date().getTime(), event: 'mtm.Start' });
loadMatomoScript();
setInitTracking();
router.afterEach((to) => {
setNavigationTracking(to.path);
});
}
});
// nuxt.config.ts
export default defineNuxtConfig({
plugins: [
'~/plugins/matomo.client.ts',
],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment