Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(analytics): attribute cloud signups to Google Ads clicks (gclid) (#15048)

Jannik Maierhöfer535ac9da1256
diff --git a/web/src/__tests__/server/unit/signupAttribution.servertest.ts b/web/src/__tests__/server/unit/signupAttribution.servertest.ts
new file mode 100644
index 0000000000..9d99ada80d
--- /dev/null
+++ b/web/src/__tests__/server/unit/signupAttribution.servertest.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+
+import { getGclidFromRequest } from "@/src/features/auth/lib/signupAttribution";
+
+// The gclid is read from first-party cookies on .langfuse.com so that
+// cloud_signup_complete events can be attributed to Google Ads clicks that
+// landed on the langfuse.com marketing site. See signupAttribution.ts for
+// the source priority.
+describe("getGclidFromRequest", () => {
+ const posthogCookieName = "ph_phc_someProjectApiKey123_posthog";
+
+ it("returns undefined without any attribution cookies", () => {
+ expect(getGclidFromRequest({ cookies: {} })).toBeUndefined();
+ });
+
+ it("reads the dedicated lf_gclid cookie", () => {
+ expect(
+ getGclidFromRequest({
+ cookies: { lf_gclid: "Cj0KCQjw_test-123" },
+ }),
+ ).toBe("Cj0KCQjw_test-123");
+ });
+
+ it("prefers lf_gclid over _gcl_aw", () => {
+ expect(
+ getGclidFromRequest({
+ cookies: {
+ lf_gclid: "gclid-from-dedicated-cookie",
+ _gcl_aw: "GCL.1700000000.gclid-from-google-cookie",
+ },
+ }),
+ ).toBe("gclid-from-dedicated-cookie");
+ });
+
+ it("parses the gclid from Google's _gcl_aw linker cookie", () => {
+ expect(
+ getGclidFromRequest({
+ cookies: { _gcl_aw: "GCL.1700000000.Cj0KCQjw_abcDEF-123" },
+ }),
+ ).toBe("Cj0KCQjw_abcDEF-123");
+ });
+
+ it("ignores a malformed _gcl_aw cookie", () => {
+ expect(
+ getGclidFromRequest({ cookies: { _gcl_aw: "not-the-format" } }),
+ ).toBeUndefined();
+ });
+
+ it("falls back to the gclid in the PostHog first-touch URL", () => {
+ const cookieValue = JSON.stringify({
+ distinct_id: "some-id",
+ $initial_person_info: {
+ r: "https://www.google.com/",
+ u: "https://langfuse.com/?utm_source=x&gclid=Cj0-initial-touch",
+ },
+ });
+ expect(
+ getGclidFromRequest({
+ cookies: { [posthogCookieName]: cookieValue },
+ }),
+ ).toBe("Cj0-initial-touch");
+ });
+
+ it("returns undefined when the PostHog first-touch URL has no gclid", () => {
+ const cookieValue = JSON.stringify({
+ distinct_id: "some-id",
+ $initial_person_info: { r: "", u: "https://langfuse.com/docs" },
+ });
+ expect(
+ getGclidFromRequest({
+ cookies: { [posthogCookieName]: cookieValue },
+ }),
+ ).toBeUndefined();
+ });
+
+ it("ignores a malformed PostHog cookie", () => {
+ expect(
+ getGclidFromRequest({
+ cookies: { [posthogCookieName]: "%%%not-json" },
+ }),
+ ).toBeUndefined();
+ });
+
+ it("rejects values with unexpected characters or excessive length", () => {
+ expect(
+ getGclidFromRequest({
+ cookies: { lf_gclid: '"><script>alert(1)</script>' },
+ }),
+ ).toBeUndefined();
+ expect(
+ getGclidFromRequest({
+ cookies: { lf_gclid: "a".repeat(513) },
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
index f6355dd11c..7438333bba 100644
--- a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
+++ b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
@@ -15,6 +15,10 @@ export async function createUserEmailPassword(
email: string,
password: string,
name: string,
+ options?: {
+ /** Google Ads click id, see getGclidFromRequest */
+ gclid?: string;
+ },
) {
if (!isValidPassword(password))
throw new Error("Password needs to be at least 8 characters long.");
@@ -42,7 +46,10 @@ export async function createUserEmailPassword(
},
});
- await createProjectMembershipsOnSignup(newUser, { userWasJustCreated: true });
+ await createProjectMembershipsOnSignup(newUser, {
+ userWasJustCreated: true,
+ gclid: options?.gclid,
+ });
return newUser.id;
}
diff --git a/web/src/features/auth-credentials/server/signupApiHandler.ts b/web/src/features/auth-credentials/server/signupApiHandler.ts
index 1495aa8ff0..371096a70e 100644
--- a/web/src/features/auth-credentials/server/signupApiHandler.ts
+++ b/web/src/features/auth-credentials/server/signupApiHandler.ts
@@ -1,5 +1,6 @@
import { env } from "@/src/env.mjs";
import { createUserEmailPassword } from "@/src/features/auth-credentials/lib/credentialsServerUtils";
+import { getGclidFromRequest } from "@/src/features/auth/lib/signupAttribution";
import { signupSchema } from "@/src/features/auth/lib/signupSchema";
import { getSsoAuthProviderIdForDomain } from "@/src/ee/features/multi-tenant-sso/utils";
import { ENTERPRISE_SSO_REQUIRED_MESSAGE } from "@/src/features/auth/constants";
@@ -95,6 +96,7 @@ export async function signupApiHandler(
body.email,
body.password,
body.name,
+ { gclid: getGclidFromRequest(req) },
);
} catch (error) {
const message =
diff --git a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts
index 49040f2a86..d87bc4b23f 100644
--- a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts
+++ b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts
@@ -16,7 +16,11 @@ export async function createProjectMembershipsOnSignup(
email: string | null;
name: string | null;
},
- options?: { userWasJustCreated?: boolean },
+ options?: {
+ userWasJustCreated?: boolean;
+ /** Google Ads click id, see getGclidFromRequest */
+ gclid?: string;
+ },
) {
try {
const isCloudDeployment = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
@@ -292,6 +296,8 @@ export async function createProjectMembershipsOnSignup(
hasDemoAccess: demoProject !== undefined,
hasDefaultOrg: defaultOrgs.length > 0,
hasDefaultProject: defaultProjects.length > 0,
+ // Google Ads click id for ad conversion attribution
+ ...(options?.gclid ? { gclid: options.gclid } : {}),
},
});
await posthog.shutdown();
diff --git a/web/src/features/auth/lib/signupAttribution.ts b/web/src/features/auth/lib/signupAttribution.ts
new file mode 100644
index 0000000000..426b698655
--- /dev/null
+++ b/web/src/features/auth/lib/signupAttribution.ts
@@ -0,0 +1,82 @@
+// gclids are opaque tokens (typically ~60-120 chars); cap length and charset to
+// avoid persisting arbitrary user-controlled strings into analytics events
+const MAX_GCLID_LENGTH = 512;
+const GCLID_FORMAT = /^[A-Za-z0-9_-]+$/;
+
+// posthog-js persistence cookie, named after the project api key
+const POSTHOG_COOKIE_NAME = /^ph_phc_[A-Za-z0-9]+_posthog$/;
+
+type RequestWithCookies = {
+ cookies: Partial<Record<string, string>>;
+};
+
+function sanitizeGclid(value: string | null | undefined): string | undefined {
+ if (!value) return undefined;
+ const trimmed = value.trim();
+ if (
+ trimmed.length === 0 ||
+ trimmed.length > MAX_GCLID_LENGTH ||
+ !GCLID_FORMAT.test(trimmed)
+ )
+ return undefined;
+ return trimmed;
+}
+
+/**
+ * Extracts the Google Ads click id (gclid) of the ad click that led this
+ * browser to Langfuse, if any. Used to attribute `cloud_signup_complete`
+ * events to Google Ads campaigns (uploaded via a PostHog CDP destination).
+ *
+ * All sources are first-party cookies on `.langfuse.com`, so they are sent
+ * along with every request to the cloud app regardless of which page the ad
+ * click originally landed on (usually the langfuse.com marketing site):
+ *
+ * 1. `lf_gclid` — set by langfuse.com on every landing with a `?gclid=` param
+ * (last ad click wins).
+ * 2. `_gcl_aw` — Google's own conversion-linker cookie set by gtag.js on
+ * langfuse.com, format `GCL.<timestamp>.<gclid>`.
+ * 3. The PostHog cookie's `$initial_person_info.u` (the URL of the visitor's
+ * first-ever pageview) — first-touch fallback, e.g. when ad-consent was
+ * not given so gtag never ran.
+ */
+export function getGclidFromRequest(
+ req: RequestWithCookies,
+): string | undefined {
+ // 1. dedicated first-party cookie set by the marketing site
+ const fromDedicatedCookie = sanitizeGclid(req.cookies["lf_gclid"]);
+ if (fromDedicatedCookie) return fromDedicatedCookie;
+
+ // 2. Google conversion-linker cookie: GCL.<timestamp>.<gclid>
+ const gclAw = req.cookies["_gcl_aw"];
+ if (gclAw) {
+ const fromGclAw = sanitizeGclid(gclAw.split(".").slice(2).join("."));
+ if (fromGclAw) return fromGclAw;
+ }
+
+ // 3. PostHog persistence cookie: first-touch URL may contain the gclid
+ const posthogCookie = Object.entries(req.cookies).find(([name]) =>
+ POSTHOG_COOKIE_NAME.test(name),
+ )?.[1];
+ if (posthogCookie) {
+ try {
+ const parsed: unknown = JSON.parse(posthogCookie);
+ const initialUrl =
+ typeof parsed === "object" &&
+ parsed !== null &&
+ "$initial_person_info" in parsed &&
+ typeof parsed.$initial_person_info === "object" &&
+ parsed.$initial_person_info !== null &&
+ "u" in parsed.$initial_person_info &&
+ typeof parsed.$initial_person_info.u === "string"
+ ? parsed.$initial_person_info.u
+ : undefined;
+ if (initialUrl) {
+ return sanitizeGclid(new URL(initialUrl).searchParams.get("gclid"));
+ }
+ } catch {
+ // malformed cookie — attribution is best-effort, ignore
+ }
+ }
+
+ return undefined;
+}
diff --git a/web/src/pages/api/auth/[...nextauth].ts b/web/src/pages/api/auth/[...nextauth].ts
index 80c9550f47..2e524a7104 100644
--- a/web/src/pages/api/auth/[...nextauth].ts
+++ b/web/src/pages/api/auth/[...nextauth].ts
@@ -1,6 +1,7 @@
import { validateHeaderValue } from "node:http";
import { getAuthOptions } from "@/src/server/auth";
+import { getGclidFromRequest } from "@/src/features/auth/lib/signupAttribution";
import { getCookieName } from "@/src/server/utils/cookies";
import { env } from "@/src/env.mjs";
import { logger } from "@langfuse/shared/src/server";
@@ -135,7 +136,11 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) {
}
// Do whatever you want here, before the request is passed down to `NextAuth`
- const authOptions = await getAuthOptions();
+ // Pass Google Ads click attribution from first-party cookies so that new
+ // SSO signups can be attributed to ad clicks (cloud_signup_complete event).
+ const authOptions = await getAuthOptions({
+ gclid: getGclidFromRequest(req),
+ });
// https://github.com/nextauthjs/next-auth/issues/2408#issuecomment-1382629234
// for api routes, we need to call the headers in the api route itself
// disable caching for anything auth related
diff --git a/web/src/pages/api/auth/signup-verify.ts b/web/src/pages/api/auth/signup-verify.ts
index 9577f704dc..8bd4d0b79b 100644
--- a/web/src/pages/api/auth/signup-verify.ts
+++ b/web/src/pages/api/auth/signup-verify.ts
@@ -2,6 +2,7 @@ import { env } from "@/src/env.mjs";
import { isEmailVerificationRequired } from "@/src/features/auth-credentials/lib/credentialsUtils";
import { validateSignupEligibility } from "@/src/features/auth-credentials/server/signupApiHandler";
import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";
+import { getGclidFromRequest } from "@/src/features/auth/lib/signupAttribution";
import { prisma } from "@langfuse/shared/src/db";
import { logger } from "@langfuse/shared/src/server";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -84,6 +85,7 @@ export default async function handler(
await createProjectMembershipsOnSignup(newUser, {
userWasJustCreated: true,
+ gclid: getGclidFromRequest(req),
});
// Trigger new user signup event
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 77b94d188b..d54e07c287 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -590,7 +590,12 @@ if (env.AUTH_WORDPRESS_CLIENT_ID && env.AUTH_WORDPRESS_CLIENT_SECRET)
// Extend Prisma Adapter
const prismaAdapter = PrismaAdapter(prisma);
const ignoredAccountFields = env.AUTH_IGNORE_ACCOUNT_FIELDS?.split(",") ?? [];
-const extendedPrismaAdapter: Adapter = {
+// Factory instead of a static adapter so that per-request signup attribution
+// (Google Ads click id from first-party cookies) can reach the signup event
+// captured for new SSO users.
+const createExtendedPrismaAdapter = (signupAttribution?: {
+ gclid?: string;
+}): Adapter => ({
...prismaAdapter,
async createUser(profile: Omit<AdapterUser, "id">) {
if (!prismaAdapter.createUser)
@@ -610,7 +615,10 @@ const extendedPrismaAdapter: Adapter = {
const user = await prismaAdapter.createUser(profile);
- await createProjectMembershipsOnSignup(user, { userWasJustCreated: true });
+ await createProjectMembershipsOnSignup(user, {
+ userWasJustCreated: true,
+ gclid: signupAttribution?.gclid,
+ });
return user;
},
@@ -652,7 +660,9 @@ const extendedPrismaAdapter: Adapter = {
select: { id: true, email: true, name: true },
});
if (user) {
- await createProjectMembershipsOnSignup(user);
+ await createProjectMembershipsOnSignup(user, {
+ gclid: signupAttribution?.gclid,
+ });
}
},
@@ -723,14 +733,20 @@ const extendedPrismaAdapter: Adapter = {
return verificationToken;
},
-};
+});
/**
* Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
*
+ * @param signupAttribution - per-request marketing attribution (e.g. Google
+ * Ads click id) attached to the signup analytics event if the request results
+ * in a new user. Only passed by the NextAuth API route.
+ *
* @see https://next-auth.js.org/configuration/options
*/
-export async function getAuthOptions(): Promise<NextAuthOptions> {
+export async function getAuthOptions(signupAttribution?: {
+ gclid?: string;
+}): Promise<NextAuthOptions> {
let dynamicSsoProviders: Provider[] = [];
try {
dynamicSsoProviders = await loadSsoProviders();
@@ -1070,7 +1086,7 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
});
},
},
- adapter: extendedPrismaAdapter,
+ adapter: createExtendedPrismaAdapter(signupAttribution),
providers,
pages: {
signIn: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/sign-in`,