Building Privacy-First SaaS Analytics: Leveraging Cloudflare Workers and Edge Data
The modern web is moving away from heavy, privacy-invasive third-party tracking scripts. If you are building a modern SaaS platform or a high-performance portfolio, injecting a 50KB bloated tracking snippet that slows down your Largest Contentful Paint (LCP) is no longer an option.
Instead, the future belongs to Edge-driven, privacy-first analytics.
By shift-lefting your data collection to Cloudflare Workers and combining it with a lightweight server-side parser, you can capture incredibly rich, cumulative insights without setting a single cookie or sacrificing an ounce of performance.
Here is a deep dive into what you can track at the Edge, how to extract it, where to store it, and—most importantly—how to turn raw logs into beautiful, interactive business dashboards.
1. What You Can Collect (Without Third-Party Cookies)
By intercepting requests directly at the Cloudflare Edge, you gain immediate access to structured network metadata and client headers. We can divide these metrics into two powerful categories: Hyper-Local Geodata and Granular Environment Metadata.
A. Network & Geo-Inference (request.cf)
Cloudflare automatically populates the request.cf object at the edge node closest to the user. You don’t need external IP-lookup APIs:
request.cf.country(string): The two-letter ISO 3166-1 Alpha-2 country code (e.g.,UA,US,GB). Essential for global traffic segmentation.request.cf.city(string): The city name in English (e.g.,Kyiv,New York,London).request.cf.latitude&request.cf.longitude(string): The precise coordinates of the city center or region. This is the ultimate fuel for building live, interactive cumulative maps.
B. Client Environment (The User-Agent Header)
While geodata tells you where they are, parsing the standard HTTP User-Agent string on your backend tells you how they experience your product:
- Browser: Identifying whether they use Chrome, Safari, Firefox, or Edge helps prioritize front-end cross-browser testing.
- Operating System (OS): Tracking ecosystem splits (macOS vs. Windows, iOS vs. Android) defines your product design decisions.
- Device Type: Categorizing traffic into
desktop,mobile, ortabletdirectly shapes your CSS layout strategies. - Device Vendor & Model: Extracting specific hardware brands (e.g., Apple iPhone, Samsung Galaxy S24) lets you spot premium user segments and target device-specific mobile optimizations.
2. How to Capture It: The Implementation
In an Astro project deployed via the @astrojs/cloudflare adapter, you don’t need a separate server. You can handle this natively inside an API route or a server-rendered page layout.
By pairing Cloudflare’s native object with a lightweight V8-compatible runtime parser like ua-parser-js, you can extract zero-bloat environment data in milliseconds:
// src/pages/api/track-visit.ts
import type { APIRoute } from 'astro';
import { UAParser } from 'ua-parser-js';
export const POST: APIRoute = async ({ request, runtime }) => {
try {
const env = runtime.env;
const cf = (request as any).cf;
const body = await request.json();
// Parse the standard User-Agent header
const uaString = request.headers.get('user-agent') || '';
const parser = new UAParser(uaString);
const uaResult = parser.getResult();
// Extract Edge Geodata
const country = cf?.country || 'Unknown';
const city = cf?.city || 'Unknown';
const lat = cf?.latitude ? parseFloat(cf.latitude) : null;
const lng = cf?.longitude ? parseFloat(cf.longitude) : null;
// Extract parsed device environment
const device_type = uaResult.device.type || 'desktop';
const device_vendor = uaResult.device.vendor || 'Generic';
const device_model = uaResult.device.model || 'Generic Device';
const os = uaResult.os.name || 'Other OS';
const browser = uaResult.browser.name || 'Other Browser';
// Ready for secure server-side storage...
} catch (err) {
return new Response(JSON.stringify({ error: err.message }), { status: 500 });
}
};
3. Where to Store It: Edge-Native Databases
Traditional SQL databases require managing connection pools, VPCs, and global replication. For an Edge architecture, your storage solution needs to live right alongside your compute.
Cloudflare D1 (built on top of SQLite) is the perfect fit. It offers instant scaling, zero-cold starts, and zero-management setup.
The Storage Schema
CREATE TABLE user_visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
session_id TEXT NOT NULL,
page_path TEXT NOT NULL,
referrer TEXT,
-- Geolocation
country TEXT,
city TEXT,
latitude REAL,
longitude REAL,
-- Client Environment
device_type TEXT,
device_vendor TEXT,
device_model TEXT,
os TEXT,
browser TEXT
);
CREATE INDEX idx_visits_geo ON user_visits(latitude, longitude);
CREATE INDEX idx_visits_timestamp ON user_visits(timestamp);
4. How to Use It: Transforming Data Into UI Value
Collecting data is worthless unless it drives product growth, operational awareness, or client conversions. Here is how you can leverage these cumulative metrics to build a breathtaking B2B SaaS dashboard:
📊 Live Cumulative Map Markers
Instead of generic list rows, use the extracted latitude and longitude fields to plot geographic heatmaps or bubble maps via Leaflet.js or Mapbox. Group your D1 rows using COUNT(*) based on coordinate pairs. As visits accumulate, the radius of the marker expands, creating a visual showcase of your global adoption.
📱 Premium Hardware Analytics
By combining device_vendor and device_model, you can move past vague “Mobile vs Desktop” metrics. Now you can display sleek progress bars showing exactly which flagship devices are browsing your SaaS application. If 40% of your mobile traffic comes from the latest Apple iPhone or Samsung Galaxy S, you instantly know where to focus your mobile web performance budgeting.
🧩 Smart Content & Dynamic Routing
Since request.cf is available before the page is fully rendered, you can use it inside your Astro components to personalize the UI on the fly. Dynamically display pricing in the local currency based on request.cf.country, pre-select country codes on payment forms, or serve localized hero sections without waiting for client-side JavaScript to boot. Final Thoughts
Building your own web analytics isn’t just a fun side-project—it’s a massive competitive advantage for modern SaaS products. By utilizing Cloudflare Workers, D1, and native User-Agent parsing, you gain absolute ownership over your data pipeline, guarantee 100% data privacy for your users, and maintain an uncompromisingly fast web experience.
Are you still relying on external tracking scripts, or have you started moving your product analytics to the Edge? Let’s discuss on Linkedin! 👇**
