Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(growth): expand www middleware to /dashboard and /docs (Phase 1 - instrumentation only) (#43413)

Sean Oliver8ebbad3a5b9b
diff --git a/apps/www/middleware.test.ts b/apps/www/middleware.test.ts
new file mode 100644
index 00000000000..de465560ef7
--- /dev/null
+++ b/apps/www/middleware.test.ts
@@ -0,0 +1,135 @@
+import { NextRequest } from 'next/server'
+import { describe, expect, it } from 'vitest'
+
+import { FIRST_REFERRER_COOKIE_NAME, MW_DIAG_COOKIE_NAME } from 'common/first-referrer-cookie'
+
+import { middleware } from './middleware'
+
+function makeRequest(
+ url: string,
+ { referer, hasCookie }: { referer?: string; hasCookie?: boolean } = {}
+): NextRequest {
+ const req = new NextRequest(new URL(url, 'https://supabase.com'), {
+ headers: referer ? { referer } : {},
+ })
+ if (hasCookie) {
+ req.cookies.set(FIRST_REFERRER_COOKIE_NAME, 'existing')
+ }
+ return req
+}
+
+function parseDiagCookie(value: string) {
+ const params = new URLSearchParams(value)
+ return {
+ hit: params.get('hit') === '1',
+ would_stamp: params.get('would_stamp') === '1',
+ has_cookie: params.get('has_cookie') === '1',
+ }
+}
+
+describe('www middleware', () => {
+ describe('cookie stamping on normal paths', () => {
+ it('stamps cookie for external referrer on www path', () => {
+ const req = makeRequest('/pricing', { referer: 'https://google.com' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(FIRST_REFERRER_COOKIE_NAME)).toBeDefined()
+ })
+
+ it('does not stamp cookie for internal referrer', () => {
+ const req = makeRequest('/pricing', { referer: 'https://supabase.com/docs' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(FIRST_REFERRER_COOKIE_NAME)).toBeUndefined()
+ })
+ })
+
+ describe('dashboard/docs diagnostic guard', () => {
+ it('sets diagnostic cookie on /dashboard paths', () => {
+ const req = makeRequest('/dashboard/project/123', { referer: 'https://google.com' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(MW_DIAG_COOKIE_NAME)).toBeDefined()
+ })
+
+ it('sets diagnostic cookie on /docs paths', () => {
+ const req = makeRequest('/docs/guides/auth', { referer: 'https://google.com' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(MW_DIAG_COOKIE_NAME)).toBeDefined()
+ })
+
+ it('encodes hit=1 in diagnostic cookie', () => {
+ const req = makeRequest('/dashboard/project/123', { referer: 'https://google.com' })
+ const res = middleware(req)
+ const raw = res.cookies.get(MW_DIAG_COOKIE_NAME)?.value ?? ''
+ const diag = parseDiagCookie(raw)
+
+ expect(diag.hit).toBe(true)
+ })
+
+ it('encodes would_stamp=1 for external referrer with no existing cookie', () => {
+ const req = makeRequest('/dashboard/project/123', { referer: 'https://google.com' })
+ const res = middleware(req)
+ const raw = res.cookies.get(MW_DIAG_COOKIE_NAME)?.value ?? ''
+ const diag = parseDiagCookie(raw)
+
+ expect(diag.would_stamp).toBe(true)
+ expect(diag.has_cookie).toBe(false)
+ })
+
+ it('encodes would_stamp=0 for direct navigation (no referrer)', () => {
+ const req = makeRequest('/dashboard/project/123')
+ const res = middleware(req)
+ const raw = res.cookies.get(MW_DIAG_COOKIE_NAME)?.value ?? ''
+ const diag = parseDiagCookie(raw)
+
+ expect(diag.would_stamp).toBe(false)
+ expect(diag.has_cookie).toBe(false)
+ })
+
+ it('encodes would_stamp=0 for internal referrer', () => {
+ const req = makeRequest('/dashboard/project/123', {
+ referer: 'https://supabase.com/pricing',
+ })
+ const res = middleware(req)
+ const raw = res.cookies.get(MW_DIAG_COOKIE_NAME)?.value ?? ''
+ const diag = parseDiagCookie(raw)
+
+ expect(diag.would_stamp).toBe(false)
+ })
+
+ it('encodes has_cookie=1 when first-referrer cookie is already present', () => {
+ const req = makeRequest('/dashboard/project/123', {
+ referer: 'https://google.com',
+ hasCookie: true,
+ })
+ const res = middleware(req)
+ const raw = res.cookies.get(MW_DIAG_COOKIE_NAME)?.value ?? ''
+ const diag = parseDiagCookie(raw)
+
+ expect(diag.has_cookie).toBe(true)
+ })
+
+ it('does NOT stamp first-referrer cookie on /dashboard paths', () => {
+ const req = makeRequest('/dashboard/project/123', { referer: 'https://google.com' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(FIRST_REFERRER_COOKIE_NAME)).toBeUndefined()
+ })
+
+ it('does NOT stamp first-referrer cookie on /docs paths', () => {
+ const req = makeRequest('/docs/guides/auth', { referer: 'https://google.com' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(FIRST_REFERRER_COOKIE_NAME)).toBeUndefined()
+ })
+
+ it('does NOT set diagnostic cookie on normal www paths', () => {
+ const req = makeRequest('/pricing', { referer: 'https://google.com' })
+ const res = middleware(req)
+
+ expect(res.cookies.get(MW_DIAG_COOKIE_NAME)).toBeUndefined()
+ })
+ })
+})
diff --git a/apps/www/middleware.ts b/apps/www/middleware.ts
index 27c61a108c1..b7d94f5f28e 100644
--- a/apps/www/middleware.ts
+++ b/apps/www/middleware.ts
@@ -1,18 +1,42 @@
-import { stampFirstReferrerCookie } from 'common/first-referrer-cookie'
+import {
+ FIRST_REFERRER_COOKIE_NAME,
+ MW_DIAG_COOKIE_NAME,
+ shouldRefreshCookie,
+ stampFirstReferrerCookie,
+} from 'common/first-referrer-cookie'
import { NextResponse, type NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const response = NextResponse.next()
+
+ const pathname = request.nextUrl.pathname
+ const isDashboardOrDocs = pathname.startsWith('/dashboard') || pathname.startsWith('/docs')
+
+ if (isDashboardOrDocs) {
+ // Phase 1: diagnostic only — no permanent cookie mutations.
+ // Compute what Phase 2 would do and encode it in a short-lived cookie
+ // readable by client-side telemetry so we get PostHog-visible data.
+ // This also tests the Set-Cookie mutation path that Phase 2 will use.
+ const referrer = request.headers.get('referer') ?? ''
+ const hasCookie = request.cookies.has(FIRST_REFERRER_COOKIE_NAME)
+ const { stamp: wouldStamp } = shouldRefreshCookie(hasCookie, { referrer, url: request.url })
+
+ response.cookies.set(
+ MW_DIAG_COOKIE_NAME,
+ `hit=1&would_stamp=${wouldStamp ? '1' : '0'}&has_cookie=${hasCookie ? '1' : '0'}`,
+ { path: '/', sameSite: 'lax', maxAge: 60 }
+ )
+ return response
+ }
+
stampFirstReferrerCookie(request, response)
return response
}
export const config = {
matcher: [
- // Match all paths except Next.js internals, static files, and proxied app paths.
- // - _next/data: client-side navigation JSON fetches (MUST exclude to prevent full page reloads)
- // - dashboard: Studio app (proxied via multi-zone, has its own cookie stamping in proxy.ts)
- // - docs: Docs app (proxied via multi-zone in prod, has its own middleware for cookie stamping)
- '/((?!api|_next/static|_next/image|_next/data|dashboard|docs|favicon.ico|__nextjs).*)',
+ // Match all paths except Next.js internals and static files.
+ // MUST exclude _next/data to prevent full page reloads in multi-zone apps.
+ '/((?!api|_next/static|_next/image|_next/data|favicon.ico|__nextjs).*)',
],
}
diff --git a/packages/common/first-referrer-cookie.test.ts b/packages/common/first-referrer-cookie.test.ts
index ce308e2d244..18f54214620 100644
--- a/packages/common/first-referrer-cookie.test.ts
+++ b/packages/common/first-referrer-cookie.test.ts
@@ -3,9 +3,11 @@ import { describe, expect, it } from 'vitest'
import {
buildFirstReferrerData,
FIRST_REFERRER_COOKIE_NAME,
+ MW_DIAG_COOKIE_NAME,
hasPaidSignals,
isExternalReferrer,
parseFirstReferrerCookie,
+ parseMwDiagCookie,
serializeFirstReferrerCookie,
shouldRefreshCookie,
} from './first-referrer-cookie'
@@ -167,6 +169,71 @@ describe('first-referrer-cookie', () => {
})
})
+ describe('parseMwDiagCookie', () => {
+ it('parses well-formed value with would_stamp=1 and has_cookie=0', () => {
+ const header = `${MW_DIAG_COOKIE_NAME}=hit=1&would_stamp=1&has_cookie=0`
+ expect(parseMwDiagCookie(header)).toEqual({
+ hit: true,
+ would_stamp: true,
+ has_existing_cookie: false,
+ })
+ })
+
+ it('parses well-formed value with would_stamp=0 and has_cookie=1', () => {
+ const header = `${MW_DIAG_COOKIE_NAME}=hit=1&would_stamp=0&has_cookie=1`
+ expect(parseMwDiagCookie(header)).toEqual({
+ hit: true,
+ would_stamp: false,
+ has_existing_cookie: true,
+ })
+ })
+
+ it('returns null when hit=0', () => {
+ const header = `${MW_DIAG_COOKIE_NAME}=hit=0&would_stamp=1&has_cookie=1`
+ expect(parseMwDiagCookie(header)).toBeNull()
+ })
+
+ it('returns object with would_stamp: false when would_stamp key is missing', () => {
+ const header = `${MW_DIAG_COOKIE_NAME}=hit=1&has_cookie=1`
+ expect(parseMwDiagCookie(header)).toEqual({
+ hit: true,
+ would_stamp: false,
+ has_existing_cookie: true,
+ })
+ })
+
+ it('returns object with has_existing_cookie: false when has_cookie key is missing', () => {
+ const header = `${MW_DIAG_COOKIE_NAME}=hit=1&would_stamp=1`
+ expect(parseMwDiagCookie(header)).toEqual({
+ hit: true,
+ would_stamp: true,
+ has_existing_cookie: false,
+ })
+ })
+
+ it('returns null for empty string input', () => {
+ expect(parseMwDiagCookie('')).toBeNull()
+ })
+
+ it('returns null when cookie is not present in header', () => {
+ expect(parseMwDiagCookie('session=abc123; theme=dark')).toBeNull()
+ })
+
+ it('returns null for garbage value', () => {
+ const header = `${MW_DIAG_COOKIE_NAME}=not-a-valid-query-string`
+ expect(parseMwDiagCookie(header)).toBeNull()
+ })
+
+ it('parses correct cookie from header with multiple cookies', () => {
+ const header = `session=abc123; ${MW_DIAG_COOKIE_NAME}=hit=1&would_stamp=1&has_cookie=0; theme=dark`
+ expect(parseMwDiagCookie(header)).toEqual({
+ hit: true,
+ would_stamp: true,
+ has_existing_cookie: false,
+ })
+ })
+ })
+
describe('shouldRefreshCookie', () => {
it('stamps when no cookie and external referrer', () => {
expect(
diff --git a/packages/common/first-referrer-cookie.ts b/packages/common/first-referrer-cookie.ts
index f45d4db782d..c7a7cb50705 100644
--- a/packages/common/first-referrer-cookie.ts
+++ b/packages/common/first-referrer-cookie.ts
@@ -47,6 +47,13 @@ interface MiddlewareResponse {
export const FIRST_REFERRER_COOKIE_NAME = '_sb_first_referrer'
+/**
+ * Short-lived (60s) diagnostic cookie written by www middleware on /dashboard and /docs paths.
+ * Encodes: hit=1&would_stamp={0|1}&has_cookie={0|1}
+ * Read by Studio telemetry to report middleware reach and attribution signals to PostHog.
+ */
+export const MW_DIAG_COOKIE_NAME = '_sb_mw_diag'
+
/** 365 days in seconds */
export const FIRST_REFERRER_COOKIE_MAX_AGE = 365 * 24 * 60 * 60
@@ -262,6 +269,44 @@ export function stampFirstReferrerCookie(
})
}
+// ---------------------------------------------------------------------------
+// Middleware diagnostic cookie — parse (client-side)
+// ---------------------------------------------------------------------------
+
+export interface MwDiagData {
+ hit: boolean
+ would_stamp: boolean
+ has_existing_cookie: boolean
+}
+
+/**
+ * Parse the short-lived middleware diagnostic cookie written by www middleware
+ * on /dashboard and /docs paths. Returns null if the cookie is absent or malformed.
+ */
+export function parseMwDiagCookie(cookieHeader: string): MwDiagData | null {
+ try {
+ const cookies = cookieHeader.split(';')
+ const match = cookies
+ .map((c) => c.trim())
+ .find((c) => c.startsWith(`${MW_DIAG_COOKIE_NAME}=`))
+
+ if (!match) return null
+
+ const value = match.slice(`${MW_DIAG_COOKIE_NAME}=`.length)
+ const params = new URLSearchParams(value)
+
+ if (params.get('hit') !== '1') return null
+
+ return {
+ hit: true,
+ would_stamp: params.get('would_stamp') === '1',
+ has_existing_cookie: params.get('has_cookie') === '1',
+ }
+ } catch {
+ return null
+ }
+}
+
// ---------------------------------------------------------------------------
// Parse cookie from document.cookie header (client-side)
// ---------------------------------------------------------------------------
diff --git a/packages/common/telemetry.tsx b/packages/common/telemetry.tsx
index 0a0df847c54..b9c2045025e 100644
--- a/packages/common/telemetry.tsx
+++ b/packages/common/telemetry.tsx
@@ -12,8 +12,8 @@ import { hasConsented, useConsentState } from './consent-state'
import { IS_PLATFORM, IS_PROD, LOCAL_STORAGE_KEYS } from './constants'
import { useFeatureFlags } from './feature-flags'
import { post } from './fetchWrappers'
-import type { FirstReferrerData } from './first-referrer-cookie'
-import { isExternalReferrer, parseFirstReferrerCookie } from './first-referrer-cookie'
+import type { FirstReferrerData, MwDiagData } from './first-referrer-cookie'
+import { isExternalReferrer, parseFirstReferrerCookie, parseMwDiagCookie } from './first-referrer-cookie'
import { ensurePlatformSuffix, isBrowser } from './helpers'
import { useParams, useTelemetryCookie } from './hooks'
import { posthogClient, type ClientTelemetryEvent } from './posthog-client'
@@ -109,6 +109,7 @@ interface HandlePageTelemetryOptions {
ref?: string
telemetryDataOverride?: SharedTelemetryData
firstReferrerData?: FirstReferrerData | null
+ mwDiagData?: MwDiagData | null
}
function handlePageTelemetry({
@@ -119,6 +120,7 @@ function handlePageTelemetry({
ref,
telemetryDataOverride,
firstReferrerData,
+ mwDiagData,
}: HandlePageTelemetryOptions) {
// Send to PostHog client-side (only in browser)
if (typeof window !== 'undefined') {
@@ -223,6 +225,13 @@ function handlePageTelemetry({
first_referrer_cookie_present: firstReferrerCookiePresent,
first_referrer_cookie_consumed: firstReferrerCookieConsumed,
}),
+ // Phase 1 middleware diagnostic: present only when _sb_mw_diag cookie was found
+ // (i.e., the request was routed through www middleware on /dashboard or /docs)
+ ...(mwDiagData && {
+ mw_diag_hit: mwDiagData.hit,
+ mw_diag_would_stamp: mwDiagData.would_stamp,
+ mw_diag_has_existing_cookie: mwDiagData.has_existing_cookie,
+ }),
})
}
@@ -336,10 +345,12 @@ export const PageTelemetry = ({
hasAcceptedConsent &&
!hasSentInitialPageTelemetryRef.current
) {
- // Read the edge-set first-referrer cookie (cross-app handoff)
- const firstReferrerData = parseFirstReferrerCookie(document.cookie)
+ // Read the edge-set cookies (cross-app handoff)
+ const cookieHeader = document.cookie
+ const firstReferrerData = parseFirstReferrerCookie(cookieHeader)
+ const mwDiagData = parseMwDiagCookie(cookieHeader)
- const cookies = document.cookie.split(';')
+ const cookies = cookieHeader.split(';')
const telemetryCookieValue = cookies
.map((cookie) => cookie.trim())
.find((cookie) => cookie.startsWith(`${TELEMETRY_DATA}=`))
@@ -358,6 +369,7 @@ export const PageTelemetry = ({
ref,
telemetryDataOverride: telemetryData,
firstReferrerData,
+ mwDiagData,
})
} catch (error) {
if (!IS_PROD) {
@@ -370,6 +382,7 @@ export const PageTelemetry = ({
slug,
ref,
firstReferrerData,
+ mwDiagData,
})
} finally {
clearTelemetryDataCookie()
@@ -382,6 +395,7 @@ export const PageTelemetry = ({
slug,
ref,
firstReferrerData,
+ mwDiagData,
})
}