Skip to content

Open source alternative to Semrush and Ahrefs

Track ad signups with the Meta Pixel when advertising is allowed (#952)

Ben Senescu5619aa4ce48f
diff --git a/deploy/.env.production.example b/deploy/.env.production.example
index ff0b1b19..12562dfe 100644
--- a/deploy/.env.production.example
+++ b/deploy/.env.production.example
@@ -42,6 +42,11 @@ DATABASE_PROVIDER=postgres
# link destinations kept on openseo.so, and the native Stripe integration
# disconnected (sales are reported by the app; both would double count).
# DUB_API_KEY=
+# Meta ad signup attribution (Conversions API). The same pixel id must be set
+# on the marketing site worker, which loads the pixel where the visitor's
+# advertising choice allows it.
+# META_PIXEL_ID=
+# META_CONVERSIONS_API_TOKEN=
# Long random secret shared only with scripts/erase-user-data.ts.
# GDPR_ERASURE_SECRET=
# POSTHOG_PUBLIC_KEY=
diff --git a/deploy/alchemy/alchemy.run.ts b/deploy/alchemy/alchemy.run.ts
index 3a25ec93..400b7aca 100644
--- a/deploy/alchemy/alchemy.run.ts
+++ b/deploy/alchemy/alchemy.run.ts
@@ -280,6 +280,8 @@ const dataEnv = {
AUTUMN_SECRET_KEY: optionalSecret("AUTUMN_SECRET_KEY"),
AUTUMN_WEBHOOK_SECRET: optionalSecret("AUTUMN_WEBHOOK_SECRET"),
DUB_API_KEY: optionalSecret("DUB_API_KEY"),
+ META_PIXEL_ID: optionalVar("META_PIXEL_ID"),
+ META_CONVERSIONS_API_TOKEN: optionalSecret("META_CONVERSIONS_API_TOKEN"),
GDPR_ERASURE_SECRET: optionalSecret("GDPR_ERASURE_SECRET"),
LOOPS_API_KEY: optionalSecret("LOOPS_API_KEY"),
LOOPS_TRANSACTIONAL_VERIFY_EMAIL_ID: optionalVar(
diff --git a/src/client/components/PrivacyChoices.tsx b/src/client/components/PrivacyChoices.tsx
index 899b2ff3..7d7bd6ea 100644
--- a/src/client/components/PrivacyChoices.tsx
+++ b/src/client/components/PrivacyChoices.tsx
@@ -62,9 +62,12 @@ export function usePrivacyChoices() {
readCookies,
);
const saved = React.useMemo(() => readPrivacyCookie(cookies), [cookies]);
- const regionOptIn = usePrivacyRegion(isHosted && saved === null);
+ // Choices not saved yet follow the region. That includes the Meta choice in
+ // a cookie saved before it existed, since saving analytics writes it too.
+ const needsRegion = saved?.advertising === undefined;
+ const regionOptIn = usePrivacyRegion(isHosted && needsRegion);
- const optIn = saved ? false : regionOptIn;
+ const optIn = needsRegion ? regionOptIn : false;
if (!isHosted || optIn === undefined) return null;
// A browser without a saved choice still honors an analytics opt-out the
diff --git a/src/env.d.ts b/src/env.d.ts
index a679c9ff..05607da8 100644
--- a/src/env.d.ts
+++ b/src/env.d.ts
@@ -57,6 +57,10 @@ declare namespace Cloudflare {
// Dub referral conversion tracking (hosted only); all Dub code no-ops
// when unset.
DUB_API_KEY?: string;
+ // Meta ad signup attribution via the Conversions API (hosted only); no-ops
+ // unless both are set.
+ META_PIXEL_ID?: string;
+ META_CONVERSIONS_API_TOKEN?: string;
// HMAC secret for the operator-only GDPR storage-erasure endpoint.
GDPR_ERASURE_SECRET?: string;
diff --git a/src/lib/auth.ts b/src/lib/auth.ts
index b057fa21..dcc260da 100644
--- a/src/lib/auth.ts
+++ b/src/lib/auth.ts
@@ -23,11 +23,10 @@ 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 { captureMetaSignup } from "@/server/referrals/meta";
import {
- effectivePrivacyChoices,
productUpdatesOnByDefault,
- readPrivacyCookie,
- requiresOptIn,
+ requestPrivacyChoices,
} from "@/shared/privacy-choices";
import {
sendHostedPasswordResetEmail,
@@ -46,16 +45,6 @@ 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
@@ -242,7 +231,7 @@ function createAuth() {
// 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);
+ const choices = requestPrivacyChoices(ctx?.request);
const now = new Date();
// Every hosted signup path (email form, Google on the sign-up or
// sign-in page) shows the Terms clickwrap next to its button.
@@ -261,13 +250,14 @@ function createAuth() {
},
after: async (user, ctx) => {
await syncHostedSignupContact(user);
- // 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);
+ if (isHostedAuthMode(env.AUTH_MODE)) {
+ // Partner attribution is a referral choice: an older dub_id
+ // cookie must not credit a partner without it.
+ if (requestPrivacyChoices(ctx?.request).referrals) {
+ await captureDubReferralSignup(user.id, ctx?.request);
+ }
+ // Sent only if the separate advertising (Meta) choice allows it.
+ captureMetaSignup(ctx?.request);
}
},
},
diff --git a/src/server/referrals/meta.test.ts b/src/server/referrals/meta.test.ts
new file mode 100644
index 00000000..d1550745
--- /dev/null
+++ b/src/server/referrals/meta.test.ts
@@ -0,0 +1,42 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { captureMetaSignup } from "./meta";
+
+vi.mock("cloudflare:workers", () => ({
+ env: { META_PIXEL_ID: "123", META_CONVERSIONS_API_TOKEN: "token" },
+ waitUntil: (promise: Promise<unknown>) => promise,
+}));
+vi.mock("@/server/lib/posthog", () => ({ captureServerError: vi.fn() }));
+
+const fetchMock = vi.fn();
+
+function signupRequest(headers: Record<string, string>) {
+ return new Request("https://app.openseo.so/api/auth/sign-up/email", {
+ headers: { cookie: "_fbp=fb.1.1.1", ...headers },
+ });
+}
+
+describe("captureMetaSignup", () => {
+ beforeEach(() => {
+ fetchMock.mockResolvedValue(new Response("{}"));
+ vi.stubGlobal("fetch", fetchMock);
+ });
+
+ it("sends nothing to Meta without advertising permission", () => {
+ // An EU visitor who hasn't opted in, and a US visitor sending GPC. The
+ // full set of region and saved-choice cases is in privacy-choices.test.ts.
+ captureMetaSignup(signupRequest({ "cf-ipcountry": "DE" }));
+ captureMetaSignup(signupRequest({ "cf-ipcountry": "US", "sec-gpc": "1" }));
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("reports the signup once advertising is allowed", () => {
+ // EU visitor who opted in to advertising but not partner referrals.
+ captureMetaSignup(
+ signupRequest({
+ "cf-ipcountry": "DE",
+ cookie: "_fbp=fb.1.1.1; openseo_privacy=a0.d0.m1",
+ }),
+ );
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/server/referrals/meta.ts b/src/server/referrals/meta.ts
new file mode 100644
index 00000000..bb9c7028
--- /dev/null
+++ b/src/server/referrals/meta.ts
@@ -0,0 +1,56 @@
+import { env, waitUntil } from "cloudflare:workers";
+import { parseCookies } from "better-auth/cookies";
+import { captureServerError } from "@/server/lib/posthog";
+import { requestPrivacyChoices } from "@/shared/privacy-choices";
+
+// Meta ad signup attribution (hosted only). Sent only when the visitor's
+// advertising (Meta) choice allows it, read here from the privacy cookie,
+// location and GPC header, and the pixel on openseo.so left its cookies.
+// Deliberately no name or email.
+
+const META_GRAPH_API_URL = "https://graph.facebook.com/v23.0";
+
+/** Must never fail the signup. */
+export function captureMetaSignup(request: Request | null | undefined) {
+ const pixelId = env.META_PIXEL_ID;
+ const accessToken = env.META_CONVERSIONS_API_TOKEN;
+ if (!pixelId || !accessToken || !request) return;
+ if (!requestPrivacyChoices(request).advertising) return;
+
+ const headers = request.headers;
+ const cookies = parseCookies(headers.get("cookie") ?? "");
+ const fbp = cookies.get("_fbp");
+ const fbc = cookies.get("_fbc");
+ if (!fbp && !fbc) return;
+
+ const event = {
+ event_name: "CompleteRegistration",
+ event_time: Math.floor(Date.now() / 1000),
+ action_source: "website",
+ event_source_url: new URL("/sign-up", request.url).href,
+ user_data: {
+ client_ip_address: headers.get("cf-connecting-ip") ?? undefined,
+ client_user_agent: headers.get("user-agent") ?? undefined,
+ fbp,
+ fbc,
+ },
+ };
+
+ waitUntil(
+ fetch(`${META_GRAPH_API_URL}/${pixelId}/events`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ data: [event], access_token: accessToken }),
+ signal: AbortSignal.timeout(10_000),
+ })
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(`Meta signup tracking failed (${response.status})`);
+ }
+ })
+ .catch(async (error: unknown) => {
+ console.error("Meta signup tracking failed", { error });
+ await captureServerError(error, { source: "meta_signup" });
+ }),
+ );
+}
diff --git a/src/shared/privacy-choices.test.ts b/src/shared/privacy-choices.test.ts
index 9ba22d35..e9f6b551 100644
--- a/src/shared/privacy-choices.test.ts
+++ b/src/shared/privacy-choices.test.ts
@@ -30,17 +30,35 @@ describe("privacy choices", () => {
optIn: true,
globalPrivacyControl: false,
}),
- ).toEqual({ analytics: false, ads: false });
+ ).toEqual({ analytics: false, referrals: false, advertising: false });
});
it("lets Global Privacy Control override a saved advertising choice", () => {
- const saved = readPrivacyCookie("other=1; openseo_privacy=a1.d1");
+ const saved = readPrivacyCookie("other=1; openseo_privacy=a1.d1.m1");
expect(
effectivePrivacyChoices({
saved,
optIn: false,
globalPrivacyControl: true,
}),
- ).toEqual({ analytics: true, ads: false });
+ ).toEqual({ analytics: true, referrals: false, advertising: false });
+ });
+
+ it("applies the region default to Meta in a cookie saved before that choice existed", () => {
+ const saved = readPrivacyCookie("openseo_privacy=a1.d1");
+ expect(
+ effectivePrivacyChoices({
+ saved,
+ optIn: true,
+ globalPrivacyControl: false,
+ }),
+ ).toEqual({ analytics: true, referrals: true, advertising: false });
+ expect(
+ effectivePrivacyChoices({
+ saved,
+ optIn: false,
+ globalPrivacyControl: false,
+ }).advertising,
+ ).toBe(true);
});
});
diff --git a/src/shared/privacy-choices.ts b/src/shared/privacy-choices.ts
index 5419dabb..b71b7d76 100644
--- a/src/shared/privacy-choices.ts
+++ b/src/shared/privacy-choices.ts
@@ -9,7 +9,16 @@ export type PrivacyChoices = {
* not covered here. */
analytics: boolean;
/** Partner referral attribution (Dub's referral cookie). */
- ads: boolean;
+ referrals: boolean;
+ /** Meta ad measurement: the Meta Pixel on openseo.so and the app's signup
+ * event to Meta's Conversions API. */
+ advertising: boolean;
+};
+
+/** Choices as saved in the cookie. A cookie saved before Meta had its own
+ * choice has no `advertising`, so the region default applies to it. */
+type SavedPrivacyChoices = Omit<PrivacyChoices, "advertising"> & {
+ advertising?: boolean;
};
const PRIVACY_COOKIE = "openseo_privacy";
@@ -46,34 +55,60 @@ export function productUpdatesOnByDefault(
}
export function defaultPrivacyChoices(optIn: boolean): PrivacyChoices {
- return { analytics: !optIn, ads: !optIn };
+ return { analytics: !optIn, referrals: !optIn, advertising: !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 {
+): SavedPrivacyChoices | 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 ?? "");
+ // Format: "a1.d0.m1" — analytics, Dub referrals, Meta advertising. Cookies
+ // saved before the Meta choice existed stop after the "d" flag.
+ const match = /^a([01])\.d([01])(?:\.m([01]))?$/.exec(raw ?? "");
if (!match) return null;
- return { analytics: match[1] === "1", ads: match[2] === "1" };
+ return {
+ analytics: match[1] === "1",
+ referrals: match[2] === "1",
+ advertising: match[3] ? match[3] === "1" : undefined,
+ };
}
-/** Choices that apply right now. Global Privacy Control always turns off
+/** Choices that apply right now: the saved ones, with the region default for
+ * any the visitor hasn't made. Global Privacy Control always turns off
* advertising and referral tracking, whatever was saved. */
export function effectivePrivacyChoices(args: {
- saved: PrivacyChoices | null;
+ saved: SavedPrivacyChoices | null;
optIn: boolean;
globalPrivacyControl: boolean;
}): PrivacyChoices {
- const choices = args.saved ?? defaultPrivacyChoices(args.optIn);
- return args.globalPrivacyControl ? { ...choices, ads: false } : choices;
+ const defaults = defaultPrivacyChoices(args.optIn);
+ const choices = args.saved
+ ? {
+ ...args.saved,
+ advertising: args.saved.advertising ?? defaults.advertising,
+ }
+ : defaults;
+ return args.globalPrivacyControl
+ ? { ...choices, referrals: false, advertising: false }
+ : choices;
+}
+
+/** The choices that apply to a request: the browser's saved choices, or the
+ * defaults for its location, under its Global Privacy Control header. */
+export function requestPrivacyChoices(
+ request: Request | undefined,
+): PrivacyChoices {
+ return effectivePrivacyChoices({
+ saved: readPrivacyCookie(request?.headers.get("cookie")),
+ optIn: requiresOptIn(request?.headers.get("cf-ipcountry")),
+ globalPrivacyControl: request?.headers.get("sec-gpc") === "1",
+ });
}
// ---- Browser helpers ----
@@ -102,15 +137,20 @@ const flag = (value: boolean) => (value ? "1" : "0");
export function savePrivacyChoices(choices: PrivacyChoices) {
writeCookie(
PRIVACY_COOKIE,
- `a${flag(choices.analytics)}.d${flag(choices.ads)}`,
+ `a${flag(choices.analytics)}.d${flag(choices.referrals)}.m${flag(choices.advertising)}`,
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) {
+ if (!choices.referrals) {
for (const name of ["dub_id", "dub_partner_data"]) writeCookie(name, "", 0);
}
+ // Withdrawing advertising permission removes the Meta Pixel's browser and
+ // click ids, so a later signup isn't attributed to an ad.
+ if (!choices.advertising) {
+ for (const name of ["_fbp", "_fbc"]) writeCookie(name, "", 0);
+ }
window.dispatchEvent(new Event(PRIVACY_CHOICES_CHANGED_EVENT));
}
diff --git a/web/.env.example b/web/.env.example
index d94e39d8..cb160c68 100644
--- a/web/.env.example
+++ b/web/.env.example
@@ -15,3 +15,4 @@ VITE_TURNSTILE_SITE_KEY=
# TURNSTILE_SECRET_KEY pairs with VITE_TURNSTILE_SITE_KEY; required in deployed
# environments alongside rate-limit and budget bindings
# LOOPS_API_KEY newsletter subscribe endpoint
+# META_PIXEL_ID Meta Pixel served by /js/meta.js (empty script when unset)
diff --git a/web/src/components/landing-page.css b/web/src/components/landing-page.css
index 91a1eeaa..10ccc5f9 100644
--- a/web/src/components/landing-page.css
+++ b/web/src/components/landing-page.css
@@ -1049,6 +1049,7 @@ body:has(.itc-campaign) {
display: flex;
gap: 20px;
}
-.itc-campaign-footer a:hover {
+.itc-campaign-footer a:hover,
+.itc-campaign-footer button:hover {
color: var(--ink);
}
diff --git a/web/src/components/privacy-choices.tsx b/web/src/components/privacy-choices.tsx
index 0f73aed7..28d88447 100644
--- a/web/src/components/privacy-choices.tsx
+++ b/web/src/components/privacy-choices.tsx
@@ -12,26 +12,49 @@ 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).
+// opt-out). The consent-based tracking here is the Meta Pixel and Dub's
+// referral cookie on partner links. Each loads where the visitor's choice or
+// region allows it; where opt-in is required, visitors from a partner link or
+// one of our Meta ads are asked. 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 [saved, setSaved] =
+ React.useState<ReturnType<typeof readPrivacyCookie>>(null);
const [optIn, setOptIn] = React.useState<boolean | null>(null);
- const [view, setView] = React.useState<"none" | "partner" | "dialog">("none");
+ const [view, setView] = React.useState<"none" | "partner" | "ad" | "dialog">(
+ "none",
+ );
React.useEffect(() => {
const savedChoices = readPrivacyCookie(document.cookie);
setSaved(savedChoices);
- if (isPartnerVisit() && !hasGlobalPrivacyControl()) {
- if (savedChoices) {
- if (savedChoices.ads) loadReferralAttribution();
- } else {
+ if (!hasGlobalPrivacyControl()) {
+ if (isPartnerVisit()) {
+ if (savedChoices) {
+ if (savedChoices.referrals) loadReferralAttribution();
+ } else {
+ void fetchOptIn().then((required) => {
+ setOptIn(required);
+ if (required) setView("partner");
+ else loadReferralAttribution();
+ });
+ }
+ }
+ // Without a saved Meta choice, /js/meta.js applies the region default
+ // itself. Only an ad visit, which gets the prompt where opt-in is
+ // required, looks up the region here.
+ if (
+ savedChoices?.advertising === undefined &&
+ isMetaAdVisit() &&
+ !isPartnerVisit()
+ ) {
void fetchOptIn().then((required) => {
setOptIn(required);
- if (required) setView("partner");
- else loadReferralAttribution();
+ if (required) setView("ad");
+ else loadMetaPixel();
});
+ } else if (savedChoices?.advertising !== false) {
+ loadMetaPixel();
}
}
@@ -40,15 +63,16 @@ export function PrivacyChoices() {
return () => window.removeEventListener(OPEN_PRIVACY_CHOICES_EVENT, open);
}, []);
- // The dialog shows location-based defaults to visitors who haven't chosen.
+ // The dialog shows region defaults for choices the visitor hasn't made.
+ const needsRegion = saved?.advertising === undefined;
React.useEffect(() => {
- if (view === "dialog" && saved === null && optIn === null) {
+ if (view === "dialog" && needsRegion && optIn === null) {
void fetchOptIn().then(setOptIn);
}
- }, [view, saved, optIn]);
+ }, [view, needsRegion, optIn]);
const choices =
- saved || optIn !== null
+ !needsRegion || optIn !== null
? effectivePrivacyChoices({
saved,
optIn: optIn ?? false,
@@ -57,34 +81,37 @@ export function PrivacyChoices() {
: 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;
+ // A loaded script can't be unloaded; a reload stops it.
+ const stopScripts =
+ (!next.referrals &&
+ document.querySelector("script[data-openseo-dub]") !== null) ||
+ (!next.advertising &&
+ document.querySelector("script[data-openseo-meta]") !== null);
savePrivacyChoices(next);
setSaved(next);
setView("none");
- if (next.ads) loadReferralAttribution();
- if (stopReferrals) location.reload();
+ if (next.advertising) loadMetaPixel();
+ if (next.referrals) loadReferralAttribution();
+ if (stopScripts) 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>
+ <Prompt onAnswer={(referrals) => save({ ...choices, referrals })}>
+ You came from a partner&apos;s link. Can we keep a 90-day cookie (Dub)
+ so they get credit if you sign up?
+ </Prompt>
+ );
+ }
+
+ if (view === "ad") {
+ return (
+ <Prompt onAnswer={(advertising) => save({ ...choices, advertising })}>
+ You came from one of our ads on Facebook or Instagram. Can Meta measure
+ whether it led to a sign-up?
+ </Prompt>
);
}
@@ -145,9 +172,20 @@ function ChoicesForm({
? "Off because your browser sends Global Privacy Control."
: "A 90-day cookie that credits the partner who sent you (Dub)."
}
- checked={draft.ads && !gpc}
+ checked={draft.referrals && !gpc}
disabled={gpc}
- onChange={(ads) => setDraft({ ...draft, ads })}
+ onChange={(referrals) => setDraft({ ...draft, referrals })}
+ />
+ <ChoiceRow
+ label="Advertising"
+ description={
+ gpc
+ ? "Off because your browser sends Global Privacy Control."
+ : "Lets Meta measure which of our ads lead to sign-ups (Meta Pixel)."
+ }
+ checked={draft.advertising && !gpc}
+ disabled={gpc}
+ onChange={(advertising) => setDraft({ ...draft, advertising })}
/>
</div>
<div className="mt-4 flex justify-end gap-2">
@@ -198,8 +236,25 @@ function Panel(props: { className: string; children: React.ReactNode }) {
);
}
-// 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 Prompt(props: {
+ children: React.ReactNode;
+ onAnswer: (allow: boolean) => void;
+}) {
+ return (
+ <Panel className="max-w-sm">
+ <p>{props.children}</p>
+ <div className="mt-3 flex justify-end gap-2">
+ <PanelButton onClick={() => props.onAnswer(false)}>
+ No thanks
+ </PanelButton>
+ <PanelButton onClick={() => props.onAnswer(true)}>Allow</PanelButton>
+ </div>
+ </Panel>
+ );
+}
+
+// A 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;
@@ -240,6 +295,15 @@ const isPartnerVisit = () => {
return params.has("dub_id") || params.has("via");
};
+// A click on one of our Facebook or Instagram ads: Meta adds ?fbclid=, and
+// the ads' UTM tags name the platform.
+const META_AD_SOURCES = new Set(["facebook", "instagram", "meta", "fb", "ig"]);
+const isMetaAdVisit = () => {
+ const params = new URLSearchParams(location.search);
+ const source = params.get("utm_source")?.toLowerCase() ?? "";
+ return params.has("fbclid") || META_AD_SOURCES.has(source);
+};
+
// 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.
@@ -252,6 +316,23 @@ async function fetchOptIn(): Promise<boolean> {
}
}
+// The Meta Pixel, served first-party by routes/js/meta[.]js.ts. Its `_fbp` and
+// `_fbc` cookies on `.openseo.so` let the app attribute a signup to an ad.
+function loadMetaPixel() {
+ if (document.querySelector("script[data-openseo-meta]")) return;
+ const script = document.createElement("script");
+ script.async = true;
+ script.src = "/js/meta.js";
+ script.dataset.openseoMeta = "";
+ // The route serves an empty script where the pixel isn't allowed. Dropping
+ // that tag keeps a save from reloading the page to stop a pixel that never
+ // ran, and lets an Allow on this page request the pixel again.
+ script.onload = () => {
+ if (!("fbq" in window)) script.remove();
+ };
+ document.head.appendChild(script);
+}
+
// 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.
diff --git a/web/src/routeTree.gen.ts b/web/src/routeTree.gen.ts
index c8155b0a..5cfb6d29 100644
--- a/web/src/routeTree.gen.ts
+++ b/web/src/routeTree.gen.ts
@@ -55,6 +55,7 @@ import { Route as DocsSplatRouteImport } from './routes/docs/$'
import { Route as DocsLlmsDottxtRouteImport } from './routes/docs/llms[.]txt'
import { Route as GuidesIndexRouteImport } from './routes/guides/index'
import { Route as GuidesSplatRouteImport } from './routes/guides/$'
+import { Route as JsMetaDotjsRouteImport } from './routes/js/meta[.]js'
import { Route as JsScriptDotjsRouteImport } from './routes/js/script[.]js'
import { Route as MarketingFeaturesIndexRouteImport } from './routes/_marketing/features/index'
import { Route as MarketingFeaturesAiBrandVisibilityRouteImport } from './routes/_marketing/features/ai-brand-visibility'
@@ -343,6 +344,11 @@ const GuidesSplatRoute = GuidesSplatRouteImport.update({
path: '/guides/$',
getParentRoute: () => rootRouteImport,
} as any)
+const JsMetaDotjsRoute = JsMetaDotjsRouteImport.update({
+ id: '/js/meta.js',
+ path: '/js/meta.js',
+ getParentRoute: () => rootRouteImport,
+} as any)
const JsScriptDotjsRoute = JsScriptDotjsRouteImport.update({
id: '/js/script.js',
path: '/js/script.js',
@@ -656,6 +662,7 @@ export interface FileRoutesByFullPath {
'/docs/$': typeof DocsSplatRoute
'/docs/llms.txt': typeof DocsLlmsDottxtRoute
'/guides/$': typeof GuidesSplatRoute
+ '/js/meta.js': typeof JsMetaDotjsRoute
'/js/script.js': typeof JsScriptDotjsRoute
'/blogs/': typeof BlogsIndexRoute
'/docs/': typeof DocsIndexRoute
@@ -747,6 +754,7 @@ export interface FileRoutesByTo {
'/docs/$': typeof DocsSplatRoute
'/docs/llms.txt': typeof DocsLlmsDottxtRoute
'/guides/$': typeof GuidesSplatRoute
+ '/js/meta.js': typeof JsMetaDotjsRoute
'/js/script.js': typeof JsScriptDotjsRoute
'/blogs': typeof BlogsIndexRoute
'/docs': typeof DocsIndexRoute
@@ -840,6 +848,7 @@ export interface FileRoutesById {
'/docs/$': typeof DocsSplatRoute
'/docs/llms.txt': typeof DocsLlmsDottxtRoute
'/guides/$': typeof GuidesSplatRoute
+ '/js/meta.js': typeof JsMetaDotjsRoute
'/js/script.js': typeof JsScriptDotjsRoute
'/_marketing/': typeof MarketingIndexRoute
'/blogs/': typeof BlogsIndexRoute
@@ -934,6 +943,7 @@ export interface FileRouteTypes {
| '/docs/$'
| '/docs/llms.txt'
| '/guides/$'
+ | '/js/meta.js'
| '/js/script.js'
| '/blogs/'
| '/docs/'
@@ -1025,6 +1035,7 @@ export interface FileRouteTypes {
| '/docs/$'
| '/docs/llms.txt'
| '/guides/$'
+ | '/js/meta.js'
| '/js/script.js'
| '/blogs'
| '/docs'
@@ -1117,6 +1128,7 @@ export interface FileRouteTypes {
| '/docs/$'
| '/docs/llms.txt'
| '/guides/$'
+ | '/js/meta.js'
| '/js/script.js'
| '/_marketing/'
| '/blogs/'
@@ -1186,6 +1198,7 @@ export interface RootRouteChildren {
DocsSplatRoute: typeof DocsSplatRoute
DocsLlmsDottxtRoute: typeof DocsLlmsDottxtRoute
GuidesSplatRoute: typeof GuidesSplatRoute
+ JsMetaDotjsRoute: typeof JsMetaDotjsRoute
JsScriptDotjsRoute: typeof JsScriptDotjsRoute
BlogsIndexRoute: typeof BlogsIndexRoute
DocsIndexRoute: typeof DocsIndexRoute
@@ -1516,6 +1529,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof GuidesSplatRouteImport
parentRoute: typeof rootRouteImport
}
+ '/js/meta.js': {
+ id: '/js/meta.js'
+ path: '/js/meta.js'
+ fullPath: '/js/meta.js'
+ preLoaderRoute: typeof JsMetaDotjsRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/js/script.js': {
id: '/js/script.js'
path: '/js/script.js'
@@ -2043,6 +2063,7 @@ const rootRouteChildren: RootRouteChildren = {
DocsSplatRoute: DocsSplatRoute,
DocsLlmsDottxtRoute: DocsLlmsDottxtRoute,
GuidesSplatRoute: GuidesSplatRoute,
+ JsMetaDotjsRoute: JsMetaDotjsRoute,
JsScriptDotjsRoute: JsScriptDotjsRoute,
BlogsIndexRoute: BlogsIndexRoute,
DocsIndexRoute: DocsIndexRoute,
diff --git a/web/src/routes/_campaign.tsx b/web/src/routes/_campaign.tsx
index 794644f2..6e0ac944 100644
--- a/web/src/routes/_campaign.tsx
+++ b/web/src/routes/_campaign.tsx
@@ -1,6 +1,7 @@
import { createFileRoute, Link, Outlet } from "@tanstack/react-router";
import { useEffect } from "react";
import { SIGNUP_URL } from "@/components/landing-page";
+import { PrivacyChoicesLink } from "@/components/privacy-choices";
/**
* Layout for paid-traffic landing pages. No site navigation: the only ways
@@ -55,6 +56,9 @@ function CampaignLayout() {
<nav aria-label="Legal">
<a href="/privacy">Privacy</a>
<a href="/terms-and-conditions">Terms</a>
+ {/* Ads land here, and the pixel can load here, so the opt-out
+ must be reachable without the site footer. */}
+ <PrivacyChoicesLink />
</nav>
</div>
</footer>
diff --git a/web/src/routes/js/meta[.]js.ts b/web/src/routes/js/meta[.]js.ts
new file mode 100644
index 00000000..50a45cc3
--- /dev/null
+++ b/web/src/routes/js/meta[.]js.ts
@@ -0,0 +1,38 @@
+import { env } from "cloudflare:workers";
+import { createFileRoute } from "@tanstack/react-router";
+import { requestPrivacyChoices } from "../../../../src/shared/privacy-choices";
+
+// Meta Pixel, served first-party. The browser requests it unless the visitor
+// turned advertising off or sends Global Privacy Control
+// (components/privacy-choices.tsx). This route makes the final call from the
+// privacy cookie, CF-IPCountry and Sec-GPC, so a visitor without a saved
+// choice needs no separate region lookup. Where the pixel isn't allowed, or
+// on a worker without META_PIXEL_ID (like preview), it serves an empty script.
+// The pixel's `_fbp`/`_fbc` cookies are what the app's signup Conversions API
+// event (src/server/referrals/meta.ts) attributes against.
+export const Route = createFileRoute("/js/meta.js")({
+ server: {
+ handlers: {
+ GET: ({ request }) => {
+ const value: unknown = Reflect.get(env, "META_PIXEL_ID");
+ const pixelId = typeof value === "string" ? value : "";
+ const allowed = pixelId && requestPrivacyChoices(request).advertising;
+ return new Response(allowed ? buildPixelScript(pixelId) : "", {
+ headers: {
+ "content-type": "application/javascript; charset=utf-8",
+ // The answer depends on the visitor's cookie and location.
+ "cache-control": "private, no-store",
+ },
+ });
+ },
+ },
+ },
+});
+
+// Meta's base code, with automatic configuration turned off before init so the
+// pixel doesn't collect button text or page metadata. PageView is the only
+// event sent.
+function buildPixelScript(pixelId: string) {
+ const id = JSON.stringify(pixelId);
+ return `!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('set','autoConfig',false,${id});fbq('init',${id});fbq('track','PageView');`;
+}
diff --git a/web/tests/meta-pixel.test.ts b/web/tests/meta-pixel.test.ts
new file mode 100644
index 00000000..5a09954c
--- /dev/null
+++ b/web/tests/meta-pixel.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("cloudflare:workers", () => ({ env: { META_PIXEL_ID: "123" } }));
+vi.mock("@tanstack/react-router", () => ({
+ createFileRoute: () => (options: unknown) => options,
+}));
+import { Route } from "../src/routes/js/meta[.]js";
+
+const route = Route as unknown as {
+ server: { handlers: { GET: (args: { request: Request }) => Response } };
+};
+
+async function servesPixel(country: string, headers = {}) {
+ const response = route.server.handlers.GET({
+ request: new Request("https://openseo.so/js/meta.js", {
+ headers: { "cf-ipcountry": country, ...headers },
+ }),
+ });
+ // The answer differs per visitor, so no shared cache may keep it.
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
+ return (await response.text()).includes("fbq('init'");
+}
+
+describe("/js/meta.js", () => {
+ it("serves the pixel only where the visitor's advertising choice allows it", async () => {
+ // The full set of region and saved-choice cases is in
+ // src/shared/privacy-choices.test.ts; this covers the route's inputs.
+ expect(await servesPixel("DE", { cookie: "openseo_privacy=a0.d0.m1" })).toBe(
+ true,
+ );
+ expect(await servesPixel("US", { "sec-gpc": "1" })).toBe(false);
+ });
+});