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