How to use Google Analytics Reporting API with Nodejs

How to use Google Analytics Reporting API with Nodejs

In this article, we will learn how to implement Google Analytics API, with a Node.js application using the official 'googleapis' npm package.

so, let's get started...

How to use Google Analytics Reporting API with Nodejs

If you prefer watching a video..

Be sure to Subscribe to the Official TutsCoder Youtube Channel for more videos.

Create New Project

Go to https://cloud.google.com/ and navigate to the console area.

Create a new Project and give an appropriate name for it, like the below:

Create-New-Project
Create-New-Project

Configure a Service Account

Once our project is created we need to set up a service account.

Select your Project from the list

Select-Your-Project
Select-Your-Project

Fill the details for service account and click on Create and Continue button.

Create-Service-Account
Create-Service-Account

Now your service account is created, then we need to create keys for it, so click on the 'Manage keys' option from the dropdown, as shown below:

View-Service-Account
View-Service-Account

Click on Create new key

Keys-Listing
Keys-Listing

Select JSON as the key type and then click on Create.

Create-Private-Key
Create-Private-Key

Enable Google Analytics API

Now Select Google Analytics API and enable it from the Marketplace menu on the left to gain further access.

Select-Google-Analytics-API
Select-Google-Analytics-API

Click on Enable button to activate the API.

Enable-Google-Analytics-API-original
Enable-Google-Analytics-API-original

Add the user to Google Analytics

You must need to include the client email value in your Google Analytics profile because we're using the Service to Service API in these examples.

Click User Management in the Admin panel by selecting a property or a view..

Click on Add users from dropdown:

Add-User
Add-User

Then Add the email you got in the JSON file's client email key as well and click on Add button.

Add-roles-and-data-restrictions-min
Add-roles-and-data-restrictions-min

Once the user is added, we also need view_id to access analytics, view_id contains the ID of the view, which You can get from the admin panel, by selecting View Settings on the view you want to access:  

Copy-View-id
Copy-View-id

Create a node js application and access Google Analytics APIs

Install googleapis package

npm i googleapis

and then Import it 

const { google } = require('googleapis')

Setup Environment variables

Now copy client_email and private_key values from the JSON key file which you have previously downloaded and put them as environment variables so that they will be accessible through process.env. option in nodejs

For accessing analytics API we need a JWT, which we can get using:

const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY.replace(/\\n/g, "\n"),
  scopes
);

Now let's see some examples:

Get Total Visitors in the Last 30 days:

const { google } = require("googleapis");

const scopes = "https://www.googleapis.com/auth/analytics.readonly";

const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY.replace(/\\n/g, "\n"),
  scopes
);
const view_id = "Your_View_ID";

async function getViews(){
  try {
    await jwt.authorize();

    const response = await google.analytics("v3").data.ga.get({
      auth: jwt,
      ids: "ga:" + view_id,
      "start-date": "30daysAgo",
      "end-date": "today",
      metrics: "ga:pageviews",
    });

    console.log(response);

  } catch (err) {
     console.log(err);
  }
};

Get the Top 10 most viewed Posts:

async function getTopPosts() {
  try {
    await jwt.authorize();

    const response = await google.analytics("v3").data.ga.get({
      auth: jwt,
      ids: "ga:" + view_id,
      "start-date": "2019-01-01",
      "end-date": "today",
      dimensions: "ga:pagePath,ga:pageTitle",
      metrics: "ga:pageviews",
      sort: "-ga:pageviews",
      "max-results": "10",
      filters: "ga:medium==organic",
    });

   console.log(response);
  } catch (err) {
   console.log(err);
  }
};

Other Resources :

Check other available options for metrics and dimensions the options:

https://ga-dev-tools.web.app/dimensions-metrics-explorer

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Comments (1)

dharmesh

There are only two columns in the Google Analytics Admin website. there is not column named of View. how can I get view ID ?

Reply

Leave a Comment