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](https://res.cloudinary.com/practicaldev/image/fetch/s--0hyLr1i2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663236368/zzkc2aekhw9kqjwmpvwf.jpg)
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](https://res.cloudinary.com/practicaldev/image/fetch/s--Sx6lPUNN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237321/rwuxdvcnjsd6yqvyzh2b.jpg)
Fill the details for service account and click on Create and Continue button.
![Create-Service-Account](https://res.cloudinary.com/practicaldev/image/fetch/s--7l9ViGG9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237304/efjifizmpteralwinc93.jpg)
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](https://res.cloudinary.com/practicaldev/image/fetch/s---H4Z_mUM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237330/r1ic3jcys6lfamde5foq.jpg)
Click on Create new key
![Keys-Listing](https://res.cloudinary.com/practicaldev/image/fetch/s--UkVy-Yf_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237312/fouljkdg1psizfntcynv.jpg)
Select JSON as the key type and then click on Create.
![Create-Private-Key](https://res.cloudinary.com/practicaldev/image/fetch/s--tx7jN3h9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663237293/dwp7ju1pxma0epff2b32.jpg)
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](https://res.cloudinary.com/practicaldev/image/fetch/s--iaE8yUeI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663236385/cdgnuawetpjc3jcwcvwe.jpg)
Click on Enable button to activate the API.
![Enable-Google-Analytics-API-original](https://res.cloudinary.com/practicaldev/image/fetch/s--BghWJ9cy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663236376/p4xf4yxcgmtuyshh6fjo.jpg)
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](https://res.cloudinary.com/practicaldev/image/fetch/s---EIQP0C---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663242123/a9j4m8jach1mzma9x0wb.jpg)
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](https://res.cloudinary.com/practicaldev/image/fetch/s--iEq0OAO5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663242089/u49c06kln4cmgwvnhngo.jpg)
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](https://res.cloudinary.com/practicaldev/image/fetch/s--ygWEstSr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/dvo6eiftd/image/upload/v1663242133/bjjo6qyubqo7anzpzucx.jpg)
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:
Top comments (0)