DEV Community

Rick Delpo
Rick Delpo

Posted on • Updated on • Originally published at javasqlweb.org

Removing Google Analytics and Replacing it with a cookie free Javascript Geo Tracking app

Running Google Analytics slows down site performance because adding any script to our html head tag adds overhead to our app. This includes any third party libraries also added to the head tag.

I found a free jsonp geolocation api, pulled country, city and ip variables into my javascript, then passed these vars into a Lambda function and saved them as a json file to a simple AWS S3 bucket. This way I could avoid adding the google analytics to my head tag, thereby speeding up my performance a bit. I included the following code just before my end body tag.

<script type="text/javascript" src="https://ipinfo.io/json?callback=myCallback">

</script>
Enter fullscreen mode Exit fullscreen mode

then my callback function looks like this

 function myCallback(post){
session = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); //added 11-11 default session 

pg_name="whatever ur page name is";                  
country = post.country;
city =post.city;
ip_address = post.ip;

passVars(); //first run start script then run passvars javascript function to  pass vars to Lambda


        }  //end myCallback
Enter fullscreen mode Exit fullscreen mode

my passvars javascript function looks like this..note we fetch Lambda inside this function

function passVars() {

var date = new Date().toLocaleDateString('en-US');
var now = new Date().toLocaleTimeString();
var out = new Date().toLocaleTimeString();

   //then pass 5 objects... ses, hit2 etc to lambda and call event.ses inside lambda..note, this object must be called article
const article = { ses: session, city2: city, hit2: date, page:pg_name, ip2:ip_address,country2:country, time2:now, time3:out };
    //call Lambda function here, this next line is the AWS api gateway call to the Lambda function
fetch("https://xxxx.execute-api.us-east-2.amazonaws.com/default/saveS3", {

    method: "POST",
    // Adding body or contents to send
    body: JSON.stringify(article),
    // Adding headers to the request
    headers: {
        "Content-type": "application/json; charset=UTF-8"
    }
})

}
Enter fullscreen mode Exit fullscreen mode

my Lambda function looks like this

NOTE as of 2023 below code does not work in Node18 because aws-sdk library is no longer native and requires a deployment pkg. But Node 16 still works for below code

const AWS = require('aws-sdk');
const fetch = require('node-fetch');
const s3 = new AWS.S3();

exports.handler = async (event) => {
       //first fetch ur current json file from s3 bucket
//this handler function uses an event argument to pass data to json file saved in s3 bucket
  const res = await fetch('https://xxxx.s3.us-east-2.amazonaws.com/tracker2.json');
  const json = await res.json();

  // then add a new record
        json.push({
          // get geo data from javascript, then pass geo variables into the event object
            country: event.country2,
            session: event.ses,
            page_name: event.page,
            hit: event.hit2,
            ip: event.ip2,
            time_in: event.time2,
            time_out: event.time3,
            event_name: event.city2

        });


   //then re write the whole updated file back to s3 and it will overwrite existing json file, this is our only way of appending json data. It is similar to an SQL insert command

  var params = {
      Bucket: 'xxxx',
         Key: 'tracker2.json',
         Body: JSON.stringify(json), //pass fetch result into body with update from push
         ContentType: 'json',
   };

   var s3Response = await s3.upload(params).promise();

};
Enter fullscreen mode Exit fullscreen mode

My AWS S3 json file looks like this

[{"country":"Philippines","session":"j4w9nq38x4nl8v1fxy3ja","page_name":"Learn Java","hit":"11/22/2021","ip":"175.176.55.14","time_in":"7:52:35 PM","time_out":"7:52:35 PM"},{"country":"United States","session":"n0ja7c6z2vlec6tn7bd","page_name":"Learn Java","hit":"11/22/2021","ip":"66.249.66.130","time_in":"7:04:57 AM","time_out":"7:04:57 AM"}]

Enter fullscreen mode Exit fullscreen mode

After passing variables to my S3 json file I can then render the result to html.

see the SQL section of my website at
https://javasqlweb.org
for more

Also added some listeners to record time spent on page. Just view sourcecode at my site for this

Happy coding folks!

Top comments (7)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Cool post about an alternative to Google Analytics ✨👍🏼

Also, don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
rickdelpo1 profile image
Rick Delpo

Thanks for the advice, I never new how to do colors on codeblock, Looks much nicer this way

Collapse
 
leober_ramos33 profile image
Leober Ramos

It is good for sites that do not exceed the free quota that IPinfo gives you. And for sites that do not require more complex analytics, just knowing where the visits come from and to which page. In addition to the fact that it would be necessary to build a Frontend to read that data.

But to avoid all that, and pay for the IPinfo service, it is better to use open source alternatives to Google Analytics such as Plausible or Matomo.

Collapse
 
rickdelpo1 profile image
Rick Delpo • Edited

Hey thanks for ur response. My code is just for experimental use and not commercial use. It is designed to give my students a start at javascript coding then they can become creative and add more features.

yes IPInfo provides a very generous free tier option of 50000 hits per month. I am lucky to get only 1000 per month, so for the small user we are just testing.

Also I did build a small javascript front end, see my post at
javasqlweb.org/SQL/to-SQL-or-to-No...

a few pointers on why we test Google Analytics

1 when gdpr announced cookie notice a few years ago I noticed that Google Analytics put a cookie on my pc, so I experimented with creating my own javascripted session object with no cookie.

2 Also many of my website pages are meant for only one view so GA will consider this a bounce, so I added a listener to record when the user would leave my page. It is very interesting because my session duration is way higher because user may spend several minutes reading one of my pieces where GA considers it a bounce if user does not connect to another page so will show 0 minutes for session duration.

3 Also many users block Google Analytics. For example in the past 2 days GA showed that I had 11 visitors whereas my program showed 15 visitors. This means that 27% are blocking GA in this small sample. Reason for this is because user blocks GA but does not turn off javascript so my program registers a session.

I hope u found this useful, thanks for reading

Collapse
 
reincoder profile image
Reincoder

Awesome article. I work for IPinfo, so couple of notes :)

  • Feel free to sign up to IPinfo or you are going to get rate limited. The free tier is pretty generous, so check it out.
  • If you are using the token, you should use the service in the backend, but if not no worries use the whitelist domains feature from the dashboard.
Collapse
 
rickdelpo1 profile image
Rick Delpo • Edited

Hey thanks so much for providing ur free tier option. We are only a very small test site with a number of students experimenting with Javascript. You are providing an excellent service, Thanks from me and my students !!

Collapse
 
reincoder profile image
Reincoder

That is incredible to hear @rickdelpo1 😄. Thank you very much!! Please feel free to reach out to me anytime if you have any feedback, queries or suggestions!

twitter.com/reincdr