/

Interacting with the Google Analytics API using Node.js

Interacting with the Google Analytics API using Node.js

Learn how to interface a Node.js application with the Google Analytics API by using the official googleapis package. In this blog, we will use a JSON Web Token for authentication and provide examples of API interaction.

Note: uBlock Origin blocks the images on this post because they have the word “analytics” in the path. To view the images, please disable uBlock Origin for this page.

In this blog post, we will show some examples of how to use the Google Analytics API with Node.js.

Environment variables

Once you have downloaded the JSON Key file from Google, put the client_email and private_key values as environment variables, so they can be accessed through process.env.CLIENT_EMAIL and process.env.PRIVATE_KEY.

Add the user to Google Analytics

In these examples, we are using the Service to Service API, so you need to add the client_email value to your Google Analytics profile. Go to the Admin panel and click on User Management for either a property or a view.

Google Analytics Settings

Add the email address that you found in the client_email key in the JSON file.

Add a new user

Import the Google library

To get started, import the googleapis package as follows:

1
const { google } = require('googleapis')

Remember to include the {} around the google object when importing it from the googleapis library.

Define the scope

This line sets the scope for the Google Analytics API:

1
const scopes = 'https://www.googleapis.com/auth/analytics.readonly'

Google Analytics API offers several scopes, each with different levels of access. For now, we will choose https://www.googleapis.com/auth/analytics.readonly to only view the data.

The Google Analytics Reporting API

Note: You can also use the Google Analytics Reporting API, which provides access to the same data but with a different set of methods and scope (https://www.googleapis.com/auth/analytics.readonly and https://www.googleapis.com/auth/analytics). However, we will not cover it in this blog.

Create the JWT

To create a JSON Web Token (JWT) for authentication, use the following code:

1
const jwt = new google.auth.JWT(process.env.CLIENT_EMAIL, null, process.env.PRIVATE_KEY, scopes)

Perform a request

To make a request to the Google Analytics API, use the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const view_id = 'XXXXX'

async function getData() {
const response = await jwt.authorize()
const result = await google.analytics('v3').data.ga.get({
'auth': jwt,
'ids': 'ga:' + view_id,
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:pageviews'
})

console.dir(result)
}

getData()

This code retrieves the number of pageviews in the last 30 days from the Google Analytics API using the specified view_id. You can access the pageviews count in result.data.rows[0][0].

Metrics

In addition to pageviews, there are many other metrics available in the Google Analytics API. For example:

  • ga:pageviews: Number of pageviews
  • ga:users: Number of unique users
  • ga:sessions: Number of sessions
  • ga:organicSearches: Number of organic searches

To get the number of sessions today, use the following code:

1
2
3
4
5
6
7
8
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': 'today',
'end-date': 'today',
'metrics': 'ga:sessions'
})

console.dir(result.data.rows[0][0])

To get the number of sessions from organic sources (search engines) today, add the filters property:

1
2
3
4
5
6
7
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': 'today',
'end-date': 'today',
'metrics': 'ga:sessions',
'filters': 'ga:medium==organic',
})

To get the number of sessions yesterday, use the following code:

1
2
3
4
5
6
7
8
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': 'yesterday',
'end-date': 'yesterday',
'metrics': 'ga:sessions'
})

console.dir(result.data.rows[0][0])

To get the number of sessions in the last 30 days, use the following code:

1
2
3
4
5
6
7
8
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions'
})

console.dir(result.data.rows[0][0])

To get the browsers used in the last 30 days, use the following code:

1
2
3
4
5
6
7
8
9
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': '30daysAgo',
'end-date': 'today',
'dimensions': 'ga:browser',
'metrics': 'ga:sessions'
})

console.dir(result.data.rows.sort((a, b) => b[1] - a[1]))

To get the number of visitors using the Chrome browser, use the following code:

1
2
3
4
5
6
7
8
9
10
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': '30daysAgo',
'end-date': 'today',
'dimensions': 'ga:browser',
'metrics': 'ga:sessions',
'filters': 'ga:browser==Chrome',
})

console.dir(result.data.rows[0][1])

To get the sessions by traffic source, use the following code:

1
2
3
4
5
6
7
8
9
const result = await google.analytics('v3').data.ga.get({
...defaults,
'start-date': '30daysAgo',
'end-date': 'today',
'dimensions': 'ga:source',
'metrics': 'ga:sessions'
})

console.dir(result.data.rows.sort((a, b) => b[1] - a[1]))

The Google Analytics Real Time API

The Google Analytics Real Time API is currently in private beta and is not publicly accessible. For more information, refer to the official Google Analytics Real Time API reference.

Using the googleapis package and the examples provided, you can easily interact with the Google Analytics API from your Node.js application. Now you have the tools to retrieve valuable data from your Google Analytics account.

tags: [“Google Analytics”, “Node.js”, “API”, “JSON Web Token”]