From 7ca5abd041add2e471837c779d01fb4d3d8ad6e7 Mon Sep 17 00:00:00 2001
From: yusufipk
Date: Sat, 1 Aug 2026 20:00:27 +0300
Subject: [PATCH] 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.
---
.env.example | 4 +
README.md | 1 +
app/(auth)/register/page.tsx | 9 +
app/(marketing)/[slug]/page.tsx | 14 +-
app/admin/growth/page.tsx | 358 +++++++++++++++++
app/admin/layout.tsx | 16 +-
app/api/admin/growth/route.ts | 35 ++
.../approvals/[requestId]/decision/route.ts | 7 +
app/api/auth/register/route.ts | 10 +
app/api/billing/checkout/route.ts | 10 +
app/api/events/route.ts | 36 ++
app/api/onboarding/source/route.ts | 40 ++
.../videos/[videoId]/share/route.ts | 15 +-
app/api/projects/[projectId]/videos/route.ts | 7 +
app/api/projects/route.ts | 10 +
.../versions/[versionId]/comments/route.ts | 13 +
app/api/workspaces/route.ts | 7 +
app/onboarding/onboarding-wizard.tsx | 77 +++-
app/onboarding/page.tsx | 2 +
app/page.tsx | 13 +-
components/LandingPage.tsx | 13 +-
components/marketing/comparison-page.tsx | 9 +-
components/marketing/cta-link.tsx | 30 ++
lib/analytics/billing-events.ts | 88 +++++
lib/analytics/bots.ts | 42 ++
lib/analytics/channel.ts | 212 ++++++++++
lib/analytics/cookies.ts | 113 ++++++
lib/analytics/record.ts | 183 +++++++++
lib/analytics/scoreboard.ts | 323 ++++++++++++++++
lib/analytics/signup.ts | 48 +++
lib/analytics/visitor.ts | 72 ++++
lib/auth.ts | 15 +
lib/billing.ts | 58 ++-
lib/client/track.ts | 31 ++
lib/email-verification.ts | 19 +
lib/feature-flags.ts | 10 +
lib/rate-limit.ts | 3 +
.../migration.sql | 87 +++++
prisma/schema.prisma | 116 +++++-
proxy.ts | 72 +++-
tests/api/analytics-events.test.ts | 365 ++++++++++++++++++
tests/api/analytics-scoreboard.test.ts | 155 ++++++++
tests/api/auth-matrix.test.ts | 24 +-
tests/setup/db-global.ts | 1 +
tests/unit/lib/analytics-channel.test.ts | 130 +++++++
tests/unit/lib/analytics-cookies.test.ts | 137 +++++++
tests/unit/lib/analytics-scoreboard.test.ts | 36 ++
tests/unit/proxy.test.ts | 163 ++++++++
48 files changed, 3214 insertions(+), 25 deletions(-)
create mode 100644 app/admin/growth/page.tsx
create mode 100644 app/api/admin/growth/route.ts
create mode 100644 app/api/events/route.ts
create mode 100644 app/api/onboarding/source/route.ts
create mode 100644 components/marketing/cta-link.tsx
create mode 100644 lib/analytics/billing-events.ts
create mode 100644 lib/analytics/bots.ts
create mode 100644 lib/analytics/channel.ts
create mode 100644 lib/analytics/cookies.ts
create mode 100644 lib/analytics/record.ts
create mode 100644 lib/analytics/scoreboard.ts
create mode 100644 lib/analytics/signup.ts
create mode 100644 lib/analytics/visitor.ts
create mode 100644 lib/client/track.ts
create mode 100644 prisma/migrations/20260801120000_add_acquisition_analytics/migration.sql
create mode 100644 tests/api/analytics-events.test.ts
create mode 100644 tests/api/analytics-scoreboard.test.ts
create mode 100644 tests/unit/lib/analytics-channel.test.ts
create mode 100644 tests/unit/lib/analytics-cookies.test.ts
create mode 100644 tests/unit/lib/analytics-scoreboard.test.ts
create mode 100644 tests/unit/proxy.test.ts
diff --git a/.env.example b/.env.example
index fa63f41..5d0d2f2 100644
--- a/.env.example
+++ b/.env.example
@@ -34,6 +34,10 @@ OPENFRAME_R2_MULTIPART_PART_SIZE_BYTES="33554432"
# Run once after creating the bucket: bun run r2:configure-cors
# Or set CORS manually in Cloudflare R2 -> bucket -> Settings -> CORS policy.
OPENFRAME_REQUIRE_INVITE_CODE="true"
+# Acquisition attribution and funnel events, read back on /admin/growth. Off by
+# default: the rows only pay for themselves if you are running a signup funnel.
+# Everything is written to this instance's own database and sent nowhere.
+OPENFRAME_ENABLE_ANALYTICS="false"
SELF_HOSTED_AUTO_CREATE_BUCKET="false"
# ============================================================================
diff --git a/README.md b/README.md
index adc1b64..79f6dfd 100644
--- a/README.md
+++ b/README.md
@@ -180,6 +180,7 @@ Behavior when disabled:
- `OPENFRAME_ENABLE_BUNNY_UPLOADS=false` hides Bunny direct-upload entry points. URL-based providers such as YouTube remain available.
- `OPENFRAME_ENABLE_S3_VIDEO_UPLOADS=true` (with `R2_*` configured) enables presigned uploads to your own S3-compatible storage. Set `OPENFRAME_ENABLE_BUNNY_UPLOADS=false` — only one direct-upload backend can be active. The bucket must allow CORS `PUT` from your app origin (for example `http://localhost:3000` in dev and your production URL). For Docker + MinIO, keep `R2_ENDPOINT=http://minio:9000` (app-internal) and set `R2_PRESIGN_ENDPOINT` to the browser-reachable MinIO origin (for example `http://localhost:9000` locally, or `https://minio.example.com` when MinIO is behind a reverse proxy). Use the origin only — no path suffix. The app's Content-Security-Policy is generated from runtime env at request time, so published Docker images pick up custom `R2_PRESIGN_ENDPOINT` values without rebuilding or editing `next.config.ts`.
- `OPENFRAME_REQUIRE_INVITE_CODE=false` allows open registration while keeping invitation-link registration intact.
+- `OPENFRAME_ENABLE_ANALYTICS=true` records first-touch attribution and funnel events into your own database, readable on `/admin/growth`. Off by default, and nothing leaves the instance either way.
For self-hosted MinIO behind a reverse proxy, choose one of these browser-facing layouts:
diff --git a/app/(auth)/register/page.tsx b/app/(auth)/register/page.tsx
index 43a012a..2610263 100644
--- a/app/(auth)/register/page.tsx
+++ b/app/(auth)/register/page.tsx
@@ -1,3 +1,6 @@
+import { cookies } from 'next/headers';
+import { after } from 'next/server';
+import { readVisitorContext, recordVisitorEvent } from '@/lib/analytics/visitor';
import { isInviteCodeRequired } from '@/lib/feature-flags';
import { getInvitationPreviewByToken } from '@/lib/invitations';
import { isInvitationPreviewAllowed } from '@/lib/invitation-preview-limit';
@@ -8,6 +11,12 @@ interface RegisterPageProps {
}
export default async function RegisterPage({ searchParams }: RegisterPageProps) {
+ // Reaching this page is the funnel step. Recording it here rather than from the
+ // browser also keeps it honest: a prefetch of this route is filtered in the
+ // proxy, so signup starts can never outnumber the landing views above them.
+ const visitor = readVisitorContext(await cookies());
+ after(() => recordVisitorEvent('SIGNUP_STARTED', visitor));
+
const googleEnabled = Boolean(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET);
const githubEnabled = Boolean(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET);
diff --git a/app/(marketing)/[slug]/page.tsx b/app/(marketing)/[slug]/page.tsx
index 4e0c393..6a5b0b5 100644
--- a/app/(marketing)/[slug]/page.tsx
+++ b/app/(marketing)/[slug]/page.tsx
@@ -1,6 +1,9 @@
import type { Metadata } from 'next';
+import { cookies } from 'next/headers';
import { notFound } from 'next/navigation';
+import { after } from 'next/server';
import { ComparisonPage } from '@/components/marketing/comparison-page';
+import { readVisitorContext, recordVisitorEvent } from '@/lib/analytics/visitor';
import { auth } from '@/lib/auth';
import { comparisonPages, getComparisonPage } from '@/lib/marketing/comparison-pages';
import { buildComparisonJsonLd, buildComparisonMetadata } from '@/lib/marketing/metadata';
@@ -38,6 +41,15 @@ export default async function MarketingSlugPage({ params }: MarketingSlugPagePro
}
const session = await auth();
+ const isLoggedIn = Boolean(session?.user);
+
+ // A comparison page is a landing page: for most of these visitors it is the
+ // first thing they see, so it belongs in the same visitor count as `/`.
+ if (!isLoggedIn) {
+ const visitor = readVisitorContext(await cookies());
+ after(() => recordVisitorEvent('LANDING_VIEW', visitor));
+ }
+
const structuredData = buildComparisonJsonLd({
title: page.title,
description: page.metaDescription,
@@ -57,7 +69,7 @@ export default async function MarketingSlugPage({ params }: MarketingSlugPagePro
}}
/>
))}
-
+
>
);
}
diff --git a/app/admin/growth/page.tsx b/app/admin/growth/page.tsx
new file mode 100644
index 0000000..58d34ab
--- /dev/null
+++ b/app/admin/growth/page.tsx
@@ -0,0 +1,358 @@
+import { Metadata } from 'next';
+import { redirect } from 'next/navigation';
+import { auth } from '@/lib/auth';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import {
+ AT_RISK_SILENT_DAYS,
+ conversionRates,
+ getScoreboard,
+ type FunnelRates,
+} from '@/lib/analytics/scoreboard';
+import { isProductAnalyticsEnabled } from '@/lib/feature-flags';
+import { AlertTriangle, CreditCard, TrendingUp, Users } from 'lucide-react';
+
+export const metadata: Metadata = {
+ title: 'Growth | OpenFrame',
+ description: 'Acquisition funnel and retention scoreboard',
+};
+
+function formatMoney(cents: number | null, currency: string) {
+ if (cents === null) return '—';
+ const safeCurrency = /^[a-zA-Z]{3}$/.test(currency) ? currency.toUpperCase() : 'USD';
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: safeCurrency,
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 0,
+ }).format(cents / 100);
+}
+
+function formatWeek(date: Date) {
+ return date.toISOString().slice(0, 10);
+}
+
+function formatDate(date: Date | null) {
+ return date ? date.toISOString().slice(0, 10) : 'never';
+}
+
+/** A percentage with the count it was computed from, because n matters here. */
+function Rate({ rate, of }: { rate: number | null; of: number }) {
+ if (rate === null) return —;
+ return (
+
+ {Math.round(rate * 100)}% /{of}
+
+ );
+}
+
+const WEEK_COLUMNS: Array<{ key: string; label: string }> = [
+ { key: 'visitors', label: 'Visitors' },
+ { key: 'signups', label: 'Signup' },
+ { key: 'firstVideo', label: 'Video' },
+ { key: 'shareLinks', label: 'Share link' },
+ { key: 'externalFeedback', label: 'Ext. feedback' },
+ { key: 'trials', label: 'Trial' },
+ { key: 'newPaid', label: 'New paid' },
+ { key: 'canceled', label: 'Canceled' },
+ { key: 'activePaid', label: 'Active paid' },
+];
+
+export default async function AdminGrowthPage() {
+ const session = await auth();
+ if (!session?.user?.isAdmin) {
+ redirect('/');
+ }
+
+ if (!isProductAnalyticsEnabled()) {
+ return (
+
+
Growth
+
+
+ Acquisition tracking is off on this deployment. Set{' '}
+ OPENFRAME_ENABLE_ANALYTICS=true to start recording
+ the funnel. Nothing is collected until you do, and nothing is ever sent anywhere but
+ this instance's own database.
+
+
+
+ {latest ? `week of ${formatWeek(latest.weekStart)}` : 'no data yet'}
+
+
+
+
+
+ At risk
+
+
+
+
{scoreboard.atRisk.length}
+
+ paid, silent for {AT_RISK_SILENT_DAYS}+ days
+
+
+
+
+
+
+
+ Weekly funnel
+
+ Weeks start Monday, UTC. Active paid is the running net of subscriptions started minus
+ canceled, so it can drift from the Stripe figure above; the difference is the drift.
+
+
+
+
+
+
+
Week
+ {WEEK_COLUMNS.map((column) => (
+
+ {column.label}
+
+ ))}
+
MRR
+
+
+
+ {scoreboard.weeks.map((week) => (
+
+
{formatWeek(week.weekStart)}
+ {WEEK_COLUMNS.map((column) => (
+
+ {week[column.key as keyof typeof week] as number}
+
+ Every step over the whole {scoreboard.weeks.length}-week window, with the denominator
+ beside it. The lowest rate is the step to work on.
+
+
+
+
+
Visitor to signup
+
+
+
+
+
+
Signup to first video
+
+
+
+
+
+
Video to share link
+
+
+
+
+
+
Share to outside feedback
+
+
+
+
+
+
Trial to paid
+
+
+
+
+
+
+
+
+
+ By source
+
+ Rolling {scoreboard.channelWindowDays} days rather than one week: a weekly per-source
+ cell holds single digits at this volume, and a percentage computed from three visits
+ reads exactly as confidently as one computed from three hundred.
+
+ Value events are videos, share links, outside feedback, approvals and projects. Rows
+ marked at risk have produced none for {AT_RISK_SILENT_DAYS} days.
+
+ );
+}
diff --git a/app/admin/layout.tsx b/app/admin/layout.tsx
index 8ac9288..a57dcbe 100644
--- a/app/admin/layout.tsx
+++ b/app/admin/layout.tsx
@@ -2,7 +2,7 @@ import { redirect } from 'next/navigation';
import { auth } from '@/lib/auth';
import { Header } from '@/components/layout';
import Link from 'next/link';
-import { LayoutDashboard, MessageSquareQuote, Users } from 'lucide-react';
+import { LayoutDashboard, MessageSquareQuote, TrendingUp, Users } from 'lucide-react';
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const session = await auth();
@@ -39,6 +39,13 @@ export default async function AdminLayout({ children }: { children: React.ReactN
Feedback
+
+
+ Growth
+
{/* Desktop Nav */}
@@ -66,6 +73,13 @@ export default async function AdminLayout({ children }: { children: React.ReactN
Feedback
+
+
+ Growth
+
diff --git a/app/api/admin/growth/route.ts b/app/api/admin/growth/route.ts
new file mode 100644
index 0000000..7a710dd
--- /dev/null
+++ b/app/api/admin/growth/route.ts
@@ -0,0 +1,35 @@
+import { NextRequest } from 'next/server';
+import { auth } from '@/lib/auth';
+import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
+import { conversionRates, getScoreboard } from '@/lib/analytics/scoreboard';
+import { isProductAnalyticsEnabled } from '@/lib/feature-flags';
+import { logError } from '@/lib/logger';
+
+// The same numbers /admin/growth renders, as JSON, so the Monday digest can pull
+// the scoreboard instead of somebody retyping it into a table.
+export async function GET(request: NextRequest) {
+ try {
+ const session = await auth();
+ if (!session?.user?.isAdmin) {
+ return apiErrors.forbidden('Admin access required');
+ }
+
+ if (!isProductAnalyticsEnabled()) {
+ return apiErrors.badRequest('Analytics are disabled by this host');
+ }
+
+ const weeksParam = Number(request.nextUrl.searchParams.get('weeks'));
+ const scoreboard = await getScoreboard({
+ weeks: Number.isSafeInteger(weeksParam) && weeksParam > 0 ? weeksParam : undefined,
+ });
+
+ const response = successResponse({
+ ...scoreboard,
+ weeks: scoreboard.weeks.map((week) => ({ ...week, rates: conversionRates(week) })),
+ });
+ return withCacheControl(response, 'private, no-store');
+ } catch (error) {
+ logError('Error building the growth scoreboard:', error);
+ return apiErrors.internalError('Failed to build the scoreboard');
+ }
+}
diff --git a/app/api/approvals/[requestId]/decision/route.ts b/app/api/approvals/[requestId]/decision/route.ts
index f5ecf6a..71b141f 100644
--- a/app/api/approvals/[requestId]/decision/route.ts
+++ b/app/api/approvals/[requestId]/decision/route.ts
@@ -6,6 +6,7 @@ import { notifyUsers } from '@/lib/notifications';
import { rateLimit } from '@/lib/rate-limit';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import { logError } from '@/lib/logger';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
type RouteParams = { params: Promise<{ requestId: string }> };
@@ -202,6 +203,12 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
});
if (updated.status === 'APPROVED') {
+ await recordEvent({
+ name: 'APPROVAL_COMPLETED',
+ dedupeKey: eventKey('APPROVAL_COMPLETED', requestId),
+ userId: approvalRequest.version.video.project.ownerId,
+ });
+
notifyUsers([updated.requestedById], {
type: 'approval_completed',
projectName: updated.version.video.project.name,
diff --git a/app/api/auth/register/route.ts b/app/api/auth/register/route.ts
index 7c28ba9..e7c671b 100644
--- a/app/api/auth/register/route.ts
+++ b/app/api/auth/register/route.ts
@@ -17,6 +17,8 @@ import {
sendVerificationEmail,
} from '@/lib/email-verification';
import { isValidEmailAddress, normalizeEmail } from '@/lib/email-validation';
+import { recordSignupCompleted } from '@/lib/analytics/signup';
+import { readVisitorContext } from '@/lib/analytics/visitor';
export async function POST(request: NextRequest) {
try {
@@ -132,6 +134,14 @@ export async function POST(request: NextRequest) {
}
}
+ // Ties the account to the first touch stored in this browser's cookie and
+ // claims the visitor events that led here. Recorded after the invitation has
+ // been accepted, so an account that gets rolled back never leaves a signup.
+ await recordSignupCompleted({
+ userId: user.id,
+ visitor: readVisitorContext(request.cookies),
+ });
+
// Send verification email if SMTP is configured
if (emailVerificationRequired) {
const verificationToken = await createVerificationToken(normalizedEmail);
diff --git a/app/api/billing/checkout/route.ts b/app/api/billing/checkout/route.ts
index b28cb83..81c44dd 100644
--- a/app/api/billing/checkout/route.ts
+++ b/app/api/billing/checkout/route.ts
@@ -11,6 +11,7 @@ import { isStripeFeatureEnabled } from '@/lib/feature-flags';
import { getStripe, getStripePriceId, isStripeConfigured } from '@/lib/stripe';
import { isTrustedSameOriginRequest } from '@/lib/request-origin';
import { logError } from '@/lib/logger';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
function getAppOrigin(request: NextRequest) {
if (isTrustedSameOriginRequest(request)) {
@@ -84,6 +85,15 @@ export async function POST(request: NextRequest) {
throw new Error('Stripe did not return a checkout URL');
}
+ // Keyed on the Stripe session, so an abandoned checkout followed by a second
+ // attempt counts twice. That is the intent: the gap between checkouts started
+ // and subscriptions started is the number worth watching.
+ await recordEvent({
+ name: 'CHECKOUT_STARTED',
+ dedupeKey: eventKey('CHECKOUT_STARTED', checkoutSession.id),
+ userId: session.user.id,
+ });
+
const response = successResponse({ url: checkoutSession.url });
return withCacheControl(response, 'private, no-store');
} catch (error) {
diff --git a/app/api/events/route.ts b/app/api/events/route.ts
new file mode 100644
index 0000000..417680e
--- /dev/null
+++ b/app/api/events/route.ts
@@ -0,0 +1,36 @@
+import { NextRequest } from 'next/server';
+import { rateLimit } from '@/lib/rate-limit';
+import { isTrustedSameOriginRequest } from '@/lib/request-origin';
+import { readVisitorContext, recordVisitorEvent } from '@/lib/analytics/visitor';
+
+// The one funnel event that cannot be observed from the server: a click on a
+// call to action, which never reaches us as a request of its own.
+//
+// Everything else in the funnel is recorded where it actually happens, so this
+// endpoint accepts exactly one event name. An anonymous caller must not be able
+// to post `SUBSCRIPTION_STARTED` into the scoreboard, and the cheapest way to
+// guarantee that is to make the allowed set a single literal.
+const ALLOWED_EVENTS = new Set(['cta_clicked']);
+
+export async function POST(request: NextRequest) {
+ // Answers 204 whatever happens. This endpoint reports nothing back to the page
+ // that called it, so there is no reason to tell a caller which of their
+ // attempts landed.
+ const noContent = new Response(null, {
+ status: 204,
+ headers: { 'Cache-Control': 'private, no-store' },
+ });
+
+ const limited = await rateLimit(request, 'analytics-beacon');
+ if (limited) return limited;
+
+ if (!isTrustedSameOriginRequest(request)) return noContent;
+
+ const body = await request.json().catch(() => null);
+ const name = typeof body?.name === 'string' ? body.name : '';
+ if (!ALLOWED_EVENTS.has(name)) return noContent;
+
+ await recordVisitorEvent('CTA_CLICKED', readVisitorContext(request.cookies));
+
+ return noContent;
+}
diff --git a/app/api/onboarding/source/route.ts b/app/api/onboarding/source/route.ts
new file mode 100644
index 0000000..c4cab9f
--- /dev/null
+++ b/app/api/onboarding/source/route.ts
@@ -0,0 +1,40 @@
+import { NextRequest } from 'next/server';
+import { auth } from '@/lib/auth';
+import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
+import { rateLimit } from '@/lib/rate-limit';
+import { setSelfReportedSource } from '@/lib/analytics/record';
+import { isAcquisitionChannel } from '@/lib/analytics/cookies';
+import { isProductAnalyticsEnabled } from '@/lib/feature-flags';
+
+// "How did you hear about us?", answered on the first onboarding screen.
+//
+// It is stored beside the cookie-derived channel rather than instead of it. The
+// cookie is precise but loses cross-device visits and cleared browsers; the
+// answer survives both, and it is the only thing that can name a channel no UTM
+// tag ever carries, like being told about it by a friend.
+export async function POST(request: NextRequest) {
+ const session = await auth();
+ if (!session?.user?.id) {
+ return apiErrors.unauthorized();
+ }
+
+ const limited = await rateLimit(request, 'onboarding-complete');
+ if (limited) return limited;
+
+ if (!isProductAnalyticsEnabled()) {
+ return apiErrors.badRequest('Analytics are disabled by this host');
+ }
+
+ const body = await request.json().catch(() => null);
+ const source = body?.source;
+ if (!isAcquisitionChannel(source)) {
+ return apiErrors.badRequest('Unknown source');
+ }
+
+ const note = typeof body?.note === 'string' ? body.note : null;
+
+ await setSelfReportedSource({ userId: session.user.id, selfReported: source, note });
+
+ const response = successResponse({ recorded: true });
+ return withCacheControl(response, 'private, no-store');
+}
diff --git a/app/api/projects/[projectId]/videos/[videoId]/share/route.ts b/app/api/projects/[projectId]/videos/[videoId]/share/route.ts
index 52d5fca..66d3971 100644
--- a/app/api/projects/[projectId]/videos/[videoId]/share/route.ts
+++ b/app/api/projects/[projectId]/videos/[videoId]/share/route.ts
@@ -8,6 +8,7 @@ import { db } from '@/lib/db';
import { rateLimit } from '@/lib/rate-limit';
import { MAX_SHARE_PASSWORD_LENGTH } from '@/lib/share-links';
import { logError } from '@/lib/logger';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
type RouteParams = { params: Promise<{ projectId: string; videoId: string }> };
@@ -141,7 +142,11 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
}
const { projectId, videoId } = await params;
- const { error } = await requireShareManagementAccess(projectId, videoId, session.user.id);
+ const { error, video } = await requireShareManagementAccess(
+ projectId,
+ videoId,
+ session.user.id
+ );
if (error) return error;
const body = await request.json().catch(() => ({}));
@@ -244,6 +249,14 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.internalError('Failed to create video share link');
}
+ // Keyed on the link id, so re-issuing the token for a link that already
+ // exists updates the row and records nothing: the share was created once.
+ await recordEvent({
+ name: 'SHARE_LINK_CREATED',
+ dedupeKey: eventKey('SHARE_LINK_CREATED', link.id),
+ userId: video?.project.ownerId ?? null,
+ });
+
const response = successResponse(serializeShareLink(request, videoId, link));
return withCacheControl(response, 'private, no-store');
diff --git a/app/api/projects/[projectId]/videos/route.ts b/app/api/projects/[projectId]/videos/route.ts
index a56fa73..cad3a12 100644
--- a/app/api/projects/[projectId]/videos/route.ts
+++ b/app/api/projects/[projectId]/videos/route.ts
@@ -8,6 +8,7 @@ import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response
import { verifyBunnyUploadToken } from '@/lib/bunny-upload-token';
import { finalizeR2VideoUpload } from '@/lib/r2-video-finalize';
import { logError } from '@/lib/logger';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
type RouteParams = { params: Promise<{ projectId: string }> };
@@ -268,6 +269,12 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
}).catch((err) => logError('Notification failed:', err));
}
+ await recordEvent({
+ name: 'VIDEO_ADDED',
+ dedupeKey: eventKey('VIDEO_ADDED', video.id),
+ userId: project.ownerId,
+ });
+
const response = successResponse(video, 201);
return withCacheControl(response, 'private, no-store');
} catch (error) {
diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts
index 3c28ae0..f35ad8d 100644
--- a/app/api/projects/route.ts
+++ b/app/api/projects/route.ts
@@ -7,6 +7,7 @@ import { buildBillingAccessWhereInput } from '@/lib/billing';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import { DEFAULT_COMMENT_TAGS } from '@/lib/comment-tags';
import { logError } from '@/lib/logger';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
// GET /api/projects - List all projects for the authenticated user
export async function GET(request: NextRequest) {
@@ -187,6 +188,15 @@ export async function POST(request: NextRequest) {
return createdProject;
});
+ // Attributed to the workspace owner rather than the caller: the funnel asks
+ // which account is progressing, and a team member creating a project moves
+ // the owner's account, not their own.
+ await recordEvent({
+ name: 'PROJECT_CREATED',
+ dedupeKey: eventKey('PROJECT_CREATED', project.id),
+ userId: workspace.ownerId,
+ });
+
const response = successResponse(project, 201);
return withCacheControl(response, 'private, no-store');
} catch (error) {
diff --git a/app/api/versions/[versionId]/comments/route.ts b/app/api/versions/[versionId]/comments/route.ts
index cf889f7..b236f1b 100644
--- a/app/api/versions/[versionId]/comments/route.ts
+++ b/app/api/versions/[versionId]/comments/route.ts
@@ -13,6 +13,7 @@ import {
getGuestIdentityFromRequest,
setGuestIdentityCookie,
} from '@/lib/guest-identity';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
import {
extractImageFileNameFromProxyUrl,
extractAudioFileNameFromProxyUrl,
@@ -547,6 +548,18 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
}
}
+ // Feedback arriving from outside the team is the moment this product
+ // becomes worth paying for, so it is the activation step of the funnel.
+ // Keyed on the account, not the comment: what matters is the first time an
+ // account ever received one.
+ if (isGuest) {
+ await recordEvent({
+ name: 'FIRST_GUEST_COMMENT',
+ dedupeKey: eventKey('FIRST_GUEST_COMMENT', project.workspace.ownerId),
+ userId: project.workspace.ownerId,
+ });
+ }
+
const viewerUserId = session?.user?.id ?? null;
const viewerGuestIdentityId = viewerUserId
? null
diff --git a/app/api/workspaces/route.ts b/app/api/workspaces/route.ts
index 83de26f..79ba35d 100644
--- a/app/api/workspaces/route.ts
+++ b/app/api/workspaces/route.ts
@@ -5,6 +5,7 @@ import { rateLimit } from '@/lib/rate-limit';
import { buildBillingAccessWhereInput, getWorkspaceCreationEligibility } from '@/lib/billing';
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
import { logError } from '@/lib/logger';
+import { eventKey, recordEvent } from '@/lib/analytics/record';
// GET /api/workspaces - List all workspaces for the authenticated user
export async function GET(request: NextRequest) {
@@ -136,6 +137,12 @@ export async function POST(request: NextRequest) {
},
});
+ await recordEvent({
+ name: 'WORKSPACE_CREATED',
+ dedupeKey: eventKey('WORKSPACE_CREATED', workspace.id),
+ userId: workspace.ownerId,
+ });
+
const response = successResponse(workspace, 201);
return withCacheControl(response, 'private, no-store');
} catch (error) {
diff --git a/app/onboarding/onboarding-wizard.tsx b/app/onboarding/onboarding-wizard.tsx
index c152b45..1c853e2 100644
--- a/app/onboarding/onboarding-wizard.tsx
+++ b/app/onboarding/onboarding-wizard.tsx
@@ -107,7 +107,45 @@ function ToggleButton({
// ─── Step 1: Welcome ───────────────────────────────────────────────────────────
-function StepWelcome({ userName, onNext }: { userName: string; onNext: () => void }) {
+// Asked here rather than on the registration form. The whole point of measuring
+// this funnel is the signup conversion rate, and a question added to the form
+// would move the number being measured.
+const SOURCE_OPTIONS: Array<{ value: string; label: string }> = [
+ { value: 'GITHUB', label: 'GitHub' },
+ { value: 'YOUTUBE', label: 'YouTube' },
+ { value: 'GOOGLE', label: 'A search engine' },
+ { value: 'REVIEW_LINK', label: 'A review or comparison site' },
+ { value: 'REFERRAL', label: 'Someone recommended it' },
+ { value: 'COMMUNITY', label: 'Reddit, X, Discord or a forum' },
+ { value: 'OUTBOUND', label: 'An email from us' },
+ { value: 'OTHER', label: 'Somewhere else' },
+];
+
+function StepWelcome({
+ userName,
+ askSource,
+ onNext,
+}: {
+ userName: string;
+ askSource: boolean;
+ onNext: () => void;
+}) {
+ const [source, setSource] = useState('');
+ const [note, setNote] = useState('');
+
+ const handleNext = () => {
+ // Never blocks the wizard. An unanswered or failed question costs one row in
+ // a cross-check column; a broken Get Started button costs the account.
+ if (askSource && source) {
+ void fetch('/api/onboarding/source', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ source, note: source === 'OTHER' ? note : undefined }),
+ }).catch(() => undefined);
+ }
+ onNext();
+ };
+
return (
@@ -122,7 +160,36 @@ function StepWelcome({ userName, onNext }: { userName: string; onNext: () => voi
manage versions, and streamline approvals — all in one place.
-
{/* Card 2: Fair Source (Self-hosted) */}
@@ -901,12 +902,12 @@ export function LandingPage({ isLoggedIn }: LandingPageProps) {
Your first review link takes minutes.
-
Start free trial
-
+
diff --git a/components/marketing/comparison-page.tsx b/components/marketing/comparison-page.tsx
index 7c7a431..c99660a 100644
--- a/components/marketing/comparison-page.tsx
+++ b/components/marketing/comparison-page.tsx
@@ -1,5 +1,6 @@
import Link from 'next/link';
import { ArrowRight, Github, MoveRight } from 'lucide-react';
+import { CtaLink } from '@/components/marketing/cta-link';
import { FeatureComparisonTable } from '@/components/marketing/feature-comparison-table';
import { MarketingFooter } from '@/components/marketing/marketing-footer';
import { MarketingHeader } from '@/components/marketing/marketing-header';
@@ -41,13 +42,13 @@ export function ComparisonPage({ page, isLoggedIn }: ComparisonPageProps) {
$10/month hosted plan covers your whole team and every client reviewer link.