i have installed a google analytics ga4 in my mobile app now i need to fetch the GA report into node.js using google analytics report api.
i have read the google analytics report document but the did'nt mentioned about how to get reoprt for node.js
This is a basic example for extracting data from Google analytics ga4 with node.js
// npm install googleapis@105 @google-cloud/[email protected] --save
// npm install @google-analytics/data
const fs = require('fs');
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly'];
const CREDENTIALS_PATH = 'C:\\Development\\FreeLance\\GoogleSamples\\Credentials\\ServiceAccountCred.json';
/**
* Runs a Google Analytics report
* For a given property id
*/
async function runReport(propertyId) {
// Imports the Google Analytics Data API client library.
const {BetaAnalyticsDataClient} = require('@google-analytics/data');
// Load the credentials.
const content = fs.readFileSync(CREDENTIALS_PATH, {encoding:'utf8', flag:'r'});
const keys = JSON.parse(content);
const analyticsDataClient = new BetaAnalyticsDataClient(
{ credentials: keys}
);
// 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]);
});
}
await runReport();
}
runReport('250796939').then().catch(console.error);