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') return
  7. /*
  8. ** Include Google Analytics Script
  9. */
  10. (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  11. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  12. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  13. })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  14. /*
  15. ** Set the current page
  16. */
  17. ga('create', 'UA-XXXXXXXX-X', 'auto')
  18. /*
  19. ** Every time the route changes (fired on initialization too)
  20. */
  21. app.router.afterEach((to, from) => {
  22. /*
  23. ** We tell Google Analytics to add a `pageview`
  24. */
  25. ga('set', 'page', to.fullPath)
  26. ga('send', 'pageview')
  27. })
  28. }

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: [
  3. { src: '~plugins/ga.js', mode: 'client' }
  4. ]
  5. }

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.