How to get data from google analytics in node.js?

by laverna_hirthe , in category: SEO Tools , 2 months ago

How to get data from google analytics in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by dudley , 2 months ago

@laverna_hirthe 

To get data from Google Analytics in Node.js, you can use the Google APIs Node.js client library. Here is a step-by-step guide on how to do it:

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


  1. Create a new project in the Google API Console and enable the Google Analytics API.
  2. Generate OAuth 2.0 credentials for your project and download the client_secret.json file.
  3. Write the following code to authenticate and make a request to the Google Analytics 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
31
32
33
34
35
const { google } = require('googleapis');
const key = require('./client_secret.json');

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;
  }

  const analytics = google.analytics('v3');
  analytics.data.ga.get(
    {
      auth: jwtClient,
      ids: 'ga:YOUR_VIEW_ID',
      'start-date': '7daysAgo',
      'end-date': 'today',
      metrics: 'ga:sessions',
    },
    function (err, response) {
      if (err) {
        console.log('API returned an error: ' + err);
        return;
      }

      console.log(response.data.rows);
    },
  );
});


Replace 'YOUR_VIEW_ID' with the ID of the Google Analytics view you want to query.

  1. Run the script and you should see the data retrieved from Google Analytics in the console.


This is just a basic example of how to get data from Google Analytics in Node.js. Depending on your requirements, you may need to modify the code to retrieve different metrics or dimensions. You can refer to the Google Analytics API documentation for more information on available parameters and methods.