How To Add Google Analytics to Your Vue.js Web App

Surbhit Rao
3 min readDec 27, 2021

Google Analytics is a free tracking tool to analyze your website visitors — this is also possible in Vue.js Apps. Here you can find out how it works!

Once you have your Vue.js app ready and deployed on the internet, Google Analytics can help you find out how users interact with your website. What buttons do they click, how much time do they spend on a page/section, which part of the world are you getting the most traffic from and much more.

Vue.js applications are usually implemented as SPA (Single Page Application). For tracking this means that we cannot simply integrate the normal Google Analytics snippet on our site, e.g. in the head.

This tutorial will be divided into 4 parts:
1. Installing Vue Analytics
2. Creating a Google Analytics project
3. Configuring Vue Analytics inside your project
4. Making the code reusable and readable

Installing Vue Analytics

vue-gtag is one of the most recent and robust library to add Google Analytics inside a Vue app. Install using the below commands depending on if you’re using npm or yarn.

Creating a Google Analytics project

Sign up on Google Analytics.
Create a new Google Analytics account.
Create a new property (A property represents a business’s web and/or app data)

Add a new data stream

Click on Web.

Add your website URL. If you’re working in a local environment you can easily setup a tunnel using ngrok and use the ngrok temporary URL to setup a data stream.

Configuring Vue Analytics inside your project

Go into your main file (entry point) and import vuegtag library and initialize it. Replace the id here with the measurement id of your data stream that we had created in the last step.

The strategy is to identify the sections of the app wherein an user can trigger an explicit event such as clicking a button.

Mapping a Google Analytics event to a button click inside our app

Register a Google Analytics event on button click as shown below:

Note: You won’t have to explicitly import vue-gtag library inside a component once you’ve initialized it in your main file.

Inside your Google Analytics console you should be able to see the events on button click, inside real time reports tab. It takes usually 48 hours for the actual data to accumulate.

Remember, this is just an example. check the all API parameters in the official gtag documentation here

Making the code reusable and readable

Mixins are a flexible way to distribute reusable functionalities for Vue components. So we’ll be creating a simple mixin for our Google analytics event.

Inside your mixin folder create a new mixin with the following code:

Using the Google Analytics mixin inside any component

--

--