Skip to main content
Version: 2.0

Track Analytics in Docusaurus Site

This section describes the process of tracking analytics data on your Docusaurus site. We will use Google Analytics service provided by Firebase.

Prerequisites​

  • Perform the configurations in Create Firebase Project and Create Firebase App sections.

  • Ensure that Google Analytics is enabled in your Firebase account by navigating to the Integrations tab. The Google Analytics widget should display an Enabled message as shown in the following image.

Setup​

  1. Execute the following command, if not executed previously.
npm install firebase
  1. Create a folder called utils within the src folder.

  2. Create a file called firebaseconfig.js within the utils folder and add the following code.

Replace the values of apikey, AuthDomain, and other variables with your Firebase values.

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth"; // If you're using Firebase Auth
import { getAnalytics } from "firebase/analytics"; // For Google Analytics

const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID", // Crucial for Analytics
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// Initialize Firebase services
export const auth = getAuth(app); // If you're using Firebase Auth
export const analytics = getAnalytics(app); // For Google Analytics

// You might export 'app' if you need it elsewhere
export default app;
  1. Update the docusaurus.config,js file with gtag data as with the following code (just before the themeconfig section).
gtag: {  
trackingID: 'YOUR\_TRACKING\_ID', // Use your GA4 Measurement ID (starts with 'G-')
anonymizeIP: true, // Optional: Anonymize IP addresses
},

  1. Open Command Prompt and execute the following commands (one after the other) in your project root directory.
   npm run build  
   npm run serve
  1. In your browser, open localhost:3000 and go through the pages to generate analytics data.

  2. In Firebase project settings, expand Analytics and select Realtime analytics.

You can see that analytics data is generated. In my case, data is generated for 1 view (my own view).

Similarly, you can view data like which page got the highest views, which region has highest users, and so on. You can also set up tracking of custom events by adding code for each event to be tracked.