Search code examples
javascriptfirebasegoogle-analyticsfirebase-analytics

How to initiate Firebase Analytics to work on Web?


I have initiated a FB SDK in the project following the documentation:

Getting started with Analytics is easy. Just add the Firebase SDK to your new or existing app, and data collection begins automatically. You can view analytics data in the Firebase console within hours.

Here is my main.js

 // Production Firebase configuration
  firebaseConfig = {
    apiKey: <AKI_LEY>,
    authDomain: <DOMAIN>,
    databaseURL: <DB_URL>,
    projectId: <PROJECT_ID>,
    storageBucket: "",
    messagingSenderId: <SENDER_ID>,
    appId: <APP_ID>,
    measurementId: <TRACKING_ID>
  };

firebase.initializeApp(firebaseConfig);
// missing firebase.analytics(); but calling this in main will throw exception. Calling this in index.html will also throw exception as initializeApp has to be called before.

This allows the application to work with firebase Storage and Auth services but analytics is still not registering anything.

What am I missing?

EDIT

After reading more documentation and double checking my index, I added the following <scripts> but with no prevail.

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script src='https://www.gstatic.com/firebasejs/7.5.0/firebase-analytics.js'></script>

The problem Default webpack firebase import doesn't have firebase analytics libraries, that's why you need to import using CDN.

After import in index I still need to run firebase.analytics() but that has to follow firebase.initializeApp().

How can one call both in the main.js so that firebase functions are not separated between index and main?

Also my main includes more logic to decide on the firebase config setup (have multiple projects) so I cannot just move all the firebase actions into index.html.

Thanks.


Solution

  • This was an issue with how the firebase library was structured. It was fixed in 7.1.0 and the analytics package is now included.

    Link to firebase github issue.

    Here is the summary how I got it working:

    index.html

    ...
    <body>
        <!-- The core Firebase JS SDK is always required and must be listed first -->
        <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-analytics.js"></script>
    ...
    

    main.js

    import * as firebase from 'firebase/app';
    ...
    firebase.initializeApp(firebaseConfig);
    firebase.analytics();
    ...
    

    This resulted in getting stats on firebase. It took 2 days for it to propagate.