From 0e1a449cb6696de7caaaa38c47832fa43459aa86 Mon Sep 17 00:00:00 2001 From: Elijah Duffy Date: Thu, 18 Dec 2025 22:06:23 -0800 Subject: [PATCH] conversion: more robust fbp, fbc with header-based attempt --- src/lib/conversion/server.ts | 12 ++++++++---- src/lib/metapixel/fbc.ts | 12 +++++++++++- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/lib/conversion/server.ts b/src/lib/conversion/server.ts index 4d89fb5..fa28434 100644 --- a/src/lib/conversion/server.ts +++ b/src/lib/conversion/server.ts @@ -8,8 +8,9 @@ import type { } from '$lib/types/conversion.js'; import { StatusCodes } from 'http-status-codes'; +import { getFbpFbcFromCookies } from '../metapixel/fbc.ts'; -const getEventIP = (request: Request, getClientAddress: () => string) => { +export const getRequestIP = (request: Request, getClientAddress: () => string) => { return ( request.headers.get('x-forwarded-for') || request.headers.get('cf-connecting-ip') || @@ -26,18 +27,21 @@ const getEventIP = (request: Request, getClientAddress: () => string) => { export const createConversionRequestHandler: (control: ConversionControl) => RequestHandler = ( control ) => { - const handle: RequestHandler = async ({ request, getClientAddress }) => { + const handle: RequestHandler = async ({ request, getClientAddress, cookies }) => { try { const body = (await request.json()) as ConversionRequestBody; // Build user data with IP and user agent - const ip = getEventIP(request, getClientAddress); + const ip = getRequestIP(request, getClientAddress); const ua = request.headers.get('user-agent'); + const { fbp, fbc } = getFbpFbcFromCookies(cookies); const userData: ConversionUserData = { ...body.user, ip, - ua: ua ?? body.user?.ua ?? undefined + ua: ua ?? body.user?.ua ?? undefined, + fbc: body.user?.fbc ?? fbc, + fbp: body.user?.fbp ?? fbp }; // Build custom data with UTM params if applicable diff --git a/src/lib/metapixel/fbc.ts b/src/lib/metapixel/fbc.ts index 7786c18..9761bf2 100644 --- a/src/lib/metapixel/fbc.ts +++ b/src/lib/metapixel/fbc.ts @@ -1,3 +1,4 @@ +import type { Cookies } from '@sveltejs/kit'; import log from 'loglevel'; export type EnsureFbcOptions = { @@ -79,10 +80,19 @@ export function ensureFbc(options: EnsureFbcOptions = {}) { } /** - * Helper to read both _fbp and _fbc for your CAPI payload. + * Helper to read both _fbp and _fbc for your CAPI payload from browser cookies. */ export function getFbpFbc(): { fbp?: string; fbc?: string } { const fbp = getCookie('_fbp'); const fbc = getCookie('_fbc'); return { fbp, fbc }; } + +/** + * Helper to read both _fbp and _fbc for your CAPI payload from cookies object. + */ +export function getFbpFbcFromCookies(cookies: Cookies): { fbp?: string; fbc?: string } { + const fbp = cookies.get('_fbp') || undefined; + const fbc = cookies.get('_fbc') || undefined; + return { fbp, fbc }; +}