How to access google analytics from node.js?

Member

by daisha , in category: Third Party Scripts , a day ago

How to access google analytics from node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 3 hours ago

@daisha 

To access Google Analytics from Node.js, you can use the official Google APIs Node.js client library. Here's how you can do it:

  1. Install the Google APIs Node.js client library using npm:
1
npm install googleapis


  1. Authenticate with Google Analytics using OAuth2. You will need to create a new project in the Google Cloud Console and enable the Google Analytics Reporting API. Then, create OAuth2 credentials for your project and download the client secret JSON file.
  2. Create a new JavaScript file and require the necessary modules:
1
2
const { google } = require('googleapis');
const key = require('./path/to/client_secret.json'); // Path to the client secret JSON file


  1. Authenticate with Google Analytics using the key obtained from the client secret file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const jwtClient = new google.auth.JWT(
    key.client_email,
    null,
    key.private_key,
    ['https://www.googleapis.com/auth/analytics.readonly']
);

jwtClient.authorize(function(err, tokens) {
    if (err) {
        console.log(err);
        return;
    }
});


  1. Make a request to the Google Analytics Reporting API:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const analyticsReporting = google.analyticsreporting({
    version: 'v4',
    auth: jwtClient
});

analyticsReporting.reports.batchGet({
    requestBody: {
        reportRequests: [
            {
                viewId: 'YOUR_VIEW_ID',
                dateRanges: [
                    {
                        startDate: '7daysAgo',
                        endDate: 'today'
                    }
                ],
                metrics: [
                    { expression: 'ga:sessions' }
                ]
            }
        ]
    }
}, (err, res) => {
    if (err) {
        console.log('The API returned an error: ' + err);
        return;
    }
    
    console.log(res.data);
});


Replace 'YOUR_VIEW_ID' with the View ID of the Google Analytics account you want to access. You can find the View ID in the Admin section of your Google Analytics account.


By following these steps, you should be able to access Google Analytics data from Node.js using the Google APIs Node.js client library.