How to use Google Analytics?

First, please check the official Google Analytics module for Nuxt.js.

Otherwise, to use Google Analytics with your Nuxt.js application, we recommend you create a file plugins/ga.js:

  1. /* eslint-disable */
  2. export default ({ app }) => {
  3. /*
  4. ** Only run on client-side and only in production mode
  5. */
  6. if (process.env.NODE_ENV !== 'production')
  7. return /*
  8. ** Include Google Analytics Script
  9. */
  10. ;(function (i, s, o, g, r, a, m) {
  11. i['GoogleAnalyticsObject'] = r
  12. ;(i[r] =
  13. i[r] ||
  14. function () {
  15. ;(i[r].q = i[r].q || []).push(arguments)
  16. }),
  17. (i[r].l = 1 * new Date())
  18. ;(a = s.createElement(o)), (m = s.getElementsByTagName(o)[0])
  19. a.async = 1
  20. a.src = g
  21. m.parentNode.insertBefore(a, m)
  22. })(
  23. window,
  24. document,
  25. 'script',
  26. 'https://www.google-analytics.com/analytics.js',
  27. 'ga'
  28. )
  29. /*
  30. ** Set the current page
  31. */
  32. ga('create', 'UA-XXXXXXXX-X', 'auto')
  33. /*
  34. ** Every time the route changes (fired on initialization too)
  35. */
  36. app.router.afterEach((to, from) => {
  37. /*
  38. ** We tell Google Analytics to add a `pageview`
  39. */
  40. ga('set', 'page', to.fullPath)
  41. ga('send', 'pageview')
  42. })
  43. }

Replace UA-XXXXXXXX-X by your Google Analytics tracking ID.

Then, we tell Nuxt.js to import it in our main application:

nuxt.config.js

  1. export default {
  2. plugins: [{ src: '~plugins/ga.js', mode: 'client' }]
  3. }

Voilà, Google Analytics is integrated into your Nuxt.js application and will track every page view!

Info: you can use this method for any other tracking service.