Peek at your traffic. A tiny self-hosted web analytics core on SQLite, shaped like PostHog so an existing posthog-js snippet works against it unchanged.
peeko is the part you keep after ripping out a hosted analytics vendor. You get a capture endpoint that accepts the {event, distinct_id, timestamp, properties} shape posthog-js already sends, a writer that buffers events for a second and flushes them in one WAL transaction so capture volume never touches your serving path, hourly retention pruning, a read API for building a dashboard, and a live SSE feed of events as they land. There's also an optional presence layer that shows which pages have active, idle, or hidden tabs right now; it lives entirely in memory and never writes a heartbeat into analytics storage.
What peeko refuses to do: GeoIP lookups, bot detection, dashboard styling, and your event schema. Those stay yours. The first two arrive through an enrichment hook you write, the dashboard is whatever you build on the read API, and any event field beyond the extracted columns lives in properties where getBreakdown can aggregate it.
Cost and custody. Analytics events are high-volume rows that are individually worthless, which is exactly what per-event pricing punishes hardest. Here everything lands in a SQLite file you own, every dashboard read is a local index scan, and no rate-limited query API sits between you and your own numbers. Give the file its own database so analytics volume can't bloat your app DB.
The write path is bounded everywhere it can hurt: writes buffer for 1s and flush in a single transaction, oversized property bags are truncated, the buffer itself is capped, and retention prunes on a timer.
And it's live. Subscribe in-process, or expose the built-in SSE feed; browsers authenticate with short-lived tickets, so an admin token never ships to the client.
npm install @aleju03/peekoRequires Node 18+ (the examples use global fetch). Storage is @libsql/client, which means a file: path, :memory:, or a remote Turso URL all work.
import { AnalyticsStore, createAnalyticsHandler, createDb } from "@aleju03/peeko";
import { createServer } from "node:http";
const db = await createDb({ url: "file:analytics.db" });
const store = new AnalyticsStore(db, {
retentionDays: 90,
feedHosts: ["example.com"], // count only real site traffic in the feed
feedExcludeViewer: "admin", // hide your own logged-in visits
feedExcludePathPrefixes: ["/admin/"],
});
await store.ensureSchema();
store.start(); // background flush + prune timers
const handler = createAnalyticsHandler({
store,
captureToken: process.env.CAPTURE_TOKEN,
allowedOrigins: ["https://dash.example.com"],
// Your GeoIP + bot-verdict enrichment hook. Runs per capture request.
enrich: (req) => ({
geoCountry: req.headers["x-vercel-ip-country"] as string | undefined,
isBot: /bot|crawler/i.test(req.headers["user-agent"] ?? ""),
}),
});
createServer((req, res) => {
handler(req, res).then((handled) => { if (!handled) { res.writeHead(404); res.end(); } });
}).listen(3000);That exposes four core routes under the base path (default /peeko):
| Route | Method | Purpose |
|---|---|---|
/peeko/capture |
POST | Ingest one payload or {batch:[...]}. Token-gated. |
/peeko/live-ticket |
GET | Mint a short-lived ticket for the browser. Token-gated. |
/peeko/live?ticket= |
GET | SSE stream of accepted, feed-filtered events. |
/peeko/monitor?rangeHours=24 |
GET | JSON rollup (overview, top paths/referrers/countries, bounce, recent). Token-gated. |
Presence routes stay disabled unless a PresenceTracker is passed to the handler:
| Route | Method | Purpose |
|---|---|---|
/peeko/presence/heartbeat |
POST | Upsert one visitor tab and refresh its TTL. Capture-token gated. |
/peeko/presence/leave |
POST | Best-effort explicit tab departure. Capture-token gated. |
/peeko/presence/snapshot |
GET | Current non-expired tabs. Token-gated; filter by country, path, or state. |
/peeko/presence/live-ticket |
GET | Mint a short-lived presence-stream ticket. Token-gated. |
/peeko/presence/live?ticket= |
GET | SSE snapshot followed by presence changes and heartbeats. |
Any posthog-js install works by pointing its host at peeko:
posthog.init("anything", { api_host: "https://your-app.com/peeko" });Or skip the library and send the payload yourself:
fetch("/peeko/capture", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
event: "$pageview",
distinct_id: visitorId,
timestamp: new Date().toISOString(),
properties: { $host: location.host, $pathname: location.pathname, $screen_width: screen.width },
}),
});Use the store directly for a custom dashboard:
await store.getOverview({ rangeHours: 24 }); // active/pageviews/uniques/events
await store.getTopPaths({ rangeHours: 24 });
await store.getTopReferrers({ rangeHours: 24 });
await store.getTopCountries({ rangeHours: 24 });
await store.getBounce({ rangeHours: 24 });
await store.getRecentFeed({ rangeHours: 24, country: "US", limit: 100 });
// The escape hatch for your own event schema: top-N of any property, any event.
await store.getBreakdown({ event: "product_viewed", prop: "sku", rangeHours: 24 });
await store.getBreakdown({ event: "$pageview", prop: "$.utm.campaign", distinct: true, rangeHours: 168 });getBreakdown is what keeps the engine schema-free. Panels like "top products" or "top authors" come from your own event fields in properties, not from anything baked into the core.
Presence answers a different question than analytics ("who's on the site right now" versus "what happened"), so it's kept apart on purpose: heartbeats never touch SQLite, never increment an event count, and vanish on process restart. Enable it only when a live operational view earns its keep:
import { AnalyticsStore, PresenceTracker, createAnalyticsHandler } from "@aleju03/peeko";
const store = new AnalyticsStore(db);
const presence = new PresenceTracker({
ttlMs: 60_000, // expire a silent tab after one minute
sweepIntervalMs: 5_000,
maxEntries: 5_000, // bound process memory; stalest tabs are evicted
});
await store.ensureSchema();
store.start();
presence.start();
const handler = createAnalyticsHandler({
store,
presence, // omit this and every /presence/* route stays disabled
captureToken: process.env.CAPTURE_TOKEN,
enrich: (req) => ({
geoCountry: req.headers["x-vercel-ip-country"] as string | undefined,
isBot: /bot|crawler/i.test(req.headers["user-agent"] ?? ""),
}),
});A heartbeat describes one browser tab. distinct_id identifies the visitor; tab_id distinguishes multiple open tabs:
const tabId = crypto.randomUUID();
let lastInteractionAt = Date.now();
for (const event of ["pointerdown", "keydown", "scroll", "touchstart"]) {
addEventListener(event, () => { lastInteractionAt = Date.now(); }, { passive: true });
}
function activityState() {
if (document.visibilityState !== "visible") return "hidden";
if (!document.hasFocus() || Date.now() - lastInteractionAt > 60_000) return "idle";
return "active";
}
function sendPresence() {
return fetch("/peeko/presence/heartbeat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
distinct_id: visitorId,
tab_id: tabId,
path: location.pathname,
state: activityState(),
last_interaction_at: lastInteractionAt,
}),
keepalive: true,
});
}
sendPresence();
const presenceTimer = setInterval(sendPresence, 25_000);
addEventListener("focus", sendPresence);
addEventListener("blur", sendPresence);
document.addEventListener("visibilitychange", sendPresence);
addEventListener("pagehide", () => {
clearInterval(presenceTimer);
navigator.sendBeacon(
"/peeko/presence/leave",
new Blob(
[JSON.stringify({ distinct_id: visitorId, tab_id: tabId })],
{ type: "application/json" },
),
);
});Call sendPresence() after SPA navigation so route changes show up immediately. If capture is token-gated, proxy the heartbeat and leave calls through your application the same way you proxy capture; the server token must never appear in browser JavaScript.
The presence SSE stream opens with presence_snapshot, then emits presence_change frames:
upsertmeans a tab joined or changed route/state/interaction metadata.touchis a compact unchanged heartbeat that refreshesupdatedAtandexpiresAt.leavewithleftcame from the best-effort leave endpoint.leavewithexpiredis the authoritative TTL timeout.leavewithevictedmeans the configured in-memory cap was reached.leavewithfilteredmeans a tab moved out of a filtered stream.
Repeated unchanged heartbeats emit only the compact touch shape and never write analytics rows. One caveat worth knowing before you rely on it: presence is process-local, which fits peeko's single-process SQLite deployment fine, but a multi-instance app needs to supply a shared ephemeral presence implementation before treating the view as global.
npm install
npm run example # boots a server, captures events, prints the live feed + rollup
npm test # unit + end-to-end HTTP/SSE testsMIT
