visit
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.
yarn add dotenv [email protected] gatsby-plugin-firebase
npm install dotenv [email protected] gatsby-plugin-firebase
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.
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";
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
: