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:

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

    reportRequests: [reportRequest]
}).then(response => {
    let reports = response.result.reports;
    // Handle the reports.
}).catch(err => {

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


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!