Search code examples
node.jsgoogle-apigoogle-analytics-apigoogle-api-nodejs-clientgoogle-analytics-data-api

How to get statistics using Google Analytics Data


I wanted to bring statistics from Firebase to my website. To do this, I linked Firebase with Google Analytics in the settings in the "Integrations" tab

From there I copied the Property ID

Enabled Google Analytics Data API in my project

Then I replaced the Property ID with my own in this script and ran the script.

But I got an error:

Unable to detect a Project Id in the current environment. To learn more about authentication and Google APIs, visit:https://cloud.google.com/docs/authentication/getting-started


Solution

  • I suspect the issue is that you have not configured GOOGLE_APPLICATION_CREDENTIALS

    You should be following the API Quickstart it shows how to configure the credentials needed to authorize this code.

    enter image description here

    Once your authorization is configured you should be able to access this. Remember that the service account needs to be granted access to your google analytics account or it wont be able to access the property.

      /**
       * TODO(developer): Uncomment this variable and replace with your
       *   Google Analytics 4 property ID before running the sample.
       */
      // propertyId = 'YOUR-GA4-PROPERTY-ID';
    
      // Imports the Google Analytics Data API client library.
      const {BetaAnalyticsDataClient} = require('@google-analytics/data');
    
      // Using a default constructor instructs the client to use the credentials
      // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
      const analyticsDataClient = new BetaAnalyticsDataClient();
    
      // Runs a simple report.
      async function runReport() {
        const [response] = await analyticsDataClient.runReport({
          property: `properties/${propertyId}`,
          dateRanges: [
            {
              startDate: '2020-03-31',
              endDate: 'today',
            },
          ],
          dimensions: [
            {
              name: 'city',
            },
          ],
          metrics: [
            {
              name: 'activeUsers',
            },
          ],
        });
    
        console.log('Report result:');
        response.rows.forEach(row => {
          console.log(row.dimensionValues[0], row.metricValues[0]);
        });
      }
    
      runReport();