@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
|
npm install googleapis |
1 2 |
const { google } = require('googleapis'); const key = require('./path/to/client_secret.json'); // Path to the client secret JSON 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 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.