When someone asks about Tracking web pages for analysis, generally Google Analytics product by Google comes up first in your mind, Right?

Google Analytics collects data about your web presence from various sources.

There are three primary sources of this data:

  1. User activities on your website or app
  2. Any CRM and external data sources you provided to Google Analytics
  3. The demographic information collected by Google about users visiting your website

Then, based on the configurations of your Google Analytics account (either through the Management API or User Interface), Google Analytics processes the data and convert those data into a format that is ready for analysis.

 Anyone can use it to track and report the traffic on their website.

In this article, we are going to see how with use of Google Analytics Data API  we can fetch data from Google Analytics in the simplest way.

Should I use Google Analytics with Angular?

Google Analytics is without doubt the most powerful and popular analytics tool that can be used for free. You can monitor all kinds of metrics like page views, sessions, bounces, visits and user engagement. It allows you to easily see how users are interacting with your website or application and make wiser marketing and business choices.

It was originally created for static websites and wasn’t designed for single page applications created with Angular (or other web libraries and frameworks). This makes it a bit trickier to add Google Analytics to an Angular application but it is doable and really not that hard.

If you want to discover how users are interacting with an Angular application then Google Analytics is definitely the cheapest, easiest and quickest way to get started.

Disadvantages of using Google Analytics with Angular

One of the biggest disadvantages of using Google Analytics is privacy.

PS: remember also that most users that care about privacy have already installed firewalls and browser extensions to block Google Analytics.

How do you use Google Analytics with Angular?

When integrating Google Analytics into our Angular application we have two options.

  • Use a 3rd party library built by the open-source community.
  • Create our own Angular service that communicates with our Google Analytics account.

Obviously, the first choice is the easiest and quickest way to use Google Analytics with Angular. But it might not offer the customization and tracking that we need. In that case we’ll need to create our own service that communicates with the Google Analytics services.

Google Analytics Setup

Go to the  Google Analytics home page and create your account.

If you already have an account then you can sign in instead.

Next we’ll have to create a new property.

Give your new property a name and properly configure the other options.

Answer the business information questions and then click create.

Then select your platform. In this case it will be Web.

Now you’ll need to specify the URL of your website as well as the name of the new data stream (the data coming in from your Angular application to Google Analytics).

This should take you to a page that displays the new web stream details. The MEASUREMENT ID is important and we’ll need it for the next step.

how to add Google Analytics to Angular application?

Alternative 1

The first step is to install the ngx-google-analytics package.

npm install --save ngx-google-analytics

Once installed, you’ll need to import it into your app.module.ts file like this.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxGoogleAnalyticsModule } from 'ngx-google-analytics';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    NavBarComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxGoogleAnalyticsModule.forRoot('MEASUREMENT-ID')
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Run your Angular application and you should see a new user show up in the Google Analytics real-time report.

There’s a problem though. ?

With the current configuration the Google Analytics package for Angular is not sending the various page views to the analytics service. This means that as a user navigates your Angular application you won’t be able to see what pages they’re navigating to.

To fix this all we have to do is import the NgxGoogleAnalyticsRouterModule module. Like this.

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxGoogleAnalyticsModule, NgxGoogleAnalyticsRouterModule } from 'ngx-google-analytics';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavBarComponent } from './core/nav-bar/nav-bar.component';

@NgModule({
  declarations: [
    AppComponent,
    NavBarComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    NgxGoogleAnalyticsModule.forRoot('MEASUREMENT-ID'),
    NgxGoogleAnalyticsRouterModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

PS: You can learn more about this package and all of it’s options, by reading the documentation here

Alternative 2

The first step is to go into the settings for your Google Analytics property and find the Global site tag.

You want to copy the global site tag into the head of your index.html file.

It should look sorta like this.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Application</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT-ID"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'MEASUREMENT-ID');
  </script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

This is a good start but again there is a problem. We’re not quite finished because Google Analytics is not notified when we route to a page inside our SPA.

To fix that, we’ll subscribe to the Angular router inside the app.component.ts file and send the new routes to Google Analytics.

import { Component } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';

declare const gtag: Function;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(public router: Router) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        gtag('config', 'MEASUREMENT-ID', { 'page_path': event.urlAfterRedirects });
      }      
    })
  }
}

That^s it. We’ve installed Google Analytics and are now sending page views to the Google Analytics servers.

How to use Google Analytics Data API?

Requirements

We need three values to fetch the data:

  • GA_PROPERTY_ID
  • GA_CLIENT_EMAIL
  • GA_PRIVATE_KEY
GA_PROPERTY_ID

First, you need to get GA_PROPERTY_ID of the Google Analytics project from which you want to fetch the data.

To get this you need to follow these steps:

  • Visit Google Analytics.
  • Select Admin.
  • Select the Property.
  • Select Property Setting
This image has an empty alt attribute; its file name is image.png

GA_CLIENT_EMAIL and GA_PRIVATE_KEY

To get GA_CLIENT_EMAIL and GA_PRIVATE_KEY you need to visit Google Analytics Data API’s documentation and then click on Enable the Google Analytics Data API v1 button as shown in the image below:

And then you will be prompted to enter the name of the project. After entering the name click on the Next button

Then you will be prompted to download the credential file as JSON.

After downloading that file. You will find private_key and client_email properties in that JSON file. Save these two in your .env.local.

Now you have all the necessary information or keys.

Installing Dependency

To fetch the data you need to install a @google-analytics/data package. You can do that by simply running the following command in the terminal.

npm i @google-analytics/data

Using Google Analytics Data API in Project

Let assume we are using Next.js, so we will use Next.js API Routes

Let”s create an API route pages/api/ga.ts:

import { NextApiRequest, NextApiResponse } from "next";
import { BetaAnalyticsDataClient } from "@google-analytics/data";

// ? Setting PropertyId
const propertyId = process.env.GA_PROPERTY_ID;

const analyticsDataClient = new BetaAnalyticsDataClient({
  credentials: {
    client_email: process.env.GA_CLIENT_EMAIL,
    private_key: process.env.GA_PRIVATE_KEY?.replace(/\n/gm, "\n"), // replacing is necessary
  },
});

export default async function handler(
  _req: NextApiRequest,
  res: NextApiResponse
) {
  // ? Running a simple report
  const [response] = await analyticsDataClient.runReport({
    property: `properties/${propertyId}`,
    dateRanges: [
      {
        startDate: `7daysAgo`, //?  e.g. "7daysAgo" or "30daysAgo"
        endDate: "today",
      },
    ],
    dimensions: [
      {
        name: "year", // data will be year wise
      },
    ],
    metrics: [
      {
        name: "activeUsers", // it returs the active users
      },
    ],
  });

  // Returning the respose.
  return res.status(200).json({
    response,
  });
}

This is all you need to fetch the data. and It will return the response.

PS: You can do the same thing with different frameworks.

Reference:

https://danielk.tech/

https://dev.to/j471n/how-to-use-google-analytics-data-api-2133

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *