feat(analytics): record where paying customers actually came from

Adds first-party acquisition attribution and a sixteen-event funnel, written to
this deployment's own database and read back on /admin/growth. Nothing is sent
anywhere else, and the whole subsystem is off unless OPENFRAME_ENABLE_ANALYTICS
is set, so a self-hosted instance carries the tables empty and pays nothing.

The proxy gives a visitor an anonymous id and stores what brought them in two
first-party cookies; signup copies that onto the account and claims the events
the visitor produced before they had one, which is what joins the two halves of
the funnel. Recording happens where each step actually happens rather than in
the browser: an ad blocker cannot undercount landing views, and blocking rates
differ by channel, so an undercounted denominator would have made GitHub traffic
look like it converts better than it does.

Every event carries a dedupe key on a UNIQUE column, so "recorded exactly once"
is a property of the schema rather than of fifteen call sites. Subscription
events are derived by comparing the row being overwritten with the row being
written inside the existing Stripe sync, which makes them order-independent and
replay-safe.

The scoreboard reports step-to-step conversion with the denominator beside it,
and splits by source over a rolling 28-day window rather than a week: at this
volume a weekly per-source cell holds single digits, and a percentage computed
from three visits reads exactly as confidently as one computed from three
hundred.

"How did you hear about us?" is asked on the first onboarding screen, not on the
registration form. The number being measured is the signup conversion rate, and
a question added to that form would move it.
This commit is contained in:
yusufipk
2026-08-01 20:00:27 +03:00
parent 93e85683e9
commit 7ca5abd041
48 changed files with 3214 additions and 25 deletions
+69 -3
View File
@@ -1,9 +1,75 @@
import { NextResponse } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';
import { buildContentSecurityPolicy } from '@/lib/content-security-policy';
import {
classifyChannel,
extractReferrerHost,
sanitizeLandingPath,
sanitizeTag,
} from '@/lib/analytics/channel';
import {
ANONYMOUS_ID_COOKIE,
ANONYMOUS_ID_MAX_AGE_SECONDS,
FIRST_TOUCH_COOKIE,
encodeFirstTouch,
generateAnonymousId,
isValidAnonymousId,
} from '@/lib/analytics/cookies';
import { isCountableDocumentRequest, isLikelyBot } from '@/lib/analytics/bots';
import { isProductAnalyticsEnabled } from '@/lib/feature-flags';
export function proxy() {
const response = NextResponse.next();
// Runs on the edge, so nothing here touches the database. It only decides who a
// visitor is and what brought them, then hands both downstream as cookies. The
// rows are written by the pages, which run in Node.
function applyAcquisitionCookies(request: NextRequest, response: NextResponse): void {
if (!isProductAnalyticsEnabled()) return;
if (!isCountableDocumentRequest(request.headers)) return;
if (isLikelyBot(request.headers.get('user-agent'))) return;
const cookieOptions = {
httpOnly: true,
sameSite: 'lax' as const,
secure: request.nextUrl.protocol === 'https:',
path: '/',
maxAge: ANONYMOUS_ID_MAX_AGE_SECONDS,
};
const existingId = request.cookies.get(ANONYMOUS_ID_COOKIE)?.value;
if (!isValidAnonymousId(existingId)) {
const anonymousId = generateAnonymousId();
// Set on the request as well as the response: without this the page rendering
// *this* request cannot see the id, and the first landing view of every new
// visitor, the one carrying the campaign tags, goes unrecorded.
request.cookies.set(ANONYMOUS_ID_COOKIE, anonymousId);
response.cookies.set(ANONYMOUS_ID_COOKIE, anonymousId, cookieOptions);
}
if (request.cookies.get(FIRST_TOUCH_COOKIE)) return;
const params = request.nextUrl.searchParams;
const referrerHost = extractReferrerHost(
request.headers.get('referer'),
request.nextUrl.hostname
);
const utmSource = sanitizeTag(params.get('utm_source'));
const utmMedium = sanitizeTag(params.get('utm_medium'));
const firstTouch = encodeFirstTouch({
channel: classifyChannel({ utmSource, utmMedium, referrerHost }),
utmSource,
utmMedium,
utmCampaign: sanitizeTag(params.get('utm_campaign')),
referrerHost,
landingPath: sanitizeLandingPath(request.nextUrl.pathname),
});
request.cookies.set(FIRST_TOUCH_COOKIE, firstTouch);
response.cookies.set(FIRST_TOUCH_COOKIE, firstTouch, cookieOptions);
}
export function proxy(request: NextRequest) {
const response = NextResponse.next({ request });
response.headers.set('Content-Security-Policy', buildContentSecurityPolicy());
applyAcquisitionCookies(request, response);
return response;
}