How to add Google Analytics to your React.js Application
2 min readDec 8, 2022
Guide to adding Google Analytics to React.js application via Firebase.
Prerequisites
- Should have a React.js application configured via create-react-app. i.e.
npx create-react-app my-app --template typescript
. - Should have a Firebase (Google Cloud) account.
Let’s get started
Add Firebase to your package.json.
yarn add firebase # npm install firebase
Set up the Firebase project and set up the configs into App.tsx (or App.js) file.
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// ...
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
getAnalytics(app);
// ...
You can find how I set up environment variables in my other story:
Add Google Tag into the public/index.html file.
<head>
....
</head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=%REACT_APP_FIREBASE_MEASUREMENT_ID%"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', "%REACT_APP_FIREBASE_MEASUREMENT_ID%");
</script>
....
That’s it! It should be good to go live in production.
Live life to the fullest,
Stephen S. Lee