Last updated Sep 15, 2022

How to use Google Analytics Reporting API with Nodejs

Generate powerful reports using Google Analytics API.

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:

Configure a Service Account

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

Select your Project from the list

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

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:

Click on Create new key

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

Enable Google Analytics API

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

Click on Enable button to activate the API.

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:

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

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:  

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

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

Comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

Loading comments…

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.