How I Built a First-Party Analytics Platform With Next.js Edge Middleware
Google Analytics ships a 45 KB script. Plausible and Fathom ship maybe 5.
Third-party analytics tools are standardized, typically consisting of a JavaScript snippet on a page, a beacon request to a data collection endpoint, and a dashboard that pulls from their database. This approach has several drawbacks, including adding a 20-50 KB script to every page, an extra network round trip, a potential target for ad blockers, and the need for a consent banner due to processing user data as a third party.
Next.js Edge Middleware provides an alternative solution that eliminates these issues. Edge Middleware runs on every request at Vercel's edge network, before the page is served, allowing for zero client-side script, zero latency, and no third-party domain that could trigger ad blockers or banners. Glint is a first-party analytics platform built using this approach.
The middleware is implemented as a single file, src/middleware.ts, and runs on every request that matches its config.matcher path. It first checks if analytics tracking is disabled, and if not, it extracts useful data from the request headers, such as city, country, region, user agent, connection type, and timestamp. This data is then used to create common data payload, which is sent to the analytics endpoint using Promise.all(...).catch(() = {}) to avoid blocking the response.
This ensures that the tracking request does not add latency to the page load. The exported config matcher excludes non-page requests to prevent noise in the analytics data.
The payload shape is designed to be optimized for the dashboard queries, with four separate payloads: an "average" record with user agent data, location record, referral record, and traffic record. This separation allows for pre-aggregation on insert, preventing the need for expensive grouping operations during dashboard queries. The result is a lightweight, efficient, and privacy-friendly analytics solution built entirely within the Next.js Edge Middleware framework.
Rewritten by urgent.news; may contain errors — check the original.
Source: hackernoon.com
Read the original at hackernoon.com →
More from HackerNoon on urgent.news
Report a problem with this story
Get the day's news by email. Daily, weekly or monthly. Sign up