Use Node.js to interact with Google Analytics API

Learn how to use the official Node.js application to interface with Google Analytics APIgoogleapispackage. We will use JSON Web Token and see some examples

Note: uBlock Origin blocked the images on this post because they haveanalyticsThe word in the path. So please make sure to disable it on this page to view the images🖼

In this article, I will show some of the Google Analytics API andNode.js.

Google provides a great npm package:googleapis. We will use it as the basis for API interaction.

Authentication is an important part of interacting with API. View this post onHow to authenticate with Google API. In this article, I assume that you have read the book and you know how to performJWTverification.

Environment variable

Finished downloadingJSON formatThe key file from Google willclient_emailwithprivate_keyValues as environment variables so that they can be accessed in the following ways

  • process.env.CLIENT_EMAIL
  • process.env.PRIVATE_KEY

Add users to Google Analytics

Since the Service to Service API is used in these examples, you need to addclient_emailThe value of your Google Analytics profile. Go to the admin panel and clickUser Management, Whether it is on the properties or on the view.

Google Analytics Settings

And add you inclient_emailType the JSON file:

Add a new user

Import Google library

const { google } = require('googleapis')

remember{}aroundgoogleObject because we need to remove it fromgoogleapisLibrary (otherwise we need to callgoogle.googleAnd it's ugly)

Define the scope

This line sets the range:

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

The Google Analytics API defines several scopes:

  • https://www.googleapis.com/auth/analytics.readonlyView data
  • https://www.googleapis.com/auth/analyticsView and manage data
  • https://www.googleapis.com/auth/analytics.editEdit management entity
  • https://www.googleapis.com/auth/analytics.manage.usersManage account users and permissions
  • https://www.googleapis.com/auth/analytics.manage.users.readonlyView users and their permissions
  • https://www.googleapis.com/auth/analytics.provisionCreate a new Google Analytics account

You should always choose an oscilloscope that can provide the least amount of power.

Since we only want to view the report right now, choosehttps://www.googleapis.com/auth/analytics.readonlyinsteadhttps://www.googleapis.com/auth/analytics.

Google Analytics Reporting API

Note: You can also useGoogle Analytics Reporting APIAccess these permissions.

It is a streamlined version of the Google Analytics API and only provides scopehttps://www.googleapis.com/auth/analytics.readonlywithhttps://www.googleapis.com/auth/analytics.

The API is slightly different from the Analytics API, but the usage and public methods are different, so we will skip it.

Create JWT

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

Execute request

Check this code:

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, scopes)

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()

It executes a request to the Google Analytics API to obtainPageviews in the last 30 days.

view_idIncluded IDview. Not your Google Analytics code, but the view ID. You can clickView settingsOn the view you want to access:

The view id

You pass this object to the request:

{
  'auth': jwt,
  'ids': 'ga:' + view_id,
  'start-date': '30daysAgo',
  'end-date': 'today',
  'metrics': 'ga:pageviews'
}

In addition to the jwt object and the view ID, we also have 3 parameters.

  • metrics: Tell the APIWhat we want
  • start-date: Define the start date of the report
  • end-date: Define the end date of the report

The request is very simple, it returns the number of pageviews that occurred during the specified time period.

The returned result will be similar to:

{
  status: 200,
  statusText: 'OK',
  headers: {...},
  config: {...},
  request: {...},
  data: {
    kind: 'analytics#gaData',
    id: 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:XXXXXXXXXXXXXXXXXX&metrics=ga:pageviews&start-date=30daysAgo&end-date=today',
    query:  {
      'start-date': '30daysAgo',
      'end-date': 'today',
      ids: 'ga:XXXXXXXXXXXXXXXXXX',
      metrics: [ 'ga:pageviews' ],
      'start-index': 1,
      'max-results': 1000
    },
    itemsPerPage: 1000,
    totalResults: 1,
    selfLink: 'https://www.googleapis.com/analytics/v3/data/ga?ids=ga:XXXXXXXXXXXXXXXXXX&metrics=ga:pageviews&start-date=30daysAgo&end-date=today',
    profileInfo: {
      profileId: 'XXXXXXXXXXXXXXXXXX',
      accountId: 'XXXXXXXXXXXXXXXXXX',
      webPropertyId: 'UA-XXXXXXXXXXX--XX',
      internalWebPropertyId: 'XXXXXXXXXXXXXXXXXX',
      profileName: 'XXXXXXXXXXXXXXXXXX',
      tableId: 'ga:XXXXXXXXXXXXXXXXXX'
    },
    containsSampledData: false,
    columnHeaders: [
      {
        name: 'ga:pageviews',
        columnType: 'METRIC',
        dataType: 'INTEGER'
      }
    ],
    totalsForAllResults: { 'ga:pageviews': '3000' },
    rows: [ [ '114426' ] ] }
}

With this, you can access pageviewsresponse.data.rows[0][0].

index

This example is very simple. We just ask for the following data:

{
  'start-date': '30daysAgo',
  'end-date': 'today',
  'metrics': 'ga:pageviews'
}

We can use a lot of data.

ThisDimensions and metrics browserIt is a great tool to discover all the options.

These terms are two concepts of Google Analytics.

aspectIs the attribute, such as "city", "country/region" or "page", referral path or session length.

indexIt is a quantitative measure, such as the number of users or the number of sessions.

Some examples of indicators:

  • Get pageviewsga:pageviews
  • Get unique usersga:users
  • Get a meetingga:sessions
  • Get natural searchga:organicSearches

Let's build some examples using these indicators.

Generic code

This is the generic code used in the example below. Put the code snippet intoauthorize()call back.

'use strict'

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, scopes)

async function getData() { const defaults = { ‘auth’: jwt, ‘ids’: ‘ga:’ + process.env.VIEW_ID, } const response = await jwt.authorize()

/* custom code goes here, using response */ }

getData()

The default object will be used in the exampleSpread operator, Which is a convenient way to handle default values in JavaScript.

Get the number of meetings today

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])

Get the number of today's sessions from natural resources (search engine)

Add tofiltersproperty:

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

Get the number of meetings yesterday

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])

Get the number of sessions in the last 30 days

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])

Get the browsers used in the last 30 days

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]))

[
[ ‘Chrome’, ‘994’ ],
[ ‘Safari’, ‘548’ ],
[ ‘Firefox’, ‘442’ ],
[ ‘Android Webview’, ‘113’ ],
[ ‘Opera’, ‘56’ ],
[ ‘Safari (in-app)’, ‘41’ ],
[ ‘Edge’, ‘36’ ],
[ ‘Internet Explorer’, ‘4’ ]
]

Get the number of visitors using the Chrome browser

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])

Get sessions by traffic source

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]))

[
[ ‘google’, ‘1343’ ],
[ ‘(direct)’, ‘731’ ],
[ medium.com, ‘624’ ],
[ t.co, ‘987’ ],
[ reddit.com, ‘65’ ]
]

Google Analytics real-time API

The Google Analytics real-time API was released in [beta] in May 2018 and is not publicly accessible.Check this page.

Download mine for freeNode.js manual


More node tutorials: