How to Add Firebase Analytics to a Gatsby Project

With Gatsby being a Static Site Generator, adding functionality that uses browser globals can break the Node.js build step. This is the case for Firebase Analytics, so adding it to a Gatsby project can be a little tricky. In this article, I’ll show you how to add Firebase Analytics to a Gatsby project the correct way.

Dependencies

We will be adding three dependencies to our project to get Firebase Analytics up and running, dotenv, firebase and gatsby-plugin-firebase. When writing this article on March 31, 2022, gatsby-plugin-firebase only supports version 8.x.x of the firebase plugin.

Using Yarn:

yarn add dotenv firebase@8.10.0 gatsby-plugin-firebase

Using NPM:

npm install dotenv firebase@8.10.0 gatsby-plugin-firebase

Firebase Setup

Head over to console.firebase.google.com and create a new project if you haven’t already. Make sure you enable Analytics.

Firebase landing page

Next up, add Firebase as a web app. Once the app is set up, you can head over to the project's settings to see the Firebase web configuration. You will need these values for the next step.

Gatsby Setup

We start by creating the file .env where we will be storing our environment variables. Remember to add this file to .gitignore if you don’t want your variables to be tracked by git.

The .env should look like the following:

GATSBY_FIREBASE_API_KEY=...
GATSBY_FIREBASE_AUTH_DOMAIN=...
GATSBY_FIREBASE_DATABASE_URL=...
GATSBY_FIREBASE_PROJECT_ID=...
GATSBY_FIREBASE_STORAGE_BUCKET=...
GATSBY_FIREBASE_MESSAGING_SENDER_ID=...
GATSBY_FIREBASE_APP_ID=...
GATSBY_FIREBASE_MEASUREMENT_ID=...

In your gatsby-config.js file:

require('dotenv').config()

module.exports = {
  plugins: [
    ...otherPlugins,
    {
      resolve: 'gatsby-plugin-firebase',
      options: {
        features: {
          auth: false,
          database: false,
          firestore: false,
          storage: false,
          messaging: false,
          functions: false,
          performance: false,
          analytics: true,
        },
        credentials: {
          apiKey: process.env.GATSBY_FIREBASE_API_KEY,
          authDomain: process.env.GATSBY_FIREBASE_AUTH_DOMAIN,
          databaseURL: process.env.GATSBY_FIREBASE_DATABASE_URL,
          projectId: process.env.GATSBY_FIREBASE_PROJECT_ID,
          storageBucket: process.env.GATSBY_FIREBASE_STORAGE_BUCKET,
          messagingSenderId: process.env.GATSBY_FIREBASE_MESSAGING_SENDER_ID,
          appId: process.env.GATSBY_FIREBASE_APP_ID,
          measurementId: process.env.GATSBY_FIREBASE_MEASUREMENT_ID,
        },
      },
    },
  ],
}

Next up, add the following import to both gatsby-browser.js and gatsby-ssr.js:

import 'firebase/analytics'

Usage

Now that your Firebase Analytics is properly set up, you can start using it. This is an example of how you can track a page visit:

import React, { useEffect } from 'react'
import firebase from 'gatsby-plugin-firebase'

const Home = () => {
  useEffect(() => {
    if (!firebase) {
      return
    }

    firebase.analytics().logEvent('visited_homepage')
  }, [firebase])

  return (
    <section>
      <h1>Hello, Firebase!</h1>
    </section>
  )
}

export default Home

When you run your website you should now see requests being sent to firebase.googleapis.com and google-analytics.com:

Request sent to firebase.googleapis.com

Request sent to google-analytics.com

If the requests do not fail you have set everything up correctly! If you head back to console.firebase.google.com you should be able to check out the real-time analytics.

Realtime analytics

Restricting the API key

It is a good idea to restrict your API key so that analytic requests can only be sent from a domain you own. To do this, head over to the Google Cloud Platform console at console.cloud.google.com. Select your project and navigate to the API Credentials page. Add an HTTP referrers restriction to match the URL of your website.

restrictions

You should now have Firebase Analytics set up on your Gatsby project! Thanks for checking out this article; any feedback is greatly appreciated!

Reply via emailBuy me a coffee

Join the newsletter

Every two weeks, I send an email about things that interest me, things I have built and things I have learned.

Previous issues