loading...
Cover image for Vue + Google Firebase Analytics

Vue + Google Firebase Analytics

razbakov profile image Aleksey Razbakov Updated on ・5 min read

Google Analytics App + Web is available when you enable Google Firebase Analytics.

It's Google Analytics v2 with a new representation of data, which focuses on users and events rather than sessions, user properties and event parameters rather than hit, session and user scoped definitions, on audiences rather than segments. It has a powerful live time view and DebugView. It's a new way to unify app and website measurement in Google Analytics.

I am using Quasar Framework for Vue to create a Single Page Application (SPA), Progressive Web App (PWA) and planning to build native applications with Cordova and Electron, with build scripts provided by Quasar. While building my new budgeting app recently I discovered Firebase Analytics and decided to give it a try and enable analytics. I haven't tested it yet in native apps though.

Setup

I will show you how to track events in Vue application, but first you will need to activate Firebase Analytics. You will find there a video tutorial how to do it.

Next thing is to configure Firebase, I just followed setup instructions from vuex-easy-firestore, library which I use as SDK for Firestore, because it's very fast to kick-off.

Which library to choose?

My previous experience with Google Tag Manager and gtag made me go in a wrong direction and spend a lot of time on debugging and trying to understand what's going on.

What didn't work for me?

  • vue-gtm - for integration with Google Tag Manager (GTM), which will send events to GTM, where you have to forward them to Google Analytics. As a Developer you will need to do configuration twice. That was my first attempt and here I shared my opinion why gtag is better than GTM.
  • vue-gtag - for custom gtag implementation which will send events directly to Google Analytics. I was already convinced that gtag is better, but something went wrong and for a long time I didn't get why. Debugger showed me that gtag is initialized twice. I assumed it is cache from GTM, even though GTM was injecting only while building on Netlify, so locally it shouldn't have been there. So I checked official documentation and finally realized that I have firebase.analytics() which adds gtag automatically. Custom gtag is possible with some changes, but I decided to see how far I can go with already existing one.

What works?

Following recommended setup the easiest way is to remove your own gtag snippets and track events with:

firebase.analytics().logEvent("notification_received");

Let's check versions of node:

node -v
v12.14.1

npm -v
6.13.6

vue -V
@vue/cli 4.2.2

First, let's setup vue app:

npm install -g @vue/cli
vue create myapp
cd myapp
npm install firebase --save

Your package.json should look like this:

{
  "dependencies": {
    "core-js": "^3.6.4",
    "firebase": "^7.9.1",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.2.0",
    "@vue/cli-plugin-eslint": "~4.2.0",
    "@vue/cli-service": "~4.2.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.1.2",
    "vue-template-compiler": "^2.6.11"
  }
}

Go to the Firebase console and setup new app with activated Analytics.

Now let's add firebase with analytics and create an alias for it, so that you don't need to pollute each script with imports:

// main.js

import Vue from 'vue'
import App from './App.vue'

import * as firebase from "firebase/app";
import "firebase/firestore";
import "firebase/analytics";

const firebaseConfig = {
  apiKey: '<your-api-key>',
  authDomain: '<your-auth-domain>',
  databaseURL: '<your-database-url>',
  projectId: '<your-cloud-firestore-project>',
  storageBucket: '<your-storage-bucket>',
  messagingSenderId: '<your-sender-id>'
  appId: '<your-app-id>',
  measurementId: '<your-measurement-id>'
};

firebase.initializeApp(firebaseConfig);
firebase.analytics();

Vue.config.productionTip = false

// alias
Vue.prototype.$analytics = firebase.analytics();

new Vue({
  render: h => h(App),
}).$mount('#app')

Now you can track events in your component methods like this:

    this.$analytics.logEvent("notification_received");

How to track events?

Before introducing new event, make sure it's not already tracked by automatic events.

Activate enhanced measurement to track data from on-page elements such as links and embedded videos.

After that check if your event listed in recommended events, if so follow recommended parameters.

