Last active
February 5, 2025 12:52
-
-
Save elreco/04e69677f95f3d89e26328e1166dfa49 to your computer and use it in GitHub Desktop.
Integrate Matomo in a Nuxt 3 Application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ~/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); | |
}); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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