How to extract data from Google Analytics using NodeJs SDK?

69 Views Asked by At

I have a use case to extract Page path and screen class data from Google Analytics,
I've found some reference code in Javascript but the code needs access to GCP credentials,
I have enabled Google Analytics Data API on the GCP dashboard,
Also created a service account and downloaded the .json Key

How do I refer the credential .json file to the SDK code?

const googleAnalytics = require('@analytics/google-analytics');

let test = async () => {
    
      const report = googleAnalytics.reports().get({
        ids: 'ga:xxx',
        start_date: '2023-05-01',
        end_date: '2023-07-31',
        metrics: 'ga:pageviews,ga:screenviews',
        dimensions: ['ga:pagePath', 'ga:screenClass']
      });
      
      report.then(function(response){
        const pages = response.data.rows.map(row => row[0]);
        const screens = response.data.rows.map(row => row[1]);
        const screenClasses = response.data.rows.map(row => row[2]);
      
        console.log('Pages: ', pages);
        console.log('Screens: ', screens);
        console.log('Screen Classes: ', screenClasses);
      });
      
}

test();

My test environment is local and the server will be AWS,
What is the right way to store and use the credentials?

0

There are 0 best solutions below