Skip to content

Open source alternative to Semrush and Ahrefs

Ask before optional tracking where opt-in is required (#942)

Ben Senescub6e0fd1ad4db
diff --git a/src/client/components/PrivacyChoices.tsx b/src/client/components/PrivacyChoices.tsx
new file mode 100644
index 00000000..0a41ada0
--- /dev/null
+++ b/src/client/components/PrivacyChoices.tsx
@@ -0,0 +1,136 @@
+import { useQuery } from "@tanstack/react-query";
+import * as React from "react";
+import { toast } from "sonner";
+import { z } from "zod";
+import {
+ identifyAnalyticsUser,
+ resetAnalyticsUser,
+ startAnalyticsCapture,
+ stopAnalyticsCapture,
+} from "@/client/lib/posthog";
+import { authClient, useSession } from "@/lib/auth-client";
+import { isHostedClientAuthMode } from "@/lib/auth-mode";
+import { getActiveOrganizationId } from "@/lib/auth-session";
+import {
+ PRIVACY_CHOICES_CHANGED_EVENT,
+ defaultPrivacyChoices,
+ effectivePrivacyChoices,
+ hasGlobalPrivacyControl,
+ readPrivacyCookie,
+ savePrivacyChoices,
+ type PrivacyChoices,
+} from "@/shared/privacy-choices";
+
+const privacyRegionSchema = z.object({ optIn: z.boolean() });
+
+// The saved choice is a cookie shared with other tabs and openseo.so, so it is
+// read fresh on every render instead of cached: a stale copy in one tab would
+// write the opposite choice back to the account after a choice in another.
+function subscribeToPrivacyCookie(onChange: () => void) {
+ window.addEventListener(PRIVACY_CHOICES_CHANGED_EVENT, onChange);
+ window.addEventListener("focus", onChange);
+ return () => {
+ window.removeEventListener(PRIVACY_CHOICES_CHANGED_EVENT, onChange);
+ window.removeEventListener("focus", onChange);
+ };
+}
+
+const readCookies = () => document.cookie;
+
+/** Whether the visitor's location requires opt-in; true if the lookup fails. */
+function usePrivacyRegion(enabled: boolean) {
+ const region = useQuery({
+ queryKey: ["privacy-region"],
+ queryFn: async () => {
+ const response = await fetch("/api/privacy-region");
+ if (!response.ok) throw new Error(`privacy region: ${response.status}`);
+ return privacyRegionSchema.parse(await response.json());
+ },
+ enabled,
+ staleTime: Infinity,
+ });
+ return region.isError ? true : region.data?.optIn;
+}
+
+/** Current optional-tracking choices for this browser, or null while the
+ * location-based defaults are still loading. Hosted mode only. */
+export function usePrivacyChoices() {
+ const isHosted = isHostedClientAuthMode();
+ const { data: session } = useSession();
+ const cookies = React.useSyncExternalStore(
+ subscribeToPrivacyCookie,
+ readCookies,
+ );
+ const saved = React.useMemo(() => readPrivacyCookie(cookies), [cookies]);
+ const regionOptIn = usePrivacyRegion(isHosted && saved === null);
+
+ const optIn = saved ? false : regionOptIn;
+ if (!isHosted || optIn === undefined) return null;
+
+ // A browser without a saved choice still honors an analytics opt-out the
+ // user made on another device (stored on the account).
+ const accountOptedOut = session?.user?.analyticsOptedOut === true;
+ const fallback = accountOptedOut
+ ? { ...defaultPrivacyChoices(optIn), analytics: false }
+ : null;
+
+ return effectivePrivacyChoices({
+ saved: saved ?? fallback,
+ optIn,
+ globalPrivacyControl: hasGlobalPrivacyControl(),
+ });
+}
+
+/** Saves the browser choice (shared with openseo.so) and mirrors the analytics
+ * choice onto the account so server-side analytics follows it. */
+export async function updatePrivacyChoices(
+ next: PrivacyChoices,
+ signedIn: boolean,
+) {
+ savePrivacyChoices(next);
+ if (!signedIn) return;
+ const result = await authClient.updateUser({
+ analyticsOptedOut: !next.analytics,
+ });
+ if (result.error) toast.error("We couldn't save your analytics setting.");
+}
+
+/** Starts and stops PostHog to match the current choices. */
+export function PrivacyBootstrap() {
+ const { data: session, isPending: isSessionPending } = useSession();
+ const choices = usePrivacyChoices();
+ const userId = session?.user?.id ?? null;
+ const accountOptedOut = session?.user?.analyticsOptedOut === true;
+ const organizationId = getActiveOrganizationId(session);
+ const previousUserIdRef = React.useRef<string | null>(null);
+
+ const analytics = choices?.analytics;
+ React.useEffect(() => {
+ if (analytics === undefined || isSessionPending) return;
+
+ if (analytics) {
+ startAnalyticsCapture();
+ if (userId) {
+ identifyAnalyticsUser({ userId, organizationId });
+ previousUserIdRef.current = userId;
+ }
+ } else {
+ stopAnalyticsCapture();
+ }
+ if (!userId && previousUserIdRef.current) {
+ previousUserIdRef.current = null;
+ resetAnalyticsUser();
+ }
+ }, [analytics, isSessionPending, organizationId, userId]);
+
+ // Keep the account flag in line with this browser so server-side events
+ // stop when analytics is off here (for example, a new EU visitor who hasn't
+ // chosen yet).
+ React.useEffect(() => {
+ if (!userId || analytics === undefined) return;
+ if (accountOptedOut === !analytics) return;
+ void authClient.updateUser({ analyticsOptedOut: !analytics });
+ }, [accountOptedOut, analytics, userId]);
+
+ return null;
+}
diff --git a/src/client/features/ai-mcp/AgentSetup.tsx b/src/client/features/ai-mcp/AgentSetup.tsx
index b8b32e60..196ff9bc 100644
--- a/src/client/features/ai-mcp/AgentSetup.tsx
+++ b/src/client/features/ai-mcp/AgentSetup.tsx
@@ -9,10 +9,12 @@ import { Button } from "@/client/components/ui/button";
export function AgentSetup({
onNext,
onBack,
+ nextLabel = "Finish",
disabled = false,
}: {
onNext: () => void;
onBack: () => void;
+ nextLabel?: string;
disabled?: boolean;
}) {
const prompt = getAgentSetupPrompt(window.location.origin);
@@ -43,7 +45,7 @@ export function AgentSetup({
className="h-8 gap-2 px-3 text-xs font-semibold"
onClick={onNext}
>
- Finish <ArrowRight className="size-4" />
+ {nextLabel} <ArrowRight className="size-4" />
</Button>
}
/>
diff --git a/src/client/features/onboarding/AnalyticsOnboardingStep.tsx b/src/client/features/onboarding/AnalyticsOnboardingStep.tsx
new file mode 100644
index 00000000..8040b6be
--- /dev/null
+++ b/src/client/features/onboarding/AnalyticsOnboardingStep.tsx
@@ -0,0 +1,59 @@
+import { Button } from "@/client/components/ui/button";
+import {
+ updatePrivacyChoices,
+ usePrivacyChoices,
+} from "@/client/components/PrivacyChoices";
+import { WizardFooter } from "@/client/features/onboarding/WizardFooter";
+
+/** Last onboarding step on the hosted app: one yes-or-no question about usage
+ * analytics, with equal buttons. Either answer finishes onboarding. Until it
+ * is answered, the region default applies (on in the US, off in the EU). */
+export function AnalyticsOnboardingStep({
+ onBack,
+ onFinish,
+}: {
+ onBack: () => void;
+ onFinish: () => void;
+}) {
+ const choices = usePrivacyChoices();
+ const answer = (analytics: boolean) => {
+ if (choices) void updatePrivacyChoices({ ...choices, analytics }, true);
+ onFinish();
+ };
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <h1 className="text-2xl font-semibold tracking-tight">
+ Help make OpenSEO better
+ </h1>
+ <p className="mt-3 text-sm text-muted-foreground">
+ Share usage analytics and session replays to help improve OpenSEO. See
+ our{" "}
+ <a
+ href="https://openseo.so/privacy"
+ target="_blank"
+ rel="noreferrer"
+ className="text-foreground underline underline-offset-2"
+ >
+ Privacy Policy
+ </a>
+ .
+ </p>
+ </div>
+ <WizardFooter
+ onBack={onBack}
+ continueAction={
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={() => answer(false)}>
+ No thanks
+ </Button>
+ <Button variant="outline" onClick={() => answer(true)}>
+ Share analytics
+ </Button>
+ </div>
+ }
+ />
+ </div>
+ );
+}
diff --git a/src/client/features/onboarding/PostSignupOnboarding.tsx b/src/client/features/onboarding/PostSignupOnboarding.tsx
index 3ffddeda..203bfffd 100644
--- a/src/client/features/onboarding/PostSignupOnboarding.tsx
+++ b/src/client/features/onboarding/PostSignupOnboarding.tsx
@@ -4,6 +4,8 @@ import { ONBOARDING_STEPS } from "./onboardingModel";
import { WebsiteOnboardingStep } from "./WebsiteOnboardingStep";
import { AgentSetup } from "@/client/features/ai-mcp/AgentSetup";
import { SearchConsoleOnboardingStep } from "./SearchConsoleOnboardingStep";
+import { AnalyticsOnboardingStep } from "./AnalyticsOnboardingStep";
+import { isHostedClientAuthMode } from "@/lib/auth-mode";
type PostSignupOnboardingProps = {
step: number;
@@ -29,12 +31,19 @@ export function PostSignupOnboarding({
accountMenu,
suggestedDomain,
}: PostSignupOnboardingProps) {
+ // Hosted only: self-hosted installs don't run PostHog.
+ const askAnalytics = isHostedClientAuthMode();
return (
<>
{accountMenu}
<OnboardingCard
step={step + 1}
- steps={["Website", "Google Search Console", "Agent setup"]}
+ steps={[
+ "Website",
+ "Google Search Console",
+ "Agent setup",
+ ...(askAnalytics ? ["Analytics"] : []),
+ ]}
onStepChange={onStepChange}
disabled={isSaving}
>
@@ -51,8 +60,15 @@ export function PostSignupOnboarding({
onBack={onBack}
onSkip={onSkip}
/>
+ ) : ONBOARDING_STEPS[step] === "agent_setup" || !askAnalytics ? (
+ <AgentSetup
+ onNext={askAnalytics ? onNext : onFinish}
+ nextLabel={askAnalytics ? "Continue" : "Finish"}
+ onBack={onBack}
+ disabled={isSaving}
+ />
) : (
- <AgentSetup onNext={onFinish} onBack={onBack} disabled={isSaving} />
+ <AnalyticsOnboardingStep onBack={onBack} onFinish={onFinish} />
)}
</fieldset>
</OnboardingCard>
diff --git a/src/client/features/onboarding/onboardingModel.ts b/src/client/features/onboarding/onboardingModel.ts
index efaebd25..ce3d7e7f 100644
--- a/src/client/features/onboarding/onboardingModel.ts
+++ b/src/client/features/onboarding/onboardingModel.ts
@@ -6,6 +6,8 @@ export const ONBOARDING_STEPS = [
"website",
"search_console",
"agent_setup",
+ // Hosted only (PostSignupOnboarding).
+ "analytics",
] as const;
export const ONBOARDING_LAST_STEP = ONBOARDING_STEPS.length - 1;
diff --git a/src/client/features/settings/PrivacySettings.tsx b/src/client/features/settings/PrivacySettings.tsx
new file mode 100644
index 00000000..d5cf92ad
--- /dev/null
+++ b/src/client/features/settings/PrivacySettings.tsx
@@ -0,0 +1,32 @@
+import { SectionHeader } from "@/client/components/PageHeader";
+import {
+ updatePrivacyChoices,
+ usePrivacyChoices,
+} from "@/client/components/PrivacyChoices";
+import { Switch } from "@/client/components/ui/switch";
+
+export function PrivacySettings() {
+ const choices = usePrivacyChoices();
+ if (!choices) return null;
+
+ return (
+ <section className="space-y-3">
+ <SectionHeader title="Analytics" />
+ <div className="flex items-start justify-between gap-6">
+ <div>
+ <p className="text-sm">Help improve OpenSEO</p>
+ <p className="mt-1 text-sm text-muted-foreground">
+ Share usage analytics and session replays.
+ </p>
+ </div>
+ <Switch
+ checked={choices.analytics}
+ onCheckedChange={(analytics) =>
+ void updatePrivacyChoices({ ...choices, analytics }, true)
+ }
+ aria-label="Share usage analytics"
+ />
+ </div>
+ </section>
+ );
+}
diff --git a/src/client/lib/posthog.ts b/src/client/lib/posthog.ts
index e22e6763..b89db3f3 100644
--- a/src/client/lib/posthog.ts
+++ b/src/client/lib/posthog.ts
@@ -10,8 +10,9 @@ type BrowserPostHogClient = typeof import("posthog-js").default;
let browserPostHogClientPromise: Promise<BrowserPostHogClient | null> | null =
null;
-let browserPostHogInitialized = false;
-let analyticsCaptureEnabled = true;
+// Off until PrivacyBootstrap applies the visitor's choices, so nothing is
+// captured before we know whether analytics is allowed.
+let analyticsCaptureEnabled = false;
let clientErrorCaptureStopped = false;
type ExceptionEntry = {
@@ -77,60 +78,61 @@ function getBrowserPostHogClient(): Promise<BrowserPostHogClient | null> {
return null;
}
- if (!browserPostHogInitialized) {
- client.init(apiKey, {
- api_host: host,
- defaults: "2026-01-30",
- capture_exceptions: true,
- before_send(event) {
- if (!event) return null;
- if (
- event.event === "$exception" &&
- isIgnorableException(event.properties)
- ) {
- return null;
- }
- return sanitizePostHogEvent(event);
+ client.init(apiKey, {
+ api_host: host,
+ defaults: "2026-01-30",
+ capture_exceptions: true,
+ before_send(event) {
+ if (!event) return null;
+ if (
+ event.event === "$exception" &&
+ isIgnorableException(event.properties)
+ ) {
+ return null;
+ }
+ return sanitizePostHogEvent(event);
+ },
+ capture_pageview: "history_change",
+ // Autocaptured clicks carry no on-screen text or element attributes.
+ mask_all_text: true,
+ mask_all_element_attributes: true,
+ mask_personal_data_properties: true,
+ respect_dnt: true,
+ // Opting out also clears PostHog's cookie and stored identifiers.
+ opt_out_persistence_by_default: true,
+ // Recording starts in startAnalyticsCapture, once analytics is allowed.
+ disable_session_recording: true,
+ // Console output can quote page content and full error messages,
+ // and the project setting would otherwise record it in replays.
+ enable_recording_console_log: false,
+ // Recordings mask all text and inputs: app screens show customer
+ // content (keywords, domains, GSC/GA data, reports, chat messages).
+ session_recording: {
+ maskAllInputs: true,
+ maskTextSelector: "*",
+ // Text masking doesn't cover attributes, and the recorder has no
+ // attribute masker. These elements carry content in attributes
+ // (keyword links, customer URLs, favicons, prompt and URL titles
+ // and labels), so they are recorded as blank boxes.
+ blockSelector:
+ 'a[href^="http"], a[href*="?"], img, [title], [aria-label]',
+ recordHeaders: false,
+ recordBody: false,
+ // Runs on page URLs and network entries. Project settings can turn
+ // payload capture on remotely, so headers and bodies are dropped
+ // here too.
+ maskCapturedNetworkRequestFn(request) {
+ return {
+ ...request,
+ name: sanitizePostHogUrl(request.name),
+ requestHeaders: undefined,
+ requestBody: undefined,
+ responseHeaders: undefined,
+ responseBody: undefined,
+ };
},
- capture_pageview: "history_change",
- // Autocaptured clicks carry no on-screen text or element attributes.
- mask_all_text: true,
- mask_all_element_attributes: true,
- mask_personal_data_properties: true,
- respect_dnt: true,
- // Console output can quote page content and full error messages,
- // and the project setting would otherwise record it in replays.
- enable_recording_console_log: false,
- // Recordings mask all text and inputs: app screens show customer
- // content (keywords, domains, GSC/GA data, reports, chat messages).
- session_recording: {
- maskAllInputs: true,
- maskTextSelector: "*",
- // Text masking doesn't cover attributes, and the recorder has no
- // attribute masker. These elements carry content in attributes
- // (keyword links, customer URLs, favicons, prompt and URL titles
- // and labels), so they are recorded as blank boxes.
- blockSelector:
- 'a[href^="http"], a[href*="?"], img, [title], [aria-label]',
- recordHeaders: false,
- recordBody: false,
- // Runs on page URLs and network entries. Project settings can turn
- // payload capture on remotely, so headers and bodies are dropped
- // here too.
- maskCapturedNetworkRequestFn(request) {
- return {
- ...request,
- name: sanitizePostHogUrl(request.name),
- requestHeaders: undefined,
- requestBody: undefined,
- responseHeaders: undefined,
- responseBody: undefined,
- };
- },
- },
- });
- browserPostHogInitialized = true;
- }
+ },
+ });
return client;
})
@@ -195,22 +197,19 @@ export function resetAnalyticsUser() {
export function stopAnalyticsCapture() {
analyticsCaptureEnabled = false;
- if (!browserPostHogInitialized || !browserPostHogClientPromise) return;
- void browserPostHogClientPromise.then((client) => {
- if (!client) return;
- try {
- client.stopSessionRecording();
- client.opt_out_capturing();
- } catch (e) {
- console.error("posthog opt-out failed", e);
- }
+ // Chained even while PostHog is still loading, so this runs after a pending
+ // start and the stop wins.
+ withExistingPostHogClient((client) => {
+ client.stopSessionRecording();
+ client.opt_out_capturing();
});
}
export function startAnalyticsCapture() {
analyticsCaptureEnabled = true;
withPostHogClient((client) => {
- client.opt_in_capturing();
+ if (!analyticsCaptureEnabled) return;
+ client.opt_in_capturing({ captureEventName: false });
client.startSessionRecording();
});
}
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index 061e6fad..03d4eb8c 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -22,6 +22,11 @@ import { resolveSignInHostedOrganization } from "@/server/auth/default-hosted-or
import { onInvitationAccepted } from "@/server/auth/invited-member";
import { AuthRepository } from "@/server/auth/repositories/AuthRepository";
import { captureDubReferralSignup } from "@/server/referrals/dub";
+import {
+ effectivePrivacyChoices,
+ readPrivacyCookie,
+ requiresOptIn,
+} from "@/shared/privacy-choices";
import {
sendHostedPasswordResetEmail,
sendHostedVerificationEmail,
@@ -39,6 +44,16 @@ const hostedBaseUrlSchema = z
);
}, "BETTER_AUTH_URL must use https or localhost");
+// The optional-tracking choices that apply to a signup request: the browser's
+// saved choice, or the defaults for its location.
+function signupPrivacyChoices(request: Request | undefined) {
+ return effectivePrivacyChoices({
+ saved: readPrivacyCookie(request?.headers.get("cookie")),
+ optIn: requiresOptIn(request?.headers.get("cf-ipcountry")),
+ globalPrivacyControl: request?.headers.get("sec-gpc") === "1",
+ });
+}
+
function createAuth() {
// Hosted needs the real configured URL (cookies, callbacks, /api/auth routes
// all use it). Self-hosted only builds this instance to mint/refresh Search
@@ -213,7 +228,7 @@ function createAuth() {
// Hosted only: keep cheap mass-signups off the free plan by rejecting
// throwaway-inbox domains before the user row is created. Self-hosted
// has no shared credit pool to protect, so it's left untouched.
- before: async (user) => {
+ before: async (user, ctx) => {
if (
isHostedAuthMode(env.AUTH_MODE) &&
isDisposableEmailDomain(user.email)
@@ -222,11 +237,20 @@ function createAuth() {
message: "Please sign up with a non-disposable email address.",
});
}
- return { data: user };
+ // Start new accounts with the analytics choice that applies to
+ // this browser, so server-side analytics doesn't run for a
+ // visitor who hasn't opted in where opt-in is required.
+ const choices = signupPrivacyChoices(ctx?.request);
+ return { data: { ...user, analyticsOptedOut: !choices.analytics } };
},
after: async (user, ctx) => {
await syncHostedSignupContact(user);
- if (isHostedAuthMode(env.AUTH_MODE)) {
+ // Partner attribution is an advertising/referral choice: an older
+ // dub_id cookie must not credit a partner without it.
+ if (
+ isHostedAuthMode(env.AUTH_MODE) &&
+ signupPrivacyChoices(ctx?.request).ads
+ ) {
await captureDubReferralSignup(user.id, ctx?.request);
}
},
diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts
index d8262d28..3ba67832 100644
--- a/src/routeTree.gen.ts
+++ b/src/routeTree.gen.ts
@@ -30,6 +30,7 @@ import { Route as AuthenticatedSubscribeRouteImport } from './routes/_authentica
import { Route as AuthenticatedYcRouteImport } from './routes/_authenticated.yc'
import { Route as AcceptInvitationIdRouteImport } from './routes/accept-invitation.$id'
import { Route as ApiHealthRouteImport } from './routes/api/health'
+import { Route as ApiPrivacyRegionRouteImport } from './routes/api/privacy-region'
import { Route as RReportIdRouteImport } from './routes/r/$reportId'
import { Route as AppBillingFixPaymentRouteImport } from './routes/_app/billing_.fix-payment'
import { Route as AppHelpDataforseoApiKeyRouteImport } from './routes/_app/help/dataforseo-api-key'
@@ -176,6 +177,11 @@ const ApiHealthRoute = ApiHealthRouteImport.update({
path: '/api/health',
getParentRoute: () => rootRouteImport,
} as any)
+const ApiPrivacyRegionRoute = ApiPrivacyRegionRouteImport.update({
+ id: '/api/privacy-region',
+ path: '/api/privacy-region',
+ getParentRoute: () => rootRouteImport,
+} as any)
const RReportIdRoute = RReportIdRouteImport.update({
id: '/r/$reportId',
path: '/r/$reportId',
@@ -419,6 +425,7 @@ export interface FileRoutesByFullPath {
'/yc': typeof AuthenticatedYcRoute
'/accept-invitation/$id': typeof AcceptInvitationIdRoute
'/api/health': typeof ApiHealthRoute
+ '/api/privacy-region': typeof ApiPrivacyRegionRoute
'/r/$reportId': typeof RReportIdRoute
'/p/$projectId': typeof AppPProjectIdRouteRouteWithChildren
'/billing/fix-payment': typeof AppBillingFixPaymentRoute
@@ -479,6 +486,7 @@ export interface FileRoutesByTo {
'/yc': typeof AuthenticatedYcRoute
'/accept-invitation/$id': typeof AcceptInvitationIdRoute
'/api/health': typeof ApiHealthRoute
+ '/api/privacy-region': typeof ApiPrivacyRegionRoute
'/r/$reportId': typeof RReportIdRoute
'/billing/fix-payment': typeof AppBillingFixPaymentRoute
'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute
@@ -539,6 +547,7 @@ export interface FileRoutesById {
'/_authenticated/yc': typeof AuthenticatedYcRoute
'/accept-invitation/$id': typeof AcceptInvitationIdRoute
'/api/health': typeof ApiHealthRoute
+ '/api/privacy-region': typeof ApiPrivacyRegionRoute
'/r/$reportId': typeof RReportIdRoute
'/_app/': typeof AppIndexRoute
'/_app/p/$projectId': typeof AppPProjectIdRouteRouteWithChildren
@@ -603,6 +612,7 @@ export interface FileRouteTypes {
| '/yc'
| '/accept-invitation/$id'
| '/api/health'
+ | '/api/privacy-region'
| '/r/$reportId'
| '/p/$projectId'
| '/billing/fix-payment'
@@ -663,6 +673,7 @@ export interface FileRouteTypes {
| '/yc'
| '/accept-invitation/$id'
| '/api/health'
+ | '/api/privacy-region'
| '/r/$reportId'
| '/billing/fix-payment'
| '/help/dataforseo-api-key'
@@ -722,6 +733,7 @@ export interface FileRouteTypes {
| '/_authenticated/yc'
| '/accept-invitation/$id'
| '/api/health'
+ | '/api/privacy-region'
| '/r/$reportId'
| '/_app/'
| '/_app/p/$projectId'
@@ -777,6 +789,7 @@ export interface RootRouteChildren {
Char91DotwellKnownChar93OpenaiAppsChallengeRoute: typeof Char91DotwellKnownChar93OpenaiAppsChallengeRoute
AcceptInvitationIdRoute: typeof AcceptInvitationIdRoute
ApiHealthRoute: typeof ApiHealthRoute
+ ApiPrivacyRegionRoute: typeof ApiPrivacyRegionRoute
RReportIdRoute: typeof RReportIdRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute
ApiAutumnSplatRoute: typeof ApiAutumnSplatRoute
@@ -936,6 +949,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ApiHealthRouteImport
parentRoute: typeof rootRouteImport
}
+ '/api/privacy-region': {
+ id: '/api/privacy-region'
+ path: '/api/privacy-region'
+ fullPath: '/api/privacy-region'
+ preLoaderRoute: typeof ApiPrivacyRegionRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/r/$reportId': {
id: '/r/$reportId'
path: '/r/$reportId'
@@ -1412,6 +1432,7 @@ const rootRouteChildren: RootRouteChildren = {
Char91DotwellKnownChar93OpenaiAppsChallengeRoute,
AcceptInvitationIdRoute: AcceptInvitationIdRoute,
ApiHealthRoute: ApiHealthRoute,
+ ApiPrivacyRegionRoute: ApiPrivacyRegionRoute,
RReportIdRoute: RReportIdRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute,
ApiAutumnSplatRoute: ApiAutumnSplatRoute,
diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx
index d9121348..ca07f1ac 100644
--- a/src/routes/__root.tsx
+++ b/src/routes/__root.tsx
@@ -14,20 +14,12 @@ import { DefaultCatchBoundary } from "@/client/components/DefaultCatchBoundary";
import { captureGoogleLinkError } from "@/client/features/integrations/googleLinkError";
import { ExportToSheetsModal } from "@/client/components/table/ExportToSheetsModal";
import { themePreferenceInitScript } from "@/client/lib/theme";
-import {
- identifyAnalyticsUser,
- resetAnalyticsUser,
- startAnalyticsCapture,
- stopAnalyticsCapture,
-} from "@/client/lib/posthog";
import { NotFound } from "@/client/components/NotFound";
+import { PrivacyBootstrap } from "@/client/components/PrivacyChoices";
import { TooltipProvider } from "@/client/components/ui/tooltip";
import appCss from "@/client/styles/app.css?url";
-import { useSession } from "@/lib/auth-client";
-import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { Toaster } from "sonner";
import { queryClient } from "@/client/tanstack-db";
-import { getActiveOrganizationId } from "@/lib/auth-session";
// Capture Google link error params before the router starts — a route loader
// redirect would otherwise replace the URL and lose them. See googleLinkError.ts.
@@ -98,34 +90,6 @@ function AppLayout() {
return <Outlet />;
}
-function PostHogBootstrap() {
- const isHostedMode = isHostedClientAuthMode();
- const { data: session, isPending: isSessionPending } = useSession();
- const userId = session?.user?.id ?? null;
- const optedOut = session?.user?.analyticsOptedOut === true;
- const organizationId = getActiveOrganizationId(session);
- const previousUserIdRef = React.useRef<string | null>(null);
-
- React.useEffect(() => {
- if (!isHostedMode || isSessionPending) {
- return;
- }
-
- if (userId && !optedOut) {
- startAnalyticsCapture();
- identifyAnalyticsUser({ userId, organizationId });
- previousUserIdRef.current = userId;
- } else if (userId && optedOut) {
- stopAnalyticsCapture();
- } else if (previousUserIdRef.current) {
- previousUserIdRef.current = null;
- resetAnalyticsUser();
- }
- }, [isHostedMode, isSessionPending, optedOut, organizationId, userId]);
-
- return null;
-}
-
function RootDocument({ children }: { children: React.ReactNode }) {
const showDevtools =
import.meta.env.DEV && import.meta.env.VITE_SHOW_DEVTOOLS !== "false";
@@ -142,7 +106,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
<ClientOnly>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
- <PostHogBootstrap />
+ <PrivacyBootstrap />
{children}
<ExportToSheetsModal />
<Toaster position="bottom-right" mobileOffset={{ bottom: 100 }} />
diff --git a/src/routes/_app/settings/index.tsx b/src/routes/_app/settings/index.tsx
index 5a398f7f..5826f06e 100644
--- a/src/routes/_app/settings/index.tsx
+++ b/src/routes/_app/settings/index.tsx
@@ -1,11 +1,8 @@
import { createFileRoute } from "@tanstack/react-router";
-import { useState } from "react";
-import { toast } from "sonner";
import { ApiKeySettings } from "@/client/features/settings/ApiKeySettings";
import { SectionHeader } from "@/client/components/PageHeader";
import { ThemePreferenceRadio } from "@/client/components/ThemePreferenceMenuItems";
-import { Switch } from "@/client/components/ui/switch";
-import { authClient, useSession } from "@/lib/auth-client";
+import { PrivacySettings } from "@/client/features/settings/PrivacySettings";
import { isHostedClientAuthMode } from "@/lib/auth-mode";
import { version } from "../../../../package.json";
@@ -15,29 +12,6 @@ export const Route = createFileRoute("/_app/settings/")({
function PersonalSettings() {
const isHosted = isHostedClientAuthMode();
- const { data: session } = useSession();
- const [isSaving, setIsSaving] = useState(false);
-
- const analyticsEnabled = session?.user?.analyticsOptedOut !== true;
-
- async function updateAnalyticsPreference(enabled: boolean) {
- setIsSaving(true);
- try {
- const result = await authClient.updateUser({
- analyticsOptedOut: !enabled,
- });
- if (result.error) {
- toast.error("We couldn't update your analytics setting.");
- } else {
- toast.success(enabled ? "Analytics enabled" : "Analytics disabled");
- }
- } catch {
- toast.error("We couldn't update your analytics setting.");
- } finally {
- setIsSaving(false);
- }
- }
-
return (
<div className="space-y-10">
<section className="space-y-3">
@@ -52,25 +26,7 @@ function PersonalSettings() {
<>
<ApiKeySettings />
- <section className="space-y-3">
- <SectionHeader title="Analytics" />
- <div className="flex items-start justify-between gap-6">
- <div>
- <p className="text-sm">Help improve OpenSEO</p>
- <p className="mt-1 text-sm text-muted-foreground">
- Share analytics and usage data.
- </p>
- </div>
- <Switch
- checked={analyticsEnabled}
- disabled={isSaving}
- onCheckedChange={(checked) => {
- void updateAnalyticsPreference(checked);
- }}
- aria-label="Enable product analytics"
- />
- </div>
- </section>
+ <PrivacySettings />
</>
) : (
<section className="space-y-3">
diff --git a/src/routes/api/privacy-region.ts b/src/routes/api/privacy-region.ts
new file mode 100644
index 00000000..1a0364a4
--- /dev/null
+++ b/src/routes/api/privacy-region.ts
@@ -0,0 +1,17 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { requiresOptIn } from "@/shared/privacy-choices";
+
+// Which privacy defaults apply to the visitor's location (Cloudflare's
+// CF-IPCountry). A route rather than a server function: signed-out pages need
+// it, and every server function requires a signed-in user.
+export const Route = createFileRoute("/api/privacy-region")({
+ server: {
+ handlers: {
+ GET: ({ request }) =>
+ Response.json(
+ { optIn: requiresOptIn(request.headers.get("cf-ipcountry")) },
+ { headers: { "cache-control": "private, no-store" } },
+ ),
+ },
+ },
+});
diff --git a/src/server/auth/repositories/AuthRepository.ts b/src/server/auth/repositories/AuthRepository.ts
index 67d319a2..3ecb8dbd 100644
--- a/src/server/auth/repositories/AuthRepository.ts
+++ b/src/server/auth/repositories/AuthRepository.ts
@@ -281,6 +281,15 @@ async function setLastActiveOrganization(
.where(eq(authUser.id, userId));
}
+async function isAnalyticsOptedOut(userId: string) {
+ const [record] = await db
+ .select({ analyticsOptedOut: authUser.analyticsOptedOut })
+ .from(authUser)
+ .where(eq(authUser.id, userId))
+ .limit(1);
+ return record?.analyticsOptedOut === true;
+}
+
export const AuthRepository = {
upsertDelegatedOrganization,
findFirstOrganizationIdForUser,
@@ -295,4 +304,5 @@ export const AuthRepository = {
getHostedUser,
getHostedUserNames,
hasPendingInvitationForEmail,
+ isAnalyticsOptedOut,
} as const;
diff --git a/src/server/lib/posthog.ts b/src/server/lib/posthog.ts
index 267d4569..7168bab0 100644
--- a/src/server/lib/posthog.ts
+++ b/src/server/lib/posthog.ts
@@ -86,6 +86,19 @@ export async function captureServerEvent(args: {
if (!client) return;
try {
+ // Product analytics follows the user's choice (synced from the browser).
+ // Imported lazily so modules that only report events don't pull in the
+ // database client at load time. Scoped because some callers, like the
+ // chat agent's telemetry, run outside a request's Postgres scope.
+ const [{ withPgClient }, { AuthRepository }] = await Promise.all([
+ import("@/db"),
+ import("@/server/auth/repositories/AuthRepository"),
+ ]);
+ const optedOut = await withPgClient(() =>
+ AuthRepository.isAnalyticsOptedOut(args.distinctId),
+ );
+ if (optedOut) return;
+
client.capture({
distinctId: args.distinctId,
event: args.event,
diff --git a/src/shared/privacy-choices.test.ts b/src/shared/privacy-choices.test.ts
new file mode 100644
index 00000000..c9d280e4
--- /dev/null
+++ b/src/shared/privacy-choices.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import {
+ effectivePrivacyChoices,
+ readPrivacyCookie,
+ requiresOptIn,
+} from "./privacy-choices";
+
+describe("privacy choices", () => {
+ it("needs opt-in for EEA/UK/Swiss and unknown locations only", () => {
+ expect(requiresOptIn("DE")).toBe(true);
+ expect(requiresOptIn("GB")).toBe(true);
+ expect(requiresOptIn(null)).toBe(true);
+ expect(requiresOptIn("XX")).toBe(true);
+ expect(requiresOptIn("T1")).toBe(true);
+ expect(requiresOptIn("US")).toBe(false);
+ });
+
+ it("keeps optional tracking off until an opt-in visitor chooses", () => {
+ expect(
+ effectivePrivacyChoices({
+ saved: null,
+ optIn: true,
+ globalPrivacyControl: false,
+ }),
+ ).toEqual({ analytics: false, ads: false });
+ });
+
+ it("lets Global Privacy Control override a saved advertising choice", () => {
+ const saved = readPrivacyCookie("other=1; openseo_privacy=a1.d1");
+ expect(
+ effectivePrivacyChoices({
+ saved,
+ optIn: false,
+ globalPrivacyControl: true,
+ }),
+ ).toEqual({ analytics: true, ads: false });
+ });
+});
diff --git a/src/shared/privacy-choices.ts b/src/shared/privacy-choices.ts
new file mode 100644
index 00000000..a29f3512
--- /dev/null
+++ b/src/shared/privacy-choices.ts
@@ -0,0 +1,107 @@
+// Optional tracking choices shared by the marketing site (openseo.so) and the
+// app (app.openseo.so). Both read one first-party cookie on `.openseo.so`, so a
+// choice made on either side applies to both. Necessary cookies (sign-in,
+// security, this cookie) are not optional and are not covered here.
+
+export type PrivacyChoices = {
+ /** PostHog product analytics in the app: events, errors and masked
+ * session recordings. The website's visit statistics are cookieless and
+ * not covered here. */
+ analytics: boolean;
+ /** Partner referral attribution (Dub's referral cookie). */
+ ads: boolean;
+};
+
+const PRIVACY_COOKIE = "openseo_privacy";
+const PRIVACY_COOKIE_MAX_AGE_SECONDS = 180 * 24 * 60 * 60;
+
+// For visitors from these countries nothing optional runs until they opt in.
+// Everywhere else optional tracking is on until the visitor opts out. EEA
+// (EU + Iceland, Liechtenstein, Norway), UK and Switzerland. The second line
+// is EU regions that report their own code (French overseas regions, Åland),
+// then Gibraltar and the Crown Dependencies, which follow GDPR-style rules.
+const OPT_IN_COUNTRIES = new Set([
+ "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU",
+ "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES",
+ "SE", "IS", "LI", "NO", "GB", "CH",
+ "RE", "GP", "MQ", "GF", "YT", "MF", "AX", "GI", "JE", "GG", "IM",
+]); // prettier-ignore
+
+/** `country` is Cloudflare's CF-IPCountry. Unknown or anonymized (XX, T1)
+ * locations get the opt-in treatment. */
+export function requiresOptIn(country: string | null | undefined): boolean {
+ if (!country || country.length !== 2) return true;
+ if (country === "XX" || country === "T1") return true;
+ return OPT_IN_COUNTRIES.has(country.toUpperCase());
+}
+
+export function defaultPrivacyChoices(optIn: boolean): PrivacyChoices {
+ return { analytics: !optIn, ads: !optIn };
+}
+
+/** Saved choices from a Cookie header or `document.cookie`, or null when the
+ * visitor hasn't chosen yet (or the cookie is unreadable). */
+export function readPrivacyCookie(
+ cookieHeader: string | null | undefined,
+): PrivacyChoices | null {
+ const raw = cookieHeader
+ ?.split(";")
+ .map((part) => part.trim())
+ .find((part) => part.startsWith(`${PRIVACY_COOKIE}=`))
+ ?.slice(PRIVACY_COOKIE.length + 1);
+ // Format: "a1.d0" — analytics, ads.
+ const match = /^a([01])\.d([01])$/.exec(raw ?? "");
+ if (!match) return null;
+ return { analytics: match[1] === "1", ads: match[2] === "1" };
+}
+
+/** Choices that apply right now. Global Privacy Control always turns off
+ * advertising and referral tracking, whatever was saved. */
+export function effectivePrivacyChoices(args: {
+ saved: PrivacyChoices | null;
+ optIn: boolean;
+ globalPrivacyControl: boolean;
+}): PrivacyChoices {
+ const choices = args.saved ?? defaultPrivacyChoices(args.optIn);
+ return args.globalPrivacyControl ? { ...choices, ads: false } : choices;
+}
+
+// ---- Browser helpers ----
+
+export function hasGlobalPrivacyControl(): boolean {
+ return (
+ typeof navigator !== "undefined" &&
+ Reflect.get(navigator, "globalPrivacyControl") === true
+ );
+}
+
+function cookieDomainAttribute(): string {
+ const host = location.hostname;
+ return host === "openseo.so" || host.endsWith(".openseo.so")
+ ? "; Domain=openseo.so"
+ : "";
+}
+
+function writeCookie(name: string, value: string, maxAgeSeconds: number) {
+ const secure = location.protocol === "https:" ? "; Secure" : "";
+ document.cookie = `${name}=${value}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax${secure}${cookieDomainAttribute()}`;
+}
+
+const flag = (value: boolean) => (value ? "1" : "0");
+
+export function savePrivacyChoices(choices: PrivacyChoices) {
+ writeCookie(
+ PRIVACY_COOKIE,
+ `a${flag(choices.analytics)}.d${flag(choices.ads)}`,
+ PRIVACY_COOKIE_MAX_AGE_SECONDS,
+ );
+ // Withdrawing referral permission removes Dub's cookies so a later signup
+ // isn't attributed to the partner. Sales of a customer attributed at signup
+ // are still reported from the server.
+ if (!choices.ads) {
+ for (const name of ["dub_id", "dub_partner_data"]) writeCookie(name, "", 0);
+ }
+ window.dispatchEvent(new Event(PRIVACY_CHOICES_CHANGED_EVENT));
+}
+
+export const PRIVACY_CHOICES_CHANGED_EVENT = "openseo:privacy-choices-changed";
diff --git a/web/src/components/privacy-choices.tsx b/web/src/components/privacy-choices.tsx
new file mode 100644
index 00000000..0f73aed7
--- /dev/null
+++ b/web/src/components/privacy-choices.tsx
@@ -0,0 +1,267 @@
+import * as React from "react";
+import {
+ effectivePrivacyChoices,
+ hasGlobalPrivacyControl,
+ readPrivacyCookie,
+ savePrivacyChoices,
+ type PrivacyChoices as Choices,
+} from "../../../src/shared/privacy-choices";
+
+// The footer's "Your privacy choices" link dispatches this to open the dialog.
+const OPEN_PRIVACY_CHOICES_EVENT = "openseo:open-privacy-choices";
+const PLAUSIBLE_IGNORE = "plausible_ignore";
+
+// Plausible counts visits without cookies for everyone (the dialog offers its
+// opt-out). The only consent-based tracking here is Dub's referral cookie on
+// partner links: loaded where allowed, asked about where opt-in is required.
+// The footer's dialog also holds the app's analytics choice (one shared cookie).
+export function PrivacyChoices() {
+ const [saved, setSaved] = React.useState<Choices | null>(null);
+ const [optIn, setOptIn] = React.useState<boolean | null>(null);
+ const [view, setView] = React.useState<"none" | "partner" | "dialog">("none");
+
+ React.useEffect(() => {
+ const savedChoices = readPrivacyCookie(document.cookie);
+ setSaved(savedChoices);
+ if (isPartnerVisit() && !hasGlobalPrivacyControl()) {
+ if (savedChoices) {
+ if (savedChoices.ads) loadReferralAttribution();
+ } else {
+ void fetchOptIn().then((required) => {
+ setOptIn(required);
+ if (required) setView("partner");
+ else loadReferralAttribution();
+ });
+ }
+ }
+
+ const open = () => setView("dialog");
+ window.addEventListener(OPEN_PRIVACY_CHOICES_EVENT, open);
+ return () => window.removeEventListener(OPEN_PRIVACY_CHOICES_EVENT, open);
+ }, []);
+
+ // The dialog shows location-based defaults to visitors who haven't chosen.
+ React.useEffect(() => {
+ if (view === "dialog" && saved === null && optIn === null) {
+ void fetchOptIn().then(setOptIn);
+ }
+ }, [view, saved, optIn]);
+
+ const choices =
+ saved || optIn !== null
+ ? effectivePrivacyChoices({
+ saved,
+ optIn: optIn ?? false,
+ globalPrivacyControl: hasGlobalPrivacyControl(),
+ })
+ : null;
+
+ function save(next: Choices) {
+ // A loaded referral script can't be unloaded; a reload stops it.
+ const stopReferrals =
+ !next.ads && document.querySelector("script[data-openseo-dub]") !== null;
+ savePrivacyChoices(next);
+ setSaved(next);
+ setView("none");
+ if (next.ads) loadReferralAttribution();
+ if (stopReferrals) location.reload();
+ }
+
+ if (!choices || view === "none") return null;
+
+ if (view === "partner") {
+ return (
+ <Panel className="max-w-sm">
+ <p>
+ You came from a partner&apos;s link. Can we keep a 90-day cookie (Dub)
+ so they get credit if you sign up?
+ </p>
+ <div className="mt-3 flex justify-end gap-2">
+ <PanelButton onClick={() => save({ ...choices, ads: false })}>
+ No thanks
+ </PanelButton>
+ <PanelButton onClick={() => save({ ...choices, ads: true })}>
+ Allow
+ </PanelButton>
+ </div>
+ </Panel>
+ );
+ }
+
+ return (
+ <Panel className="max-w-md">
+ <ChoicesForm
+ initial={choices}
+ onSave={save}
+ onCancel={() => setView("none")}
+ />
+ </Panel>
+ );
+}
+
+function ChoicesForm({
+ initial,
+ onSave,
+ onCancel,
+}: {
+ initial: Choices;
+ onSave: (choices: Choices) => void;
+ onCancel: () => void;
+}) {
+ const [draft, setDraft] = React.useState(initial);
+ const [countVisits, setCountVisits] = React.useState(
+ () => localStorage.getItem(PLAUSIBLE_IGNORE) !== "true",
+ );
+ const gpc = hasGlobalPrivacyControl();
+
+ return (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ // Plausible's own opt-out: its script skips tracking while this is set.
+ if (countVisits) localStorage.removeItem(PLAUSIBLE_IGNORE);
+ else localStorage.setItem(PLAUSIBLE_IGNORE, "true");
+ onSave(draft);
+ }}
+ >
+ <p className="font-semibold text-neutral-900">Your privacy choices</p>
+ <div className="mt-3 space-y-3">
+ <ChoiceRow
+ label="Visit counts"
+ description="Anonymous, without cookies (Plausible)."
+ checked={countVisits}
+ onChange={setCountVisits}
+ />
+ <ChoiceRow
+ label="Product analytics"
+ description="Usage analytics and session replays in the app, with all text hidden (PostHog)."
+ checked={draft.analytics}
+ onChange={(analytics) => setDraft({ ...draft, analytics })}
+ />
+ <ChoiceRow
+ label="Partner referrals"
+ description={
+ gpc
+ ? "Off because your browser sends Global Privacy Control."
+ : "A 90-day cookie that credits the partner who sent you (Dub)."
+ }
+ checked={draft.ads && !gpc}
+ disabled={gpc}
+ onChange={(ads) => setDraft({ ...draft, ads })}
+ />
+ </div>
+ <div className="mt-4 flex justify-end gap-2">
+ <PanelButton onClick={onCancel}>Cancel</PanelButton>
+ <PanelButton type="submit" primary>
+ Save
+ </PanelButton>
+ </div>
+ </form>
+ );
+}
+
+function ChoiceRow(props: {
+ label: string;
+ description: string;
+ checked: boolean;
+ disabled?: boolean;
+ onChange: (checked: boolean) => void;
+}) {
+ return (
+ <label className="flex items-start gap-3">
+ <input
+ type="checkbox"
+ className="mt-1 size-4 shrink-0"
+ checked={props.checked}
+ disabled={props.disabled}
+ onChange={(event) => props.onChange(event.target.checked)}
+ />
+ <span>
+ <span className="font-medium text-neutral-900">{props.label}</span>
+ <span className="block text-neutral-600">{props.description}</span>
+ </span>
+ </label>
+ );
+}
+
+// Bottom left on wider screens, clear of the page's centre column and the
+// Discord button; full width on phones.
+function Panel(props: { className: string; children: React.ReactNode }) {
+ return (
+ <div
+ role="dialog"
+ aria-label="Privacy choices"
+ className={`fixed inset-x-4 bottom-4 z-50 rounded-lg border border-neutral-300 bg-white p-4 text-sm text-neutral-700 shadow-lg sm:right-auto ${props.className}`}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+// The partner prompt's two answers share one style, so declining is as easy
+// as agreeing. The dialog's Save is only slightly stronger.
+function PanelButton(props: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ type?: "button" | "submit";
+ primary?: boolean;
+}) {
+ return (
+ <button
+ type={props.type ?? "button"}
+ onClick={props.onClick}
+ className={
+ props.primary
+ ? "min-h-9 rounded-md border border-neutral-300 bg-neutral-100 px-3 font-semibold text-neutral-900 hover:bg-neutral-200"
+ : "min-h-9 rounded-md border border-neutral-300 px-3 font-medium text-neutral-900 hover:bg-neutral-100"
+ }
+ >
+ {props.children}
+ </button>
+ );
+}
+
+export function PrivacyChoicesLink() {
+ return (
+ <button
+ type="button"
+ className="text-left"
+ onClick={() =>
+ window.dispatchEvent(new Event(OPEN_PRIVACY_CHOICES_EVENT))
+ }
+ >
+ Your privacy choices
+ </button>
+ );
+}
+
+const isPartnerVisit = () => {
+ const params = new URLSearchParams(location.search);
+ return params.has("dub_id") || params.has("via");
+};
+
+// Opt-in is required in the EEA, UK, Switzerland and unknown locations
+// (Cloudflare's CF-IPCountry, read by /api/privacy-region). The page is
+// prerendered, so the browser asks. A failed lookup counts as opt-in.
+async function fetchOptIn(): Promise<boolean> {
+ try {
+ const data: unknown = await (await fetch("/api/privacy-region")).json();
+ return !(data instanceof Object && Reflect.get(data, "optIn") === false);
+ } catch {
+ return true;
+ }
+}
+
+// Dub partner links land here with ?dub_id= (and ?via=). Dub's script stores
+// the click id as a `dub_id` cookie on `.openseo.so` so the app at
+// app.openseo.so can attribute the signup. Only those visits need it.
+function loadReferralAttribution() {
+ if (!isPartnerVisit()) return;
+ if (document.querySelector("script[data-openseo-dub]")) return;
+ const script = document.createElement("script");
+ script.src = "https://www.dubcdn.com/analytics/script.js";
+ script.dataset.openseoDub = "";
+ script.dataset.domains = JSON.stringify({ refer: "links.openseo.so" });
+ script.dataset.cookieOptions = JSON.stringify({ domain: ".openseo.so" });
+ document.head.appendChild(script);
+}
diff --git a/web/src/components/site-footer.tsx b/web/src/components/site-footer.tsx
index a3ca1c12..bccbc330 100644
--- a/web/src/components/site-footer.tsx
+++ b/web/src/components/site-footer.tsx
@@ -1,4 +1,5 @@
import { Link } from "@tanstack/react-router";
+import { PrivacyChoicesLink } from "@/components/privacy-choices";
import { SocialLinks } from "@/components/social-links";
import { featureGroups } from "@/lib/feature-pages";
import { freeToolList } from "@/lib/free-tools/tool-pages";
@@ -104,6 +105,7 @@ export function SiteFooter({ className }: { className?: string }) {
</a>
<Link to="/privacy">Privacy</Link>
<Link to="/terms-and-conditions">Terms</Link>
+ <PrivacyChoicesLink />
</div>
</div>
</div>
diff --git a/web/src/routeTree.gen.ts b/web/src/routeTree.gen.ts
index 0844a17e..c8155b0a 100644
--- a/web/src/routeTree.gen.ts
+++ b/web/src/routeTree.gen.ts
@@ -44,6 +44,7 @@ import { Route as ApiCompetitorKeywordFinderRouteImport } from './routes/api/com
import { Route as ApiDomainAgeCheckerRouteImport } from './routes/api/domain-age-checker'
import { Route as ApiEventRouteImport } from './routes/api/event'
import { Route as ApiKeywordGeneratorRouteImport } from './routes/api/keyword-generator'
+import { Route as ApiPrivacyRegionRouteImport } from './routes/api/privacy-region'
import { Route as ApiSpamScoreCheckerRouteImport } from './routes/api/spam-score-checker'
import { Route as ApiSubscribeRouteImport } from './routes/api/subscribe'
import { Route as ApiWebsiteTrafficCheckerRouteImport } from './routes/api/website-traffic-checker'
@@ -286,6 +287,11 @@ const ApiKeywordGeneratorRoute = ApiKeywordGeneratorRouteImport.update({
path: '/api/keyword-generator',
getParentRoute: () => rootRouteImport,
} as any)
+const ApiPrivacyRegionRoute = ApiPrivacyRegionRouteImport.update({
+ id: '/api/privacy-region',
+ path: '/api/privacy-region',
+ getParentRoute: () => rootRouteImport,
+} as any)
const ApiSpamScoreCheckerRoute = ApiSpamScoreCheckerRouteImport.update({
id: '/api/spam-score-checker',
path: '/api/spam-score-checker',
@@ -642,6 +648,7 @@ export interface FileRoutesByFullPath {
'/api/domain-age-checker': typeof ApiDomainAgeCheckerRoute
'/api/event': typeof ApiEventRoute
'/api/keyword-generator': typeof ApiKeywordGeneratorRoute
+ '/api/privacy-region': typeof ApiPrivacyRegionRoute
'/api/spam-score-checker': typeof ApiSpamScoreCheckerRoute
'/api/subscribe': typeof ApiSubscribeRoute
'/api/website-traffic-checker': typeof ApiWebsiteTrafficCheckerRoute
@@ -732,6 +739,7 @@ export interface FileRoutesByTo {
'/api/domain-age-checker': typeof ApiDomainAgeCheckerRoute
'/api/event': typeof ApiEventRoute
'/api/keyword-generator': typeof ApiKeywordGeneratorRoute
+ '/api/privacy-region': typeof ApiPrivacyRegionRoute
'/api/spam-score-checker': typeof ApiSpamScoreCheckerRoute
'/api/subscribe': typeof ApiSubscribeRoute
'/api/website-traffic-checker': typeof ApiWebsiteTrafficCheckerRoute
@@ -824,6 +832,7 @@ export interface FileRoutesById {
'/api/domain-age-checker': typeof ApiDomainAgeCheckerRoute
'/api/event': typeof ApiEventRoute
'/api/keyword-generator': typeof ApiKeywordGeneratorRoute
+ '/api/privacy-region': typeof ApiPrivacyRegionRoute
'/api/spam-score-checker': typeof ApiSpamScoreCheckerRoute
'/api/subscribe': typeof ApiSubscribeRoute
'/api/website-traffic-checker': typeof ApiWebsiteTrafficCheckerRoute
@@ -917,6 +926,7 @@ export interface FileRouteTypes {
| '/api/domain-age-checker'
| '/api/event'
| '/api/keyword-generator'
+ | '/api/privacy-region'
| '/api/spam-score-checker'
| '/api/subscribe'
| '/api/website-traffic-checker'
@@ -1007,6 +1017,7 @@ export interface FileRouteTypes {
| '/api/domain-age-checker'
| '/api/event'
| '/api/keyword-generator'
+ | '/api/privacy-region'
| '/api/spam-score-checker'
| '/api/subscribe'
| '/api/website-traffic-checker'
@@ -1098,6 +1109,7 @@ export interface FileRouteTypes {
| '/api/domain-age-checker'
| '/api/event'
| '/api/keyword-generator'
+ | '/api/privacy-region'
| '/api/spam-score-checker'
| '/api/subscribe'
| '/api/website-traffic-checker'
@@ -1166,6 +1178,7 @@ export interface RootRouteChildren {
ApiDomainAgeCheckerRoute: typeof ApiDomainAgeCheckerRoute
ApiEventRoute: typeof ApiEventRoute
ApiKeywordGeneratorRoute: typeof ApiKeywordGeneratorRoute
+ ApiPrivacyRegionRoute: typeof ApiPrivacyRegionRoute
ApiSpamScoreCheckerRoute: typeof ApiSpamScoreCheckerRoute
ApiSubscribeRoute: typeof ApiSubscribeRoute
ApiWebsiteTrafficCheckerRoute: typeof ApiWebsiteTrafficCheckerRoute
@@ -1426,6 +1439,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ApiKeywordGeneratorRouteImport
parentRoute: typeof rootRouteImport
}
+ '/api/privacy-region': {
+ id: '/api/privacy-region'
+ path: '/api/privacy-region'
+ fullPath: '/api/privacy-region'
+ preLoaderRoute: typeof ApiPrivacyRegionRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/api/spam-score-checker': {
id: '/api/spam-score-checker'
path: '/api/spam-score-checker'
@@ -2015,6 +2035,7 @@ const rootRouteChildren: RootRouteChildren = {
ApiDomainAgeCheckerRoute: ApiDomainAgeCheckerRoute,
ApiEventRoute: ApiEventRoute,
ApiKeywordGeneratorRoute: ApiKeywordGeneratorRoute,
+ ApiPrivacyRegionRoute: ApiPrivacyRegionRoute,
ApiSpamScoreCheckerRoute: ApiSpamScoreCheckerRoute,
ApiSubscribeRoute: ApiSubscribeRoute,
ApiWebsiteTrafficCheckerRoute: ApiWebsiteTrafficCheckerRoute,
diff --git a/web/src/routes/__root.tsx b/web/src/routes/__root.tsx
index cb893243..3810a238 100644
--- a/web/src/routes/__root.tsx
+++ b/web/src/routes/__root.tsx
@@ -7,6 +7,7 @@ import {
import * as React from "react";
import appCss from "@/styles/app.css?url";
import { RootProvider } from "fumadocs-ui/provider/tanstack";
+import { PrivacyChoices } from "@/components/privacy-choices";
export const Route = createRootRoute({
head: () => ({
@@ -58,18 +59,8 @@ function RootDocument({ children }: { children: React.ReactNode }) {
<html lang="en" suppressHydrationWarning>
<head>
<HeadContent />
- {/* Dub referral attribution: partner links land here with ?dub_id=
- (and ?via=). Load Dub's script only for those visits — it persists
- the click id as a `dub_id` cookie on `.openseo.so` so the app at
- app.openseo.so can attribute the signup. Injected during the
- initial HTML parse (not idle-deferred like Plausible below) so the
- cookie lands before the visitor navigates to the app. */}
- <script
- dangerouslySetInnerHTML={{
- __html:
- "(function(){var q=new URLSearchParams(window.location.search);if(!q.has('dub_id')&&!q.has('via'))return;var s=document.createElement('script');s.src='https://www.dubcdn.com/analytics/script.js';s.dataset.domains='{\"refer\":\"links.openseo.so\"}';s.dataset.cookieOptions='{\"domain\":\".openseo.so\"}';document.head.appendChild(s)})();",
- }}
- />
+ {/* Plausible counts visits without cookies, so it runs for everyone.
+ Deferred to idle so it never competes with the page's own work. */}
<script
dangerouslySetInnerHTML={{
__html:
@@ -79,6 +70,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
</head>
<body className="flex flex-col min-h-screen bg-fd-background text-fd-foreground">
<RootProvider search={{ enabled: false }}>{children}</RootProvider>
+ <PrivacyChoices />
<Scripts />
</body>
</html>
diff --git a/web/src/routes/api/privacy-region.ts b/web/src/routes/api/privacy-region.ts
new file mode 100644
index 00000000..efb2b488
--- /dev/null
+++ b/web/src/routes/api/privacy-region.ts
@@ -0,0 +1,16 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { requiresOptIn } from "../../../../src/shared/privacy-choices";
+
+// The page is prerendered, so the browser asks once which privacy defaults
+// apply to its location (Cloudflare's CF-IPCountry).
+export const Route = createFileRoute("/api/privacy-region")({
+ server: {
+ handlers: {
+ GET: ({ request }) =>
+ Response.json(
+ { optIn: requiresOptIn(request.headers.get("cf-ipcountry")) },
+ { headers: { "cache-control": "private, no-store" } },
+ ),
+ },
+ },
+});