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:
Top comments (0)