Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cdp): stop sending Meta ad clicks Meta rejects as too old (#92152)

Harley Alexander67a6bfa7b291
diff --git a/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts
index 1b25dc93d274..717afd7ba4e0 100644
--- a/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts
+++ b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.test.ts
@@ -145,19 +145,95 @@ describe('meta ads template', () => {
expect(fetchResponse.finished).toBe(true)
expect(fetchResponse.error).toBeUndefined()
})
- it('wraps a raw fbclid into an fbc click ID', async () => {
- const response = await tester.invokeMapping(
- 'Page Viewed',
- { accessToken: 'access-token', pixelId: 'pixel-id' },
- createAdDestinationPayload({
- event: { event: '$pageview', properties: {} },
- person: { properties: { fbclid: 'AbC_123-x' } },
- })
- )
+ describe('fbc click ID', () => {
+ // The event is fixed at 2025-01-01T00:00:00Z, so a click stamped 89 days earlier is inside
+ // Meta's 90-day window and one stamped 91 days earlier is outside it.
+ const eventMs = DateTime.fromISO('2025-01-01T00:00:00Z').toMillis()
+ const dayMs = 24 * 60 * 60 * 1000
- expect(response.error).toBeUndefined()
- const body = parseJSON((response.invocation.queueParameters as { body: string }).body)
- expect(body.data[0].user_data.fbc).toEqual('fb.1.1735689600000.AbC_123-x')
+ it.each([
+ {
+ name: 'sends the $fbc PostHog stamped when it saw the click',
+ event: {},
+ person: { $fbc: `fb.1.${eventMs - 89 * dayMs}.AbC_123-x` },
+ expected: `fb.1.${eventMs - 89 * dayMs}.AbC_123-x`,
+ },
+ {
+ name: 'drops a click Meta would reject as older than 90 days',
+ event: {},
+ person: { $fbc: `fb.1.${eventMs - 91 * dayMs}.AbC_123-x` },
+ expected: undefined,
+ },
+ {
+ name: 'prefers the fbc the site stores itself',
+ event: {},
+ person: { fbc: `fb.1.${eventMs}.site-owned`, $fbc: `fb.1.${eventMs}.AbC_123-x` },
+ expected: `fb.1.${eventMs}.site-owned`,
+ },
+ {
+ name: 'stamps an fbclid on this event with the event time',
+ event: { fbclid: 'AbC_123-x' },
+ person: {},
+ expected: `fb.1.${eventMs}.AbC_123-x`,
+ },
+ {
+ name: 'sends nothing for an fbclid of unknown age',
+ event: {},
+ person: { fbclid: 'AbC_123-x' },
+ expected: undefined,
+ },
+ {
+ name: 'does not redate a stale click the event still carries',
+ event: { fbclid: 'AbC_123-x' },
+ person: { $fbc: `fb.1.${eventMs - 91 * dayMs}.AbC_123-x` },
+ expected: undefined,
+ },
+ {
+ name: "keeps the appendix Meta's parameter builder adds",
+ event: {},
+ person: { fbc: `fb.1.${eventMs}.AbC_123-x.Bg` },
+ expected: `fb.1.${eventMs}.AbC_123-x.Bg`,
+ },
+ {
+ name: "keeps the parameter builder's longer appendix",
+ event: {},
+ person: { fbc: `fb.1.${eventMs}.AbC_123-x.AQYAAQAA` },
+ expected: `fb.1.${eventMs}.AbC_123-x.AQYAAQAA`,
+ },
+ {
+ name: 'drops a click stamped after the conversion',
+ event: {},
+ person: { $fbc: `fb.1.${eventMs + dayMs}.AbC_123-x` },
+ expected: undefined,
+ },
+ {
+ name: 'keeps a click stamped a moment after the event by a drifting clock',
+ event: {},
+ person: { $fbc: `fb.1.${eventMs + 1000}.AbC_123-x` },
+ expected: `fb.1.${eventMs + 1000}.AbC_123-x`,
+ },
+ {
+ name: 'sends the event when a person holds a non-string fbc',
+ event: {},
+ person: { fbc: 1735689600000 },
+ expected: undefined,
+ },
+ ])('$name', async ({ event, person, expected }) => {
+ const response = await tester.invokeMapping(
+ 'Page Viewed',
+ { accessToken: 'access-token', pixelId: 'pixel-id' },
+ createAdDestinationPayload({
+ event: { event: '$pageview', properties: event },
+ person: { properties: person },
+ })
+ )
+
+ expect(response.error).toBeUndefined()
+ const body = parseJSON((response.invocation.queueParameters as { body: string }).body)
+ expect(body.data[0].user_data.fbc).toEqual(expected)
+ // A candidate the template rejects must cost only the fbc field, never the whole send.
+ expect(body.data[0].user_data.em).toBeDefined()
+ })
})
it('surfaces error responses', async () => {
diff --git a/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts
index 3d261f559ca5..3941c944e987 100644
--- a/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts
+++ b/nodejs/src/cdp/templates/_destinations/meta_ads/meta.template.ts
@@ -37,6 +37,20 @@ const multiContents =
"{arrayMap(x -> ({'id': x.sku ?? x.product_id, 'quantity': x.quantity, 'item_price': x.price}), arrayFilter(x -> (not empty(x.sku) or not empty(x.product_id)) and not empty(x.quantity), event.properties.products ?? []))}"
const numItems = '{arrayReduce((acc, curr) -> acc + curr.quantity, event.properties.products ?? [], 0)}'
+// Meta's _fbc cookie value, `fb.<subdomainIndex>.<clickTimeMs>.<fbclid>`. Sources in order: a value
+// the site stores itself, the $fbc PostHog stamps when it sees the fbclid, and an fbclid on this
+// event. The last one only applies when the person holds no $fbc, because a click PostHog already
+// dated must not come back undated. The code drops a value Meta would reject as too old.
+const fbc =
+ "{person.properties.fbc ?? person.properties.$fbc ?? (not empty(event.properties.fbclid) ? f'fb.1.{toUnixTimestampMilli(event.timestamp)}.{event.properties.fbclid}' : '')}"
+
+const NINETY_DAYS_MS = 90 * 24 * 60 * 60 * 1000
+const CLOCK_SKEW_TOLERANCE_MS = 5 * 60 * 1000
+
+// Meta's _fbp cookie value, `fb.<subdomainIndex>.<creationTimeMs>.<randomNumber>`. It identifies a
+// browser rather than a click, so PostHog cannot derive it and this reads a value the site mints.
+const fbp = "{person.properties.fbp ?? ''}"
+
export const template: HogFunctionTemplate = {
free: false,
status: 'alpha',
@@ -89,9 +103,29 @@ fn parseValueIfArray(value) {
return value
}
+// Meta rejects an ad click older than 90 days, the lifetime of the pixel's _fbc cookie, so a stale
+// click is dropped instead of sent. The value states its own click time, in segment 3. Meta's
+// parameter builder library appends a fifth segment, which stays on the value it sends back.
+fn freshClickId(value) {
+ if (typeof(value) != 'string') {
+ return null
+ }
+ if (not match(value, '^fb[.][0-9]+[.][0-9]+[.][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)?\$')) {
+ return null
+ }
+ // A click cannot precede the conversion it caused. The tolerance holds a click and the pageview
+ // that reports it, stamped from one browser clock, in either order.
+ let ageMs := toUnixTimestampMilli(event.timestamp) - toFloat(splitByString('.', value)[3])
+ if (ageMs < ${-CLOCK_SKEW_TOLERANCE_MS} or ageMs >= ${NINETY_DAYS_MS}) {
+ return null
+ }
+ return value
+}
+
for (let key, value in inputs.userData) {
- if (not empty(value)) {
- body.data.1.user_data[key] := parseValueIfArray(value)
+ let cleaned := key == 'fbc' ? freshClickId(value) : parseValueIfArray(value)
+ if (not empty(cleaned)) {
+ body.data.1.user_data[key] := cleaned
}
}
@@ -202,7 +236,8 @@ if (res.status >= 400) {
em: '{sha256Hex(lower(person.properties.email))}',
fn: '{sha256Hex(lower(person.properties.first_name))}',
ln: '{sha256Hex(lower(person.properties.last_name))}',
- fbc: "{match(person.properties.fbclid ?? person.properties.$initial_fbclid ?? '', '^fb[.][0-9]+[.][0-9]+[.][A-Za-z0-9_-]+$') ? person.properties.fbclid ?? person.properties.$initial_fbclid : (match(person.properties.fbclid ?? person.properties.$initial_fbclid ?? '', '^[A-Za-z0-9_-]+$') ? f'fb.1.{toUnixTimestampMilli(now())}.{person.properties.fbclid ?? person.properties.$initial_fbclid}' : '')}",
+ fbc,
+ fbp,
client_user_agent: '{event.properties.$raw_user_agent}',
},
secret: false,
diff --git a/nodejs/tests/fixtures/hog-bytecode/7ea5f98b35daa0db13121c376e6ad655100c222b896113dc534463ff693aa022.json b/nodejs/tests/fixtures/hog-bytecode/7ea5f98b35daa0db13121c376e6ad655100c222b896113dc534463ff693aa022.json
new file mode 100644
index 000000000000..d203aa37a090
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/7ea5f98b35daa0db13121c376e6ad655100c222b896113dc534463ff693aa022.json
@@ -0,0 +1 @@
+["_H",1,32,"fbc",32,"properties",32,"person",1,3,47,9,35,32,"$fbc",32,"properties",32,"person",1,3,47,43,35,32,"fbclid",32,"properties",32,"event",1,3,2,"empty",1,5,40,26,32,"fb.1.",32,"timestamp",32,"event",1,2,2,"toUnixTimestampMilli",1,32,".",32,"fbclid",32,"properties",32,"event",1,3,2,"concat",4,39,2,32,"",38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/8c9c891c084713cdf87aeab8c2624e00af87fd47097bae6da35e4a36f1be4b28.json b/nodejs/tests/fixtures/hog-bytecode/8c9c891c084713cdf87aeab8c2624e00af87fd47097bae6da35e4a36f1be4b28.json
new file mode 100644
index 000000000000..06dc064e8364
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/8c9c891c084713cdf87aeab8c2624e00af87fd47097bae6da35e4a36f1be4b28.json
@@ -0,0 +1 @@
+["_H",1,32,"fbp",32,"properties",32,"person",1,3,47,3,35,32,"",38]
diff --git a/nodejs/tests/fixtures/hog-bytecode/dbc024b193d1a7df9884f009baa61b9a6e3f8d3f20a86dfc8830a47bc742a14c.json b/nodejs/tests/fixtures/hog-bytecode/dbc024b193d1a7df9884f009baa61b9a6e3f8d3f20a86dfc8830a47bc742a14c.json
new file mode 100644
index 000000000000..1a5538ba1a75
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/dbc024b193d1a7df9884f009baa61b9a6e3f8d3f20a86dfc8830a47bc742a14c.json
@@ -0,0 +1 @@
+["_H",1,32,"pixelId",32,"inputs",1,2,2,"empty",1,32,"accessToken",32,"inputs",1,2,2,"empty",1,4,2,40,6,32,"Pixel ID and access token are required",2,"Error",1,49,32,"data",32,"event_name",32,"eventName",32,"inputs",1,2,32,"event_id",32,"eventId",32,"inputs",1,2,32,"event_time",32,"eventTime",32,"inputs",1,2,32,"action_source",32,"actionSource",32,"inputs",1,2,32,"user_data",42,0,32,"custom_data",42,0,42,6,43,1,32,"access_token",32,"accessToken",32,"inputs",1,2,42,2,32,"testEventCode",32,"inputs",1,2,2,"empty",1,5,40,11,36,0,32,"test_event_code",32,"testEventCode",32,"inputs",1,2,46,32,"eventSourceUrl",32,"inputs",1,2,2,"empty",1,5,40,17,36,0,32,"data",45,33,1,45,32,"event_source_url",32,"eventSourceUrl",32,"inputs",1,2,46,52,"parseValueIfArray",1,0,53,32,"string",36,0,2,"typeof",1,11,40,40,36,0,2,"trim",1,36,1,32,"[",2,"startsWith",2,40,25,50,10,36,1,2,"jsonParse",1,38,51,39,14,36,2,32,"type",45,36,0,38,39,2,35,49,35,35,35,36,0,38,53,0,52,"freshClickId",1,0,67,32,"string",36,0,2,"typeof",1,12,40,2,31,38,36,0,32,"^fb[.][0-9]+[.][0-9]+[.][A-Za-z0-9_-]+([.][A-Za-z0-9_-]+)?$",2,"match",2,5,40,2,31,38,32,".",36,0,2,"splitByString",2,33,3,45,2,"toFloat",1,32,"timestamp",32,"event",1,2,2,"toUnixTimestampMilli",1,7,33,-300000,36,1,15,33,7776000000,36,1,14,4,2,40,2,31,38,36,0,38,35,53,0,32,"userData",32,"inputs",1,2,36,3,2,"keys",1,36,3,2,"values",1,33,1,36,5,2,"length",1,31,31,36,7,36,6,16,40,69,36,4,36,6,45,37,8,36,5,36,6,45,37,9,32,"fbc",36,8,11,40,8,36,9,36,2,54,1,39,6,36,9,36,1,54,1,36,10,2,"empty",1,5,40,16,36,0,32,"data",45,33,1,45,32,"user_data",45,36,8,36,10,46,35,36,6,33,1,6,37,6,39,-76,35,35,35,35,35,35,35,32,"customData",32,"inputs",1,2,36,3,2,"keys",1,36,3,2,"values",1,33,1,36,5,2,"length",1,31,31,36,7,36,6,16,40,51,36,4,36,6,45,37,8,36,5,36,6,45,37,9,36,9,2,"empty",1,5,40,20,36,0,32,"data",45,33,1,45,32,"custom_data",45,36,8,36,9,36,1,54,1,46,36,6,33,1,6,37,6,39,-58,35,35,35,35,35,35,35,32,"https://graph.facebook.com/v25.0/",32,"pixelId",32,"inputs",1,2,32,"/events",2,"concat",3,32,"method",32,"POST",32,"headers",32,"Content-Type",32,"application/json",42,1,32,"body",36,0,42,3,2,"fetch",2,33,400,36,3,32,"status",45,14,40,21,32,"Error from graph.facebook.com (status ",36,3,32,"status",45,32,"): ",36,3,32,"body",45,2,"concat",4,2,"Error",1,49,35,35,35,35]