You launch a new website or app, and the first thing you do is slap on Google Analytics (or any other analytics service) to start "tracking users." Well, we call it just "statistics," right? Yeah, that sounds way less dystopian. It's become almost a reflex at this point.
I'm here to present the point that there's a better and simple alternative. If you're a freelance developer or a studio, keep reading.
Don't get me wrong - Google Analytics has its place. In certain industries, it's considered the standard for comparing stats and selling partner positions. But for most websites and apps, it's just free. Sure, it's fun to see where people come from and what their age groups are, but does that information genuinely help you improve your project? I argue not.
The Issues with Heavy (Default or Standard) Analytics Services
Before we dive into the alternative, let's talk about some of the problems that come with using these comprehensive analytics tools, to show you my reasons for removing them as much as possible and figuring out our own solution.
Privacy Regulations and Consents
With the rise of privacy regulations like GDPR in Europe, you can't just load up an analytics script without the user's explicit consent (Maps, too, actually). This means implementing cookie consent banners and dealing with users potentially opting out - resulting in you getting no data at all from those users.
Don't forget - you need the consent screens not based on where you live, but based on your user's location. You may host your website in India or Canada, but as long as an EU citizen visits your website, you need to have a consent screen - annoying for you as a developer and everyone else, but pretty much necessary for each and every website.
And BTW - I noticed many developers thing the analytics provider is responsible for handling data, consents etc…. guess again. No, it’s on you as the one owning the website or app.
Reliance on Third-Party Scripts
Loading third-party scripts introduces several issues:
- Performance Hits: These scripts can slow down your website, negating any optimization efforts you've made. "But GTM and GA are fast" - no, they often are not. Trust me, we've dealt with a lot of crap from those.
- Blocking and Filtering: Users with ad blockers or script blockers might prevent these analytics scripts from loading altogether, and you get no stats at all (and there will be a lot more of those as time goes on).
- Data Control: You're sending your user data to a third party, which is increasingly considered shady and shitty.
Do You Really Need All That Data?
Let's face it - most projects don't need the exhaustive data that services like Google Analytics provide (many of us don't even understand them and misinterpret them, me included). Detailed demographic information might be fun to watch, but unless you're tailoring content or ads based on that, it's not particularly useful.
What do you actually need to know?
- How many people are visiting your site
- Which pages are they visiting
- Basic engagement metrics like time spent on a page - and this is debatable
Anything beyond that is often unnecessary for small to medium projects.
A Simple, Homemade Solution - But Perfect for You
So, what's the alternative? Build your own lightweight analytics system. Don't worry; it's way easier than it sounds.
I'll be talking about websites with server-side PHP, but the same principles apply for mobile apps and other languages.
The Basic Idea
- On the Client Side: After the website loads, run a simple JavaScript script that sends the current URL to your server via AJAX.
- On the Server Side: Capture this data and store it in a database table along with the current timestamp.
That's it. You've got basic analytics up and running. It actually takes you 10 minutes.
OK, alright, I admit, it's another 10 minutes for making it reusable.
I hate throwing numbers, your setup is different then hours. But I promise you, it’s very easy.
Why This Works
- No Privacy Issues: You're not collecting personal data, so privacy regulations like GDPR are not of your concern.
- No Third-Party Dependencies: Everything runs on your server, so there's no risk of scripts being blocked.
- Minimal Performance Impact: The scripts are lightweight and won't slow down your site.
- No Cookies = No Annoying Consents
Extending the Functionality - Later, as You Need It
If you need more than basic stats, you can gradually extend your system.
Collect Additional Data
- IP Address and User Agent: Store these to analyze geographic distribution and browser usage - extremely simple to implement.
- Page Engagement: Log time spent on pages - keep an ID of the database record in JavaScript and send it along with the spent time after the user exits the page.
- Session Tracking: Use cookies (after obtaining consent) to track returning users and session durations (page-stand duration is easier and without cookies).
Data Processing
- Scheduled Tasks: Set up cron jobs or scheduled tasks to process and summarize your data.
- Aggregated Reports: Generate reports based on days, months, hours, or even minutes if needed.
Code Examples
Let's just get you started - you can see it's actually simple to start.
Client-Side JavaScript (Vanilla JS)
<!-- Place this script before the closing </body> tag -->
<script>
(function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/track.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('url=' + encodeURIComponent(window.location.href));
})();
</script>
Server-Side PHP (track.php
)
<?php
// Get the URL from the POST request
$url = isset($_POST['url']) ? $_POST['url'] : '';
// Get the IP address and User Agent
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$timestamp = date('Y-m-d H:i:s');
// Simple validation
if ($url) {
// Database connection
$db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Prepare and execute the insert statement
$stmt = $db->prepare("INSERT INTO analytics (url, ip_address, user_agent, timestamp) VALUES (:url, :ip, :user_agent, :timestamp)");
$stmt->execute([
':url' => $url,
':ip' => $ip,
':user_agent' => $userAgent,
':timestamp' => $timestamp
]);
}
?>
Database Table Structure (analytics
)
CREATE TABLE analytics (
id INT AUTO_INCREMENT PRIMARY KEY,
url VARCHAR(255) NOT NULL,
ip_address VARCHAR(45) NOT NULL,
user_agent VARCHAR(255) NOT NULL,
timestamp DATETIME NOT NULL
);
Advantages of This Approach
- Control: You own your data and can decide how to use it.
- Privacy-Friendly: Minimal user data is collected, reducing compliance burdens and increasing user-data security. And a soon to be trendy phrase “Data-Minimalism”.
- Performance: No heavy scripts slowing down your site - if you feel this can be problematic for performance, just add a timer to run the script 0.5 seconds later.
Potential Extensions
- GeoIP Lookup: Use the IP address to determine the user's approximate location - there are a lot of free and simple-to-use APIs.
- Browser and Device Parsing: Analyze the user agent string to get information about the browser and device - again, a lot of free and simple-to-use APIs.
- Session Tracking: Implement cookies to track sessions and returning users.
- Analytics Dashboard: Build a simple dashboard to visualize your data. Yet again, you can use some third-party graph libraries, you can build it yourself, you can or don't have to implement AJAX loading or real-time stats display.
You can do it as needed. Don't get stressed out by how much you need to do - you DON'T, that's the whole point.
My Advice on How to Define a Session
Figuring out things like this is usually more time-consuming than the code itself. Well, the code is very simple often in fact.
We define a session as "15 minutes after the last activity or ping is a new session." We figured that when a user doesn't interact or doesn't have the page open for 15 minutes, they've stopped their activity, their research, their... whatever users do.
Be Mindful
- Accuracy: While the specifics (location, devices, …) won't be as precise as Google Analytics, it's sufficient for most needs.
- Scalability: For high-traffic websites, you'll need to optimize your database and scripts accordingly. My tip from our real setup - set up separate server just for the stats. But my guess is if you have a large traffic, your SEO or marketing team will force you into GA anyway.
Our 4-years Experience
In my company LINK-V, we have and keep enhancing our in-house stats for almost 4 years. From all the clients and projects, we’ve had so far 3 clients that requested GA over our own we call Grace Data. One of them has legitimate reason - they sell partner placement positions and are required to present data from GA for negotiations (yet comparing with Grace Data for different points of view GA doesn’t offer). The other two are simply used to GA, but don’t really need it. All others rely on our in-house stats and are satisfied with the data they are getting.
We also started with single logging. Then we went way overboard and collected every click (my idea, thought it was clever) and stopped and deleted all those since. Now we track session length, content view (more specific then URLs), working on filtering out bots and much more. Yet we still don’t connect those to users, because why would we?
This article is about showing you it’s very simple to start with your own and that you don’t need any more. And it’s coming from experience with development and client interactions and satisfaction. I can safely say - everybody’s happy.
With enough interest, I’ll happily share snippets and detailed experience with different aspects of data collection and processing.
Conclusion
By building a simple, homemade analytics solution, you regain control over your data, improve site performance, and sidestep many of the privacy issues associated with third-party analytics services. Plus, you can customize it to collect exactly the data you need - nothing more, nothing less.
So before you default to using heavy analytics scripts, ask yourself if you really need all that data. Chances are, a lightweight, custom solution will serve you just fine.