Reputation: 21
This is how I fetched the data from google analytics 4 using the nodejs client library '@google-analytics/data'. Is there any other ways for fetching the GA4 data like usersByGender, UsersGeoMap(users from particular country who view my website), usersbybrowser and many more. Need help!
const catchAsync = require("../utils/catchAsync");
const {BetaAnalyticsDataClient} = require("@google-analytics/data");
const propertyId = process.env.PROPERTY_ID;
const analyticsDataClient = new BetaAnalyticsDataClient();
const fetchDeviceCategories = async function(req, res, next) {
try {
const [response] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dateRanges: [
{
startDate: '2023-10-31',
endDate: 'today',
}
],
dimensions: [
{
name: 'deviceCategory',
}
],
metrics: [
{
name: 'totalUsers'
}
]
})
let transformedDeviceCategoriesData = response?.rows.map(row => ({
deviceCategory: row.dimensionValues[0].value,
value: row.metricValues[0].value,
}))
return transformedDeviceCategoriesData || [];
} catch(error) {
console.log(error, "error from fetching GA4 device categories data");
next(error);
}
};
const fetchUsersByCountry = async function(req, res, next) {
try {
const [response] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dateRanges: [
{
startDate: '2023-10-31',
endDate: 'today'
}
],
dimensions: [
{
name: 'country'
}
],
metrics: [
{
name: 'totalUsers'
}
]
})
const usersByCountry = response?.rows.map(row => ({
country: row.dimensionValues[0].value,
users: row.metricValues[0].value,
}))
return usersByCountry || [];
} catch(error) {
console.log(error, "error from fetching GA4 usersByCountry data");
next(error);
}
};
Upvotes: 1
Views: 64