Interwebs.life

Analytics - the tracking pixel

analytics cdn cloudflare nginx

A CDN will reduce load on the backend server, but since traffic doesn’t hit your server we can’t get accurate analytics from the server logs. To mitigate this, we can add a tiny image to each page and tell the CDN not to cache it.

Add a tiny image to your site #

I downloaded a small transparent gif from here: The Tiniest GIF Ever · Probably Programming and placed it in the root of the site. We could just add an img tag and reference the image, but we will lose referrer information - the referrer will always be the page the image is loaded from. It would be nice to have the real referrer information. To get that, we can add the following javascript to the page template just before the end of the body tag:

    <script>
var pixel = document.createElement("img");
pixel.setAttribute("src", "/interwebs.gif?life="
+ encodeURIComponent(document.referrer));
document.body.appendChild(pixel);
</script>

This script will dynamically create the img tag and add a query string containing the document referrer.

A note on ad blockers #

Even though this is a first-party tracking pixel, ad blockers may still block this request. I have made an attempt to make sure this request does not get blocked by naming the file interwebs.gif and using life as the query string parameter since these do not appear in https://easylist.to/easylist/easyprivacy.txt (as of the time of this writing).

Bypass the cache #

We can set up a page rule in Cloudflare to bypass the cache for this request. Use the following settings for the page rule:

Make sure this is the first rule in the list, or at least ahead of any Cache Everything rules.

Clean up the logs #

We now have all the information we need in the logs, but it’s not in the correct format. I wrote a script that will transform the tracking pixel log entries so that the path and referrer get populated correctly. GitHub - iwbz-life/pixel-parser: Rewrite tracking pixel data in nginx logs Use the following command to do the transform:

docker logs blog-prod | node pixel-parser/index.js

← Home