Learn how to use the official Node.js application to interface with Google Analytics APIgoogleapis
package. We will use JSON Web Token and see some examples
Note: uBlock Origin blocked the images on this post because they have
analytics
The 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.
- Environment variable
- Add users to Google Analytics
- Import Google library
- Define the scope
- Google Analytics Reporting API
- Create JWT
- Execute request
- index
- Generic code
- Get the number of meetings today
- Get the number of today's sessions from natural resources (search engine)
- Get the number of meetings yesterday
- Get the number of sessions in the last 30 days
- Get the browsers used in the last 30 days
- Get the number of visitors using the Chrome browser
- Get sessions by traffic source
- Google Analytics real-time API
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_email
withprivate_key
Values 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_email
The value of your Google Analytics profile. Go to the admin panel and clickUser Management, Whether it is on the properties or on the view.
And add you inclient_email
Type the JSON file:
Import Google library
const { google } = require('googleapis')
remember{}
aroundgoogle
Object because we need to remove it fromgoogleapis
Library (otherwise we need to callgoogle.google
And 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.readonly
View datahttps://www.googleapis.com/auth/analytics
View and manage datahttps://www.googleapis.com/auth/analytics.edit
Edit management entityhttps://www.googleapis.com/auth/analytics.manage.users
Manage account users and permissionshttps://www.googleapis.com/auth/analytics.manage.users.readonly
View users and their permissionshttps://www.googleapis.com/auth/analytics.provision
Create 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.readonly
insteadhttps://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.readonly
withhttps://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_id
Included IDview. Not your Google Analytics code, but the view ID. You can clickView settingsOn the view you want to access:
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 wantstart-date
: Define the start date of the reportend-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 pageviews
ga:pageviews
- Get unique users
ga:users
- Get a meeting
ga:sessions
- Get natural search
ga: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 tofilters
property:
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:
- Introduction to npm package manager
- Introduction to Node.js
- HTTP request using Axios
- Where to host Node.js applications
- Use Node.js to interact with Google Analytics API
- npx node package runner
- package.json guide
- Where does npm install packages?
- How to update Node.js
- How to use or execute packages installed with npm
- package-lock.json file
- Semantic version control using npm
- Should you submit the node_modules folder to Git?
- Update all Node dependencies to the latest version
- Use Node.js to parse JSON
- Find the installed version of the npm package
- Node.js flow
- Install an older version of the npm package
- Get the current folder in Node
- How to record objects in Node
- Use export to expose functions from Node files
- Difference between node and browser
- Use Node to make HTTP POST requests
- Use Node to get HTTP request body data
- Node buffer
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use Node.js REPL
- Node, accepts parameters from the command line
- Use Node to output to the command line
- Accept input from the command line in Node
- Use `npm uninstall` to uninstall the npm package.
- npm global or local package
- npm dependencies and devDependencies
- Node.js event loop
- Understanding process.nextTick()
- Understanding setImmediate()
- Node event emitter
- Set up an HTTP server
- Use Node to make HTTP requests
- Node fs module
- HTTP request in Node using Axios
- Use Node to read files
- Node file path
- Write file with Node
- Node file statistics
- Use file descriptors in Node
- Use folders in Node
- Node path module
- Node http module
- Combine WebSockets with Node.js
- Basic knowledge of using MySQL and Node
- Error handling in Node.js
- Pug Guide
- How to read environment variables from Node.js
- How to exit from Node.js program
- Node os module
- Node event module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to delete files using Node.js
- How to get the last update date of a file using Node.js
- How to determine whether the date is today in JavaScript
- How to write a JSON object to a file in Node.js
- Why use Node.js in the next project?
- Run web server from any folder
- How to use MongoDB with Node.js
- Use Chrome DevTools to debug Node.js applications
- What is pnpm?
- Node.js runtime v8 options list
- How to solve the "missing write access permission" error when using npm
- How to enable ES modules in Node.js
- How to use Node.js to generate child processes
- How to get the parsed body and the original body at the same time in Express
- How to handle file upload in Node.js
- What is the peer dependency in the node module?
- How to write a CSV file using Node.js
- How to use Node.js to read CSV files
- Node core module
- Use Node.js to increase the number of multiple folders at once
- How to print canvas to data URL
- How to create and save images using Node.js and Canvas
- How to download images using Node.js
- How to batch rename files in Node.js
- How to get the names of all files in a folder in Node
- How to use promise and wait function based on Node.js callback
- How to test NPM packages locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Use Node.js to serve HTML pages
- How to solve the error that util.pump in Node.js is not a function