In this article, I am going to walk you through that how you Google Analytics Data API to fetch data from Google Analytics in the simplest way I can. After reading this article you'll be able to use this in your project with ease. So without further due, Let's jump into it.
In my portfolio, I have just implemented Google Analytics Data API so that I can show how many people have visited this site in the last 7 days. As my Portfolio is already using Google Analytics to track user visits. I just need to use its API to fetch that data.
But first, look at how it's showing in my portfolio:
Requirements
We need three values to fetch the data:
GA_PROPERTY_ID
GA_CLIENT_EMAIL
GA_PRIVATE_KEY
GA_PROPERTY_ID
First, you need to get GA_PROPERTY_ID
of the Google Analytics project from which you want to fetch the data.
To get this you need to follow these steps:
- Visit Google Analytics.
- Select Admin.
- Select the Property.
- Select Property Settings.
If the Property Settings shows a numeric PROPERTY ID
such as "123...", this is the numeric Id of your Google Analytics 4 property.
GA_CLIENT_EMAIL
and GA_PRIVATE_KEY
To get GA_CLIENT_EMAIL
and GA_PRIVATE_KEY
you need to visit Google Analytics Data API's documentation and then click on Enable the Google Analytics Data API v1 button as shown in the image below:
And then you will be prompted to enter the name of the project. After entering the name click on the Next button
Then you will be prompted to download the credential file as JSON.
After downloading that file. You will find private_key
and client_email
properties in that JSON file. Save these two in your .env.local
.
Now you have all the necessary information or keys.
Installing Dependency
To fetch the data you need to install a @google-analytics/data package. You can do that by simply running the following command in the terminal.
yarn add @google-analytics/data
# or
npm i @google-analytics/data
# or
pnpm i @google-analytics/data
Using Google Analytics Data API in Project
As I am using Next.js for my portfolio so I will use Next.js API Routes. You can do the same thing with different frameworks.
I will create an API route pages/api/ga.ts
:
import { NextApiRequest, NextApiResponse } from "next";
import { BetaAnalyticsDataClient } from "@google-analytics/data";
// ๐ Setting PropertyId
const propertyId = process.env.GA_PROPERTY_ID;
const analyticsDataClient = new BetaAnalyticsDataClient({
credentials: {
client_email: process.env.GA_CLIENT_EMAIL,
private_key: process.env.GA_PRIVATE_KEY?.replace(/\n/gm, "\n"), // replacing is necessary
},
});
export default async function handler(
_req: NextApiRequest,
res: NextApiResponse
) {
// ๐ Running a simple report
const [response] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dateRanges: [
{
startDate: `7daysAgo`, //๐ e.g. "7daysAgo" or "30daysAgo"
endDate: "today",
},
],
dimensions: [
{
name: "year", // data will be year wise
},
],
metrics: [
{
name: "activeUsers", // it returs the active users
},
],
});
// Returning the respose.
return res.status(200).json({
response,
});
}
The response would be:
{
"data": {
"dimensionHeaders": [
{
"name": "year"
}
],
"metricHeaders": [
{
"name": "activeUsers",
"type": "TYPE_INTEGER"
}
],
"rows": [
{
"dimensionValues": [
{
"value": "2023",
"oneValue": "value"
}
],
"metricValues": [
{
"value": "357",
"oneValue": "value"
}
]
}
],
"totals": [
],
"maximums": [
],
"minimums": [
],
"rowCount": 1,
"metadata": {
"dataLossFromOtherRow": false,
"currencyCode": "USD",
"_currencyCode": "currencyCode",
"timeZone": "America/Los_Angeles",
"_timeZone": "timeZone"
},
"propertyQuota": null,
"kind": "analyticsData#runReport"
}
}
This is all you need to fetch the data. and It will return the response. My portfolio code can be found on GitHub you can check out How I used it.
You can play with Dimensions and Metrics to get your desired data.
Wrapping up
In this article, I have explained how you can use the Google Analytics Data API to fetch data from Google Analytics. After reading this article, you should now be able to easily implement this API on your projects.
If you enjoyed this article, then don't forget to give โค๏ธ and Bookmark ๐ท๏ธfor later use and if you have any questions or feedback then don't hesitate to drop them in the comments below. I'll see in the next one.
Connect with me
Top comments (8)
hello, if my
rows
array is empty, does that mean I have some errors or simply means I don't have any visitors yet?Hello Arafat,
If you are getting empty
rows
array orrowCount
is 0, this simply means that the Google Analytics doesn't have any data of the requested metrics (in this caseactiveUsers
). In other words you don't have any visitors.P.S. In my blog, I have added a snippet of what the response would look like if you have visitors.
nice article @j471n
Thanks mate โบ๏ธ
I was unaware that Google also provides Analytics APIs. ๐ค๐ค
Thank you for sharing .... Sharma ji ๐๐
I guess Google provides API for it's every product (not sure though).
The Google Analytics Data API is incredibly versatile for extracting valuable insights from your data. Start by setting up a project in the Google Cloud Console and enabling the API. Authentication is crucial, usually via OAuth 2.0. For querying data, familiarize yourself with the API's report types and dimensions/metrics selection to tailor your data analysis effectively. I stumbled upon AppMetrica. Its user-friendly dashboard was a beacon of simplicity in the complex sea of analytics. The no-code integration was a sigh of relief, slashing the steep learning curve and saving me countless hours.
AppMetrica's flexibility in data handling was a game-changer. I could tweak and tailor the analytics to fit my unique needs without wrestling with rigid structures. This adaptability proved invaluable when dissecting revenue streams from in-app purchases. The data painted a clear picture of where our earnings were blossoming and provided the insight needed to refine our monetization strategy.
Good post! You forget to explain that after create the credentials needs to be added on analytics account acces!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.