OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(dashboard): set the first-touch cookie server-side so every browser gets it (#637)
Carl-Gerhard Lindesvärd69e98f19b195
diff --git a/apps/public/src/app/layout.tsx b/apps/public/src/app/layout.tsxindex fec5dddd6..ab1bf0570 100644--- a/apps/public/src/app/layout.tsx+++ b/apps/public/src/app/layout.tsx@@ -6,7 +6,6 @@ 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({@@ -42,7 +41,6 @@ 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.tsxdeleted file mode 100644index 03afb7ff4..000000000--- a/apps/public/src/components/attribution-cookie.tsx+++ /dev/null@@ -1,77 +0,0 @@-'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/public/src/middleware.ts b/apps/public/src/middleware.tsindex 7edfbbe5c..8f39eeb35 100644--- a/apps/public/src/middleware.ts+++ b/apps/public/src/middleware.ts@@ -1,6 +1,90 @@import type { NextRequest } from 'next/server';import { NextResponse } from 'next/server';+// Read by the dashboard when a workspace is created; the key names are its+// contract (`zOrganizationAttribution` in the onboarding constants). Set+// server-side so every browser gets it, including those without the Cookie+// Store API.+const ATTRIBUTION_COOKIE_NAME = 'op_attribution';+const ATTRIBUTION_MAX_AGE_SECONDS = 90 * 24 * 60 * 60;+const ATTRIBUTION_COOKIE_DOMAIN = 'openpanel.dev';+const UTM_KEYS = {+ utm_source: 'utmSource',+ utm_medium: 'utmMedium',+ utm_campaign: 'utmCampaign',+ utm_content: 'utmContent',+ utm_term: 'utmTerm',+} as const;++function isOwnHost(hostname: string, requestHost: string) {+ return (+ hostname === requestHost ||+ hostname === ATTRIBUTION_COOKIE_DOMAIN ||+ hostname.endsWith(`.${ATTRIBUTION_COOKIE_DOMAIN}`)+ );+}++// A referrer's query string can carry the referring site's own tokens and+// adds nothing to attribution. A referrer on our own domain (any subdomain,+// the dashboard included) is navigation, not a source.+function externalReferrer(referer: string | null, requestHost: string) {+ if (!referer) {+ return undefined;+ }+ try {+ const parsed = new URL(referer);+ if (isOwnHost(parsed.hostname, requestHost)) {+ return undefined;+ }+ return `${parsed.origin}${parsed.pathname}`;+ } catch {+ return undefined;+ }+}++function readFirstTouch(request: NextRequest) {+ const { pathname, searchParams, hostname } = request.nextUrl;+ const value: Record<string, string> = {+ landingPage: pathname,+ firstSeenAt: new Date().toISOString(),+ };+ const referrer = externalReferrer(request.headers.get('referer'), hostname);+ if (referrer) {+ value.referrer = referrer;+ }+ for (const [param, key] of Object.entries(UTM_KEYS)) {+ const utm = searchParams.get(param);+ if (utm) {+ value[key] = utm;+ }+ }+ return value;+}++/**+ * 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. Later visits never overwrite it.+ */+function rememberFirstTouch(request: NextRequest, response: NextResponse) {+ if (request.cookies.has(ATTRIBUTION_COOKIE_NAME)) {+ return;+ }+ const { hostname, protocol } = request.nextUrl;+ const isProductionHost = hostname.endsWith(ATTRIBUTION_COOKIE_DOMAIN);+ // Next URL-encodes the value itself; the dashboard decodes it once.+ response.cookies.set({+ name: ATTRIBUTION_COOKIE_NAME,+ value: JSON.stringify(readFirstTouch(request)),+ maxAge: ATTRIBUTION_MAX_AGE_SECONDS,+ path: '/',+ domain: isProductionHost ? ATTRIBUTION_COOKIE_DOMAIN : undefined,+ sameSite: 'lax',+ secure: protocol === 'https:',+ httpOnly: false,+ });+}+export function middleware(request: NextRequest) {const { pathname } = request.nextUrl;if (pathname.endsWith('.md')) {@@ -9,9 +93,15 @@ export function middleware(request: NextRequest) {url.searchParams.set('path', pathname.slice(0, -3));return NextResponse.rewrite(url);}- return NextResponse.next();+ const response = NextResponse.next();+ rememberFirstTouch(request, response);+ return response;}export const config = {- matcher: ['/((?!_next|api|favicon|robots|sitemap|og).*\\.md)'],+ matcher: [+ // Pages: everything without a file extension, except Next internals.+ '/((?!_next|api|favicon|robots|sitemap|og|.*\\.[a-zA-Z0-9]+$).*)',+ '/((?!_next|api|favicon|robots|sitemap|og).*\\.md)',+ ],};