I am trying to add analytics to an already existing web app. I initialize Firebase Analytics as described here.


const firebase = require('firebase');
firebase.initializeApp(config);
firebase.analytics();

I get this error TypeError: firebase.analytics is not a function

What could the problem be?


You have to import 'firebase/analytics' for side effects:

const firebase = require('firebase/app')
require('firebase/analytics')

firebase.initializeApp(config);
firebase.analytics();

That worked for me


In my case, this worked. I'm using firebase version ^8.1.2

import firebase from 'firebase/app';
import 'firebase/analytics';
import 'firebase/auth';

...

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();

First, make sure you initialize firebase instance correctly, it won't work if you run it in server-side, then official providers a method to check whether your environment supports analytics or not, call firebase.analytics.isSupported(), this is a promise, so the correct way to use it is

var firebaseConfig... // your config

var firebase.initializeApp(firebaseConfig);

firebase.analytics.isSupported().then((isSupported) => {
    if (isSupported) {
      analytics = firebase.analytics();
    }
})