Otherwise you create your own custom events, but those will have reduced capabilities in analytics.

How to track page views?

Page views expect different document titles for different pages. The easiest way to implement it is to use vue-meta.

    // add to each of your page components
    metaInfo() {
      return {
        title: "Screen Name"
      };
    },

Normally you would track page views on router.afterEach, but vue-meta changes document title later and it would record a previous page name on navigation instead of new one. So we have to trigger on right timing after title updates.

// util.js
// this function defines if app is installed on homescreen as PWA
function isPWA() {
  return window && window.matchMedia("(display-mode: standalone)").matches;
}

// App.vue
import * as firebase from "firebase/app";
import { version } from "../package.json";
import { isPWA } from "./util";

// add to App component
export default {
  metaInfo: {
    changed(metaInfo) {
      firebase.analytics().setCurrentScreen(metaInfo.title);
      firebase.analytics().logEvent("page_view");
      firebase.analytics().logEvent("screen_view", {
        app_name: isPWA() ? "pwa" : "web",
        screen_name: metaInfo.title,
        app_version: version
      });
    }
  },
  mounted() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.$analytics.setUserId(user.uid);
        this.$analytics.setUserProperties({
          account_type: "Basic" // can help you to define audiences
        });
      }
    });
  }
}

Debugging

I used the following browser extensions to debug tracking:

  • GoogleAnalyticsDebugger - activates DebugView realtime in GA App + Web and logs communication in console log with errors
  • GTM/GA Debug - tab in inspector which shows all triggered events with parameters

Open Questions

How to set app version?

App version is automatically collected user property, but not in case if it is a web app.

gtag screenview has an app_version, somehow Analytics doesn't use it in reporting.

Other option is to add it to user properties, at least it becomes visible and filterable in reporting, but it is not clear if it works as intended.

Discussion

markdown guide
 

Hello @Aleksey,

Can you explain how you installed firebase/analytics ? I can't find this module on npm.

thanks

 

It's part of firebase package. You can install it with

npm install --save firebase

Refer to official firebase documentation and firebase analytics

 

Thanks for ur reply. But when i go here : firebase.google.com/docs/web/setup...

I can read that 'analytics' is not supported by nodejs.

firebase support

Am I wrong ?

I had the same feeling when I was reading that page for the first time.

Nodejs is meant as a server side and web as a client side. You can install firebase package via npm, no problem with that.

If window and document objects are available in runtime you are in web mode. But if you are trying to run nodejs express server and to track analytic event on some http patch method to your server it won't work.

Thanks again for ur time and ur reply.

My apologize, I don't understand. In ur article, you give that example :

import * as firebase from "firebase/app";
import "firebase/analytics";

// put this after firebase.initializeApp(...) 
// make sure it executes before any logEvent
firebase.analytics();

// alias
Vue.prototype.$analytics = firebase.analytics();

When I try this on my project I have this error:

This dependency was not found:

* firebase/analytics in ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/vuetify-loader/lib/loader.js??ref--18-0!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/NavBar.vue?vue&type=script&lang=js&

To install it, you can run: npm install --save firebase/analytics

Even if i did a npm install firebase

So what should I do to set forebase/analytics in my nodejs/vuejs project ?

Thanks for ur help and ur time

Have you initialized firebase?

import * as firebase from "firebase/app";
import "firebase/analytics";

const firebaseConfig = {
  apiKey: "xxx",
  // ...
};

firebase.initializeApp(firebaseConfig);
firebase.analytics();

Yes. Error comes on the second line with :

import "firebase/analytics";

Can you share a project where this works ?

I updated the setup section with step by step commands to setup vue app. I executed it step by step and checked that it works. Let me know if it works for you.

Sorry,
I still have the same problem importing firebase/analytics

if you have time to check : github.com/tibetoine/friends-party

Please follow updated setup section from the beginning. I added also versions and package.json for comparison.

In your project you only need to update firebase version, the one you use is too old and doesn't have analytics. Go to package.json and update it to:

"firebase": "^7.9.1",