First-party analytics with SQLite
By Flavio
Tagged: Database
Build product analytics with a SQLite events table in D1 instead of Google Analytics: whitelisted events, server tracking, beacons, funnel SQL.
I didn’t want Google Analytics on an app I built. All I wanted were simple funnel numbers: how many reports get created, how many people click the paywall, and how many pay.
So I built first-party analytics on top of D1, using a single events table and a whitelist of allowed event names.
One table, append-only
The schema stays flat on purpose:
export const events = sqliteTable('events', {
id: text('id').primaryKey(),
name: text('name').notNull(),
src: text('src'),
anonToken: text('anon_token'),
userId: text('user_id'),
reportId: text('report_id'),
meta: text('meta', { mode: 'json' }),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
})
Every row records an event, where name is the event type and meta holds small extras like the product id, tool name, or share slug.
Add an index on (name, created_at), since funnel queries filter by event name and time range constantly.
Whitelist event names
Accepting arbitrary strings from the client leads to garbage rows and storage bills.
Define the allowed names in TypeScript:
export const EVENT_NAMES = [
'report_created',
'report_viewed',
'checkout_started',
'checkout_completed',
'signup',
] as const
Server-side trackEvent() only inserts known names, and the type system enforces that at compile time.
For client beacons, keep a smaller allowlist with only the events that need the browser:
export const BEACON_EVENT_NAMES = [
'blur_click',
'brief_cta_click',
'agent_prompt_copy',
] as const
Everything else gets recorded on the server where you already trust the code path.
Track on the server during renders
The cleanest signals fire right where the action already happens. When POST /api/reports inserts a row, it calls trackEvent. The report page coordinator loads data and tracks the view before rendering, and the billing route tracks checkout starts right before redirecting to Polar.
Here’s how trackEvent works on the server:
await trackEvent(db, {
name: 'report_viewed',
src: getSrc(cookies),
anonToken,
userId: user?.id ?? null,
reportId,
})
trackEvent catches failures and logs them to the console, so analytics never breaks a user flow.
Client beacons for click signals
Some events only exist in the browser, like a blur panel click, a CTA tap, or a copy button.
Use navigator.sendBeacon so the request survives page navigation:
export function sendBeacon(name: BeaconEventName, reportId?: string) {
const body = JSON.stringify({ name, reportId })
const url = '/api/events'
if (navigator.sendBeacon) {
navigator.sendBeacon(url, new Blob([body], { type: 'application/json' }))
return
}
fetch(url, { method: 'POST', body, keepalive: true })
}
The POST /api/events route checks the name against BEACON_EVENT_NAMES, returning 400 for an unknown name and 429 when rate-limited.
The server attaches anonToken, userId, and campaign src from cookies, so the client only sends what it knows.
Campaign attribution with ?src=
Newsletter links carry ?src=nl-2026-07-launch. Middleware sanitizes the tag and saves it in an httpOnly cookie.
Every trackEvent call reads that cookie, so later you can group conversions by campaign without parsing UTMs in SQL.
Funnel queries on top
You build the funnel by counting rows:
SELECT name, COUNT(*) AS total
FROM events
WHERE created_at >= unixepoch('now', '-30 days') * 1000
GROUP BY name
ORDER BY total DESC
Unlock conversion is two counts:
SELECT
(SELECT COUNT(*) FROM events WHERE name = 'report_viewed' ...) AS viewed,
(SELECT COUNT(*) FROM events WHERE name = 'checkout_completed'
AND json_extract(meta, '$.product') = 'unlock' ...) AS unlocks
I built a small /admin/funnel page that runs these counts for the last 7, 30, or 90 days. Conversion percentages are just to / from * 100 in TypeScript.
What you trade away
You don’t get session replay, geo maps, or real-time cohort dashboards.
In exchange, you own the data and it stays in your SQLite database. There’s no third-party script on every page and no cookie banner drama for basic product metrics.
Start with ten event names, not a hundred, and add another only when you have a real question to answer. If you just want to know whether something you shipped worked, a single events table is enough.
If you also want to send signup and order events from your backend to a self-hosted dashboard with curl, check out Send signup and order events from your app to your own dashboard with curl.
Want me to talk about your product? You can sponsor this site.
Related posts about database: