How to use Google Analytics Reporting API with Nodejs
Tags: node, howto, google, analytics
Published: 2023-02-02 10:55:35

<p class="paragraph"> In this article, we will learn how to implement&nbsp;<b>Google Analytics API</b>, with a Node.js application using the official <b>'googleapis'</b> npm package. </p><p class="paragraph"> so, let's get started... </p><h2>How to use Google Analytics Reporting API with Nodejs</h2><p class="paragraph"> <b>If you prefer watching a video..</b> </p><p class="paragraph"> Be sure to Subscribe to the <a href="https://www.youtube.com/channel/UCmObcNnWeVBlSeO_iQhsRcA">Official TutsCoder Youtube Channel</a> for more videos. </p><div class="text-center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/2qa98xBSivw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div><h3>Create New Project</h3><p class="paragraph"> Go to&nbsp;<a href="https://cloud.google.com/">https://cloud.google.com/</a>&nbsp;and navigate to the console area. </p><p class="paragraph"> Create a new Project and give an appropriate name for it, like the below: </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663236368/zzkc2aekhw9kqjwmpvwf.jpg" alt="Create-New-Project"><figcaption class="fig-cap">Create-New-Project</figcaption></figure><h2>Configure a Service Account</h2><p class="paragraph"> Once our project is created we need to set up a service account. </p><p class="paragraph"> Select your Project from the list </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237321/rwuxdvcnjsd6yqvyzh2b.jpg" alt="Select-Your-Project"><figcaption class="fig-cap">Select-Your-Project</figcaption></figure><p class="paragraph"> Fill the details for service account and click on Create and Continue button. </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237304/efjifizmpteralwinc93.jpg" alt="Create-Service-Account"><figcaption class="fig-cap">Create-Service-Account</figcaption></figure><p class="paragraph"> Now your service account is created, then we need to create keys for it, so click on the <b>'Manage keys'</b> option from the dropdown, as shown below: </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237330/r1ic3jcys6lfamde5foq.jpg" alt="View-Service-Account"><figcaption class="fig-cap">View-Service-Account</figcaption></figure><p class="paragraph"> Click on Create new key </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237312/fouljkdg1psizfntcynv.jpg" alt="Keys-Listing"><figcaption class="fig-cap">Keys-Listing</figcaption></figure><p class="paragraph"> Select <b>JSON</b> as the key type and then click on Create. </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237293/dwp7ju1pxma0epff2b32.jpg" alt="Create-Private-Key"><figcaption class="fig-cap">Create-Private-Key</figcaption></figure><h2>Enable Google Analytics API</h2><p class="paragraph"> Now Select Google Analytics API and enable it from the Marketplace menu on the left to gain further access. </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663236385/cdgnuawetpjc3jcwcvwe.jpg" alt="Select-Google-Analytics-API"><figcaption class="fig-cap">Select-Google-Analytics-API</figcaption></figure><p class="paragraph"> Click on <b>Enable</b> button to activate the API. </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663236376/p4xf4yxcgmtuyshh6fjo.jpg" alt="Enable-Google-Analytics-API-original"><figcaption class="fig-cap">Enable-Google-Analytics-API-original</figcaption></figure><h2>Add the user to Google Analytics</h2><p class="paragraph"> You must need to include the <b>client email value</b> in your Google Analytics profile because we're using the Service to Service API in these examples.  </p><p class="paragraph"> Click User Management in the Admin panel by selecting a property or a view.. </p><p class="paragraph"> Click on Add users from dropdown: </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663242123/a9j4m8jach1mzma9x0wb.jpg" alt="Add-User"><figcaption class="fig-cap">Add-User</figcaption></figure><p class="paragraph"> Then Add the email you got in the JSON file's client email key as well and click on Add button. </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663242089/u49c06kln4cmgwvnhngo.jpg" alt="Add-roles-and-data-restrictions-min"><figcaption class="fig-cap">Add-roles-and-data-restrictions-min</figcaption></figure><p class="paragraph"> Once the user is added, we also need view_id to access analytics,&nbsp;<code>view_id</code>&nbsp;contains the ID of the&nbsp;view, which You can get from the admin panel, by selecting View Settings&nbsp;on the view you want to access:&nbsp;&nbsp; </p><figure class="fig-img"><img class="img   " src="https://res.cloudinary.com/dvo6eiftd/image/upload/v1663242133/bjjo6qyubqo7anzpzucx.jpg" alt="Copy-View-id"><figcaption class="fig-cap">Copy-View-id</figcaption></figure><h2>Create a node js application and access Google Analytics APIs</h2><p class="paragraph"> Install&nbsp;googleapis package </p><pre><code class="code-block">npm i googleapis</code></pre><p class="paragraph"> and then Import it&nbsp; </p><pre><code class="code-block">const { google } = require('googleapis')</code></pre><h2>Setup Environment variables</h2><p class="paragraph"> Now copy&nbsp;<code>client_email</code>&nbsp;and&nbsp;<code>private_key</code>&nbsp;values from the JSON key file which you have previously downloaded and put them as environment variables so that they will be accessible through&nbsp;<code class="inline-code">process.env.</code> option in nodejs </p><p class="paragraph"> For accessing analytics API we need a JWT, which we can get using: </p><pre><code class="code-block">const jwt = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  null,
  process.env.PRIVATE_KEY.replace(/\\n/g, "\n"),
  scopes
);</code></pre><p class="paragraph"> Now let's see some examples: </p><p class="paragraph"> Get Total Visitors in the Last 30 days: </p><pre><code class="code-block">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);
  }
};</code></pre><p class="paragraph"> Get the Top 10 most viewed Posts: </p><pre><code class="code-block">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);
  }
};</code></pre><p class="paragraph"> <b>Other Resources :</b> </p><p class="paragraph"> Check other available options for metrics and dimensions the options: </p><p class="paragraph"> <a href="https://ga-dev-tools.web.app/dimensions-metrics-explorer">https://ga-dev-tools.web.app/dimensions-metrics-explorer</a> </p>