How To Use Google Analytics Api In Javascript

Google Analytics is a crucial resource for all web developers aiming to comprehend the actions of users on their website. By utilizing the Google Analytics API, you can elevate your data analysis. This guide will walk you through the process of incorporating this API with JavaScript.

Step 1: Create a Google Analytics Account

Before you can utilize the Google Analytics API, you need a Google Analytics account. You can sign up for one at Google Analytics. Once you have an account, you’ll need to add your website as a property within your account.

Step 2: Setup the Google Analytics Reporting API

You’ll also need to set up the Google Analytics Reporting API. To do this, visit the Google Developers Console and create a new project. Enable the Google Analytics Reporting API for this project and create credentials that your application will use to access the API.

Step 3: Initialize Google Analytics in your JavaScript Code

With your API credentials, you can now initialize Google Analytics within your JavaScript code. Here’s how:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');

Replace ‘UA-XXXXXXXX-X’ with your Tracking ID which can be found in your Google Analytics account.

Step 4: Fetching Data with the Google Analytics API

You can fetch data from the Google Analytics API using the analytics.reports.batchGet function. This function requires a REPORT_REQUEST object, which specifies the view ID and the date ranges, metrics, and dimensions for the report.

Here is an example of how to use this function:

let reportRequest = {
    viewId: 'ga:XXXXXXXX',
    dateRanges: [
        { startDate: '2021-01-01', endDate: '2021-12-31' }
    ],
    metrics: [
        { expression: 'ga:sessions' }
    ],
    dimensions: [
        { name: 'ga:country' }
    ]
};

gapi.client.analyticsreporting.reports.batchGet({
    reportRequests: [reportRequest]
}).then(response => {
    let reports = response.result.reports;
    // Handle the reports.
}).catch(err => {
    console.log(err);
});

Don’t forget to replace ‘ga:XXXXXXXX’ with your own view ID from your Google Analytics account.

Conclusion

That’s just the basics of using the Google Analytics API in JavaScript. The API provides a lot more functionality that you can explore to help understand your website’s users and their behaviors. Happy coding!