How to use Google Analytics Data API
Tags: webdev, javascript, beginners, tutorial
Published: 2023-01-15 05:08:36


In this article, I am going to walk you through that how you [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) to fetch data from [Google Analytics](https://analytics.google.com/) 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](https://j471n.in/), I have just implemented [Google Analytics Data API](https://developers.google.com/analytics/devguides/reporting/data/v1) 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](https://j471n.in/):

![](https://i.imgur.com/gFNCTvQ.png)

## 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](https://analytics.google.com/).
* 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.

![](https://i.imgur.com/scjFbin.png)

### `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](https://developers.google.com/analytics/devguides/reporting/data/v1/quickstart-client-libraries) and then click on **Enable the Google Analytics Data API v1** button as shown in the image below:

![](https://i.imgur.com/WrN2YwC.png)

And then you will be prompted to enter the name of the project. After entering the name click on the **Next** button

![](https://i.imgur.com/2BwwX84.png)

Then you will be prompted to download the credential file as JSON.

![](https://i.imgur.com/TU6qYrV.png)

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](https://www.npmjs.com/package/@google-analytics/data) package. You can do that by simply running the following command in the terminal.

```bash
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](https://nextjs.org/) for my portfolio so I will use [Next.js API Routes](https://nextjs.org/docs/api-routes/introduction). You can do the same thing with different frameworks.

I will create an API route `pages/api/ga.ts`:

```typescript
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:

```json
{
  "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](https://github.com/j471n/j471n.in/blob/main/pages/api/ga.ts) you can check out How I used it.

You can play with [Dimensions and Metrics](https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema) 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**

|Twitter |GitHub  | LinkedIn | Instagram | Website| Newsletter| Support |
|--|--|--|--|--|--|--|
| [![](https://cdn-icons-png.flaticon.com/32/4494/4494477.png)](https://twitter.com/j471n_) |[![](https://cdn-icons-png.flaticon.com/32/2504/2504911.png)](https://github.com/j471n) |  [![](https://cdn-icons-png.flaticon.com/32/3536/3536505.png)](https://www.linkedin.com/in/j471n/)|[![](https://cdn-icons-png.flaticon.com/32/174/174855.png)](https://instagram.com/j471n_)| [![](https://cdn-icons-png.flaticon.com/32/3178/3178285.png)](https://j471n.in)| [![](https://cdn-icons-png.flaticon.com/32/5822/5822078.png)](https://j471n.substack.com/) | [![](https://cdn-icons-png.flaticon.com/32/2935/2935413.png)](https://www.buymeacoffee.com/j471n)