DEV Community

Cover image for Building My Own Google Analytics for $0
adwait12345
adwait12345

Posted on • Originally published at adwait.me

Building My Own Google Analytics for $0

Prerequisite: You must at least have heard about GA or its use case.

If you are a developer then you would have already encountered GA or equivalent.
So without wasting anymore time im gonna waste your time by forcing you to understand how Analytics services (like Google Analytics, Posthog, Cloudflare Web Analytics, etc) actually work.

It's very simple and interesting at same time. Let's say you have a webpage which is hosted on some domain. Now if you want to track views coming on webpage, then
If I ask you how would you track (without using analytics services)?

The most common answer would be:
Add a viewCounter to page and as soon as someone lands do viewCounter++
OR
Built an endpoint to increment counter
And that's how simple it is!!
Then I thought why not build one for myself.

Reverse Engineering Google Analytics

Before writing code, I like to reverse engineer.
Let's hop some website which use GA

Ex: https://solocreators.app

As soon as we land on the page, collect request triggers.
So there is some client side Script which is being executed after we land on the page and send a request to googleAnalytics server with some payload data.

Solo

If I try to scroll down the page more collect requests happen, with payload, if i click on any button then again collect request happens.

Do you notice the pattern?

If you play around you will realize collect requests are being done on almost every event.

The Basic Architecture

So we need following components:

User's Browser
    ↓
Tracking Script (track.js)
    ↓
Backend API
    ↓
Database
    ↓
Dashboard
Enter fullscreen mode Exit fullscreen mode

If you are interested I documented the full build and architecture here:
https://www.adwait.me/writings/building-my-own-google-analytics

Top comments (0)