OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): remember where a new workspace came from (#636)
Carl-Gerhard Lindesvärd8fb62e5eadc2
diff --git a/apps/public/src/app/layout.tsx b/apps/public/src/app/layout.tsxindex ab1bf0570..fec5dddd6 100644--- a/apps/public/src/app/layout.tsx+++ b/apps/public/src/app/layout.tsx@@ -6,6 +6,7 @@ import { getRootMetadata } from '@/lib/metadata';import { cn } from '@/lib/utils';import './global.css';import { OpenPanelComponent } from '@openpanel/nextjs';+import { AttributionCookie } from '@/components/attribution-cookie';import { ScrollTracker } from '@/components/scroll-tracker';const font = Geist({@@ -41,6 +42,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {<TooltipProvider>{children}</TooltipProvider></RootProvider><ScrollTracker />+ <AttributionCookie />{process.env.NEXT_PUBLIC_OP_CLIENT_ID && (<OpenPanelComponentclientId={process.env.NEXT_PUBLIC_OP_CLIENT_ID}diff --git a/apps/public/src/components/attribution-cookie.tsx b/apps/public/src/components/attribution-cookie.tsxnew file mode 100644index 000000000..03afb7ff4--- /dev/null+++ b/apps/public/src/components/attribution-cookie.tsx@@ -0,0 +1,77 @@+'use client';++import { useEffect } from 'react';++// Read by the dashboard when a workspace is created; the key names are its+// contract (`zOrganizationAttribution` in the onboarding constants).+const COOKIE_NAME = 'op_attribution';+const COOKIE_MAX_AGE_MS = 90 * 24 * 60 * 60 * 1000;+const COOKIE_DOMAIN = 'openpanel.dev';+const UTM_KEYS = {+ utm_source: 'utmSource',+ utm_medium: 'utmMedium',+ utm_campaign: 'utmCampaign',+ utm_content: 'utmContent',+ utm_term: 'utmTerm',+} as const;++// A referrer's query string can carry the referring site's own tokens and+// adds nothing to attribution.+function withoutQuery(url: string) {+ try {+ const parsed = new URL(url);+ return `${parsed.origin}${parsed.pathname}`;+ } catch {+ return url;+ }+}++function readFirstTouch() {+ const params = new URLSearchParams(window.location.search);+ const value: Record<string, string> = {+ landingPage: window.location.pathname,+ firstSeenAt: new Date().toISOString(),+ };+ if (document.referrer) {+ value.referrer = withoutQuery(document.referrer);+ }+ for (const [param, key] of Object.entries(UTM_KEYS)) {+ const utm = params.get(param);+ if (utm) {+ value[key] = utm;+ }+ }+ return value;+}++async function rememberFirstTouch() {+ if (await cookieStore.get(COOKIE_NAME)) {+ return;+ }+ const isProductionHost = window.location.hostname.endsWith(COOKIE_DOMAIN);+ await cookieStore.set({+ name: COOKIE_NAME,+ value: encodeURIComponent(JSON.stringify(readFirstTouch())),+ expires: Date.now() + COOKIE_MAX_AGE_MS,+ path: '/',+ domain: isProductionHost ? COOKIE_DOMAIN : null,+ sameSite: 'lax',+ });+}++/**+ * Remembers the first visit to openpanel.dev (referrer, landing page, UTM) in+ * a cookie shared with the dashboard, so a sign-up days later can still be+ * traced back to the channel that brought it. Browsers without the Cookie+ * Store API are left unattributed.+ */+export function AttributionCookie() {+ useEffect(() => {+ if (!('cookieStore' in window)) {+ return;+ }+ rememberFirstTouch().catch(() => undefined);+ }, []);++ return null;+}diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsxindex 5cdd38cbc..f1e8a2b3a 100644--- a/apps/start/src/routes/_steps.onboarding.project.tsx+++ b/apps/start/src/routes/_steps.onboarding.project.tsx@@ -33,6 +33,7 @@ import { Combobox } from '@/components/ui/combobox';import { Label } from '@/components/ui/label';import { rememberOnboardingKeys } from '@/hooks/use-client-secret';import { handleError, useTRPC } from '@/integrations/trpc/react';+import { readAttribution } from '@/utils/attribution';import { cn } from '@/utils/cn';import {failureReason,@@ -227,7 +228,11 @@ function Component() {...values}) => {if (createsWorkspace) {- mutation.mutate({ ...values, organization });+ mutation.mutate({+ ...values,+ organization,+ attribution: readAttribution(),+ });return;}if (!organizationId) {diff --git a/apps/start/src/utils/attribution.test.ts b/apps/start/src/utils/attribution.test.tsnew file mode 100644index 000000000..4bb3b0126--- /dev/null+++ b/apps/start/src/utils/attribution.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';+import { readAttribution, toFirstTouchProperties } from './attribution';++function cookieHeader(value: unknown) {+ return `theme=dark; op_attribution=${encodeURIComponent(JSON.stringify(value))}; other=1`;+}++describe('readAttribution', () => {+ it('is undefined without the cookie', () => {+ expect(readAttribution('')).toBeUndefined();+ expect(readAttribution('theme=dark')).toBeUndefined();+ });++ it('parses the first touch the marketing site recorded', () => {+ expect(+ readAttribution(+ cookieHeader({+ referrer: 'https://www.reddit.com/r/selfhosted/',+ landingPage: '/compare/mixpanel',+ utmSource: 'reddit',+ firstSeenAt: '2026-11-01T10:00:00.000Z',+ })+ )+ ).toEqual({+ referrer: 'https://www.reddit.com/r/selfhosted/',+ landingPage: '/compare/mixpanel',+ utmSource: 'reddit',+ firstSeenAt: '2026-11-01T10:00:00.000Z',+ });+ });++ it('ignores a cookie that is not valid attribution', () => {+ expect(readAttribution('op_attribution=not-json')).toBeUndefined();+ expect(readAttribution(cookieHeader('a string'))).toBeUndefined();+ });++ it('drops a bad field but keeps the rest of the first touch', () => {+ expect(+ readAttribution(+ cookieHeader({+ referrer: 'x'.repeat(600),+ utmSource: 'reddit',+ firstSeenAt: 'yesterday',+ })+ )+ ).toEqual({ utmSource: 'reddit' });+ });+});++describe('toFirstTouchProperties', () => {+ it('flattens the channel fields and skips empty ones', () => {+ expect(+ toFirstTouchProperties({+ referrer: 'https://news.ycombinator.com/',+ landingPage: '/',+ utmCampaign: 'launch',+ firstSeenAt: '2026-11-01T10:00:00.000Z',+ })+ ).toEqual({+ first_touch_referrer: 'https://news.ycombinator.com/',+ first_touch_landing_page: '/',+ first_touch_utm_campaign: 'launch',+ });+ expect(toFirstTouchProperties(undefined)).toEqual({});+ });+});diff --git a/apps/start/src/utils/attribution.ts b/apps/start/src/utils/attribution.tsnew file mode 100644index 000000000..8f6f249a2--- /dev/null+++ b/apps/start/src/utils/attribution.ts@@ -0,0 +1,64 @@+import {+ ATTRIBUTION_COOKIE_NAME,+ type IOrganizationAttribution,+ zOrganizationAttribution,+} from '@openpanel/core/modules/onboarding/onboarding.constants';++function readCookie(cookies: string, name: string): string | undefined {+ const prefix = `${name}=`;+ const match = cookies+ .split(';')+ .map((cookie) => cookie.trim())+ .find((cookie) => cookie.startsWith(prefix));+ return match?.slice(prefix.length);+}++function browserCookies(): string {+ return typeof document === 'undefined' ? '' : document.cookie;+}++/** The first touch on openpanel.dev, if the marketing site recorded one. */+export function readAttribution(+ cookies = browserCookies()+): IOrganizationAttribution | undefined {+ const raw = readCookie(cookies, ATTRIBUTION_COOKIE_NAME);+ if (!raw) {+ return undefined;+ }+ try {+ const parsed = zOrganizationAttribution.safeParse(+ JSON.parse(decodeURIComponent(raw))+ );+ return parsed.success ? parsed.data : undefined;+ } catch {+ return undefined;+ }+}++/** Flat `first_touch_*` properties so funnel events can break down by channel. */+export function toFirstTouchProperties(+ attribution: IOrganizationAttribution | undefined+): Record<string, string> {+ if (!attribution) {+ return {};+ }+ const properties: Record<string, string> = {};+ const keys = [+ 'referrer',+ 'landingPage',+ 'utmSource',+ 'utmMedium',+ 'utmCampaign',+ ] as const;+ for (const key of keys) {+ const value = attribution[key];+ if (value) {+ properties[`first_touch_${toSnakeCase(key)}`] = value;+ }+ }+ return properties;+}++function toSnakeCase(value: string) {+ return value.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);+}diff --git a/apps/start/src/utils/op.ts b/apps/start/src/utils/op.tsindex 5181a1b7e..ed5fad188 100644--- a/apps/start/src/utils/op.ts+++ b/apps/start/src/utils/op.ts@@ -1,4 +1,5 @@import { OpenPanel } from '@openpanel/web';+import { readAttribution, toFirstTouchProperties } from '@/utils/attribution';import { shouldSendAnalyticsEvent } from '@/utils/op-filter';const clientId = import.meta.env.VITE_OP_CLIENT_ID;@@ -15,3 +16,7 @@ export const op = new OpenPanel({// enabled: true,// }});++// Every funnel event carries the marketing first touch, so sign-ups and+// activations can be broken down by the channel that brought them.+op.setGlobalProperties(toFirstTouchProperties(readAttribution()));diff --git a/packages/core/src/modules/onboarding/onboarding.constants.ts b/packages/core/src/modules/onboarding/onboarding.constants.tsindex 93f9fc7b3..1a78714ce 100644--- a/packages/core/src/modules/onboarding/onboarding.constants.ts+++ b/packages/core/src/modules/onboarding/onboarding.constants.ts@@ -1,10 +1,47 @@import { z } from 'zod';import { zTimezone } from '../organization/organization.constants';+// Set by openpanel.dev on the first visit, readable by the dashboard because+// both share the registrable domain. The value is URL-encoded JSON matching+// `zOrganizationAttribution`.+export const ATTRIBUTION_COOKIE_NAME = 'op_attribution';+const ATTRIBUTION_FIELD_MAX_LENGTH = 512;+// One bad field (oversized, wrong type) drops that field, not the whole+// first touch.+const zAttributionField = z+ .string()+ .trim()+ .max(ATTRIBUTION_FIELD_MAX_LENGTH)+ .optional()+ .catch(undefined);++export const zOrganizationAttribution = z.object({+ referrer: zAttributionField,+ landingPage: zAttributionField,+ utmSource: zAttributionField,+ utmMedium: zAttributionField,+ utmCampaign: zAttributionField,+ utmContent: zAttributionField,+ utmTerm: zAttributionField,+ firstSeenAt: z.string().datetime().optional().catch(undefined),+});+export type IOrganizationAttribution = z.infer<typeof zOrganizationAttribution>;++// What ends up on the organization row: the cookie plus the referrer resolved+// to the same name/type the event pipeline uses, so Postgres can group by it.+export type IOrganizationAttributionStored = {+ [Key in keyof IOrganizationAttribution]-?: string | null;+} & {+ referrerName: string | null;+ referrerType: string | null;+};+export const zOnboardingProject = z.object({organization: z.string().optional(),organizationId: z.string().optional(),+ // Only used when a new organization is created.+ attribution: zOrganizationAttribution.optional(),project: z.string().min(3, 'Use at least 3 characters'),domain: z.string().url().or(z.literal('').or(z.null())),cors: z.array(z.string()).default([]),diff --git a/packages/core/src/modules/onboarding/onboarding.service.create.test.ts b/packages/core/src/modules/onboarding/onboarding.service.create.test.tsindex d9b359e91..bb25de797 100644--- a/packages/core/src/modules/onboarding/onboarding.service.create.test.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.create.test.ts@@ -88,3 +88,49 @@ test('creates a write client for events and a read client whose token works for// Its own secret, never the write client's.expect(decoded.endsWith(result.secret)).toBe(false);});++test('stores the first touch on a new organization with the referrer resolved', async () => {+ dbMock.organization.create.mockClear();+ await createOnboardingProject(+ deps,+ {+ organization: 'Beta',+ project: 'Beta site',+ domain: 'https://beta.com',+ cors: [],+ website: true,+ app: false,+ backend: false,+ attribution: {+ referrer: 'https://www.reddit.com/r/selfhosted/comments/abc/',+ landingPage: '/compare/mixpanel',+ utmCampaign: 'launch',+ firstSeenAt: '2026-11-01T10:00:00.000Z',+ },+ },+ 'user_1'+ );++ const [call] = dbMock.organization.create.mock.calls;+ expect(call?.[0].data.attribution).toEqual({+ referrer: 'https://www.reddit.com/r/selfhosted/comments/abc/',+ referrerName: 'Reddit',+ referrerType: 'social',+ landingPage: '/compare/mixpanel',+ utmSource: null,+ utmMedium: null,+ utmCampaign: 'launch',+ utmContent: null,+ utmTerm: null,+ firstSeenAt: '2026-11-01T10:00:00.000Z',+ });+});++test('resolves the referrer from utm_source and drops an empty first touch', async () => {+ const { toStoredAttribution } = await import('./onboarding.service');+ expect(toStoredAttribution({ utmSource: 'twitter' })?.referrerName).toBe(+ 'Twitter'+ );+ expect(toStoredAttribution({})).toBeUndefined();+ expect(toStoredAttribution(undefined)).toBeUndefined();+});diff --git a/packages/core/src/modules/onboarding/onboarding.service.ts b/packages/core/src/modules/onboarding/onboarding.service.tsindex f6a9bdf4c..0c1c5b1c9 100644--- a/packages/core/src/modules/onboarding/onboarding.service.ts+++ b/packages/core/src/modules/onboarding/onboarding.service.ts@@ -4,6 +4,10 @@ import { format } from 'date-fns';import type { Logger } from '../../logger';import type { ServiceDeps, Services } from '../../services';import { hashClientSecret, newClientSecret } from '../../shared/client-secret';+import {+ getReferrerWithQuery,+ parseReferrer,+} from '../../shared/parse-referrer';import { getId } from '../../slug-id';import {runSequence,@@ -22,7 +26,11 @@ import {type OrganizationWithAdmins,} from '../organization/src/contact';import { getUserById } from '../user/user.service';-import type { IOnboardingProject } from './onboarding.constants';+import type {+ IOnboardingProject,+ IOrganizationAttribution,+ IOrganizationAttributionStored,+} from './onboarding.constants';const TRIAL_DURATION_IN_DAYS = 30;// Generous trial allowance so trialing orgs never get flagged as@@ -41,6 +49,37 @@ export async function canSkipOnboarding(return { canSkip: members > 0 };}+export function toStoredAttribution(+ attribution: IOrganizationAttribution | undefined+): IOrganizationAttributionStored | undefined {+ if (!attribution) {+ return undefined;+ }+ const hasAnyValue = Object.values(attribution).some(Boolean);+ if (!hasAnyValue) {+ return undefined;+ }++ const fromReferrer = parseReferrer(attribution.referrer);+ const fromUtm = getReferrerWithQuery(+ attribution.utmSource ? { utm_source: attribution.utmSource } : undefined+ );+ const resolved = fromReferrer.name ? fromReferrer : fromUtm;++ return {+ referrer: attribution.referrer || null,+ referrerName: resolved?.name || null,+ referrerType: resolved?.type || null,+ landingPage: attribution.landingPage || null,+ utmSource: attribution.utmSource || null,+ utmMedium: attribution.utmMedium || null,+ utmCampaign: attribution.utmCampaign || null,+ utmContent: attribution.utmContent || null,+ utmTerm: attribution.utmTerm || null,+ firstSeenAt: attribution.firstSeenAt || null,+ };+}+async function createOrGetOnboardingOrganization(deps: ServiceDeps,input: IOnboardingProject,@@ -72,6 +111,7 @@ async function createOrGetOnboardingOrganization(subscriptionStatus: 'trialing',subscriptionPeriodEventsLimit: TRIAL_EVENTS_LIMIT,timezone: input.timezone,+ attribution: toStoredAttribution(input.attribution),onboarding: '',// Equal to the id so it is unique; see code migration 26.slug: organizationId,diff --git a/packages/db/prisma/migrations/20261101120000_organization_attribution/migration.sql b/packages/db/prisma/migrations/20261101120000_organization_attribution/migration.sqlnew file mode 100644index 000000000..a2d9a51f0--- /dev/null+++ b/packages/db/prisma/migrations/20261101120000_organization_attribution/migration.sql@@ -0,0 +1,2 @@+-- First-touch marketing attribution captured at sign-up (referrer, landing page, UTM).+ALTER TABLE "organizations" ADD COLUMN "attribution" JSONB;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex d4a9e802b..4e7747f0a 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -88,6 +88,10 @@ model Organization {conversations Conversation[]timezone String?onboarding String? @default("completed")+ // First touch on openpanel.dev before sign-up (referrer, landing page, UTM),+ // so paying organizations can be traced back to the channel that brought them.+ /// [IPrismaOrganizationAttribution]+ attribution Json?// SubscriptionsubscriptionId String?diff --git a/packages/db/src/types.ts b/packages/db/src/types.tsindex 34fd414b6..613dae576 100644--- a/packages/db/src/types.ts+++ b/packages/db/src/types.ts@@ -10,6 +10,7 @@ import type { IImportConfig } from '@openpanel/core/modules/import/import.constaimport type { InsightPayload } from '@openpanel/core/modules/insight/insight.constants';import type { IIntegrationConfig } from '@openpanel/core/modules/integration/integration.constants';import type { INotificationRuleConfig } from '@openpanel/core/modules/notification/notification.constants';+import type { IOrganizationAttributionStored } from '@openpanel/core/modules/onboarding/onboarding.constants';import type { IProjectAccessGrant } from '@openpanel/core/modules/organization/organization.constants';import type { IProjectFilters } from '@openpanel/core/modules/project/project.constants';import type {@@ -25,6 +26,7 @@ declare global {type IPrismaNotificationPayload = INotificationPayload;type IPrismaProjectFilters = IProjectFilters[];type IPrismaInviteProjectAccess = IProjectAccessGrant[];+ type IPrismaOrganizationAttribution = IOrganizationAttributionStored;type IPrismaProjectInsightPayload = InsightPayload;type IPrismaWidgetOptions = IWidgetOptions;type IPrismaClickhouseEvent = IClickhouseEvent;