Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix(worker): events inherit the session's utm tags (#581)

Carl-Gerhard Lindesvärd3f58274bfb89
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts
index 028d1b7e4..209e22151 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts
@@ -264,6 +264,111 @@ describe('incomingEvent', () => {
expect(testEventCall!.referrerType).toBe('search');
});
+ test('inherits utm from current session when the event URL has none', async () => {
+ const { deps, createEvent, ingest } = ctx;
+ ingest.mockResolvedValueOnce({
+ kind: 'extend',
+ current: makeSession({
+ utm_source: 'meta',
+ utm_medium: 'paid_socials',
+ utm_campaign: 'mega_pikr',
+ utm_content: '',
+ utm_term: '',
+ }),
+ });
+
+ await incomingEvent(
+ buildJobData({
+ event: {
+ name: 'registration_completed',
+ timestamp: new Date().toISOString(),
+ isTimestampFromThePast: false,
+ properties: { __path: 'https://example.com/signup/done' },
+ },
+ }),
+ deps
+ );
+
+ const event = createdEvents(createEvent).find(
+ (a) => a.name === 'registration_completed'
+ );
+ expect(event!.properties).toMatchObject({
+ __query: {
+ utm_source: 'meta',
+ utm_medium: 'paid_socials',
+ utm_campaign: 'mega_pikr',
+ },
+ });
+ const query = (event!.properties as { __query: object }).__query;
+ expect(Object.keys(query)).toHaveLength(3);
+ });
+
+ test("keeps the event's own utm over the session's", async () => {
+ const { deps, createEvent, ingest } = ctx;
+ ingest.mockResolvedValueOnce({
+ kind: 'extend',
+ current: makeSession({ utm_source: 'meta', utm_campaign: 'first' }),
+ });
+
+ await incomingEvent(
+ buildJobData({
+ event: {
+ name: 'screen_view',
+ timestamp: new Date().toISOString(),
+ isTimestampFromThePast: false,
+ properties: {
+ __path: 'https://example.com/?utm_source=google&utm_medium=cpc',
+ },
+ },
+ }),
+ deps
+ );
+
+ const event = createdEvents(createEvent).find(
+ (a) => a.name === 'screen_view'
+ );
+ expect(event!.properties).toMatchObject({
+ __query: {
+ utm_source: 'google',
+ utm_medium: 'cpc',
+ utm_campaign: 'first',
+ },
+ });
+ });
+
+ test('server events inherit utm from the profile session they ride on', async () => {
+ const { deps, createEvent, getExistingSession } = ctx;
+ getExistingSession.mockResolvedValueOnce(
+ makeSession({
+ id: 'last-session-456',
+ profile_id: 'profile-123',
+ utm_source: 'meta',
+ utm_campaign: 'mega_pikr',
+ })
+ );
+
+ await incomingEvent(
+ buildJobData({
+ event: {
+ name: 'server_event',
+ timestamp: new Date().toISOString(),
+ properties: { plan: 'pro' },
+ profileId: 'profile-123',
+ isTimestampFromThePast: false,
+ },
+ uaInfo: uaInfoServer,
+ deviceId: '',
+ sessionId: '',
+ }),
+ deps
+ );
+
+ expect(createdEvents(createEvent)[0]!.properties).toMatchObject({
+ plan: 'pro',
+ __query: { utm_source: 'meta', utm_campaign: 'mega_pikr' },
+ });
+ });
+
test('handles server events with existing profile session', async () => {
const { deps, createEvent, ingest, getExistingSession, enqueueSessionEnd } =
ctx;
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
index b4f55c9ca..0c67f8c53 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
@@ -35,6 +35,30 @@ const GLOBAL_PROPERTIES = ['__path', '__referrer', '__timestamp', '__revenue'];
/** How far before the event `session_start` is stamped, so it sorts first. */
const SESSION_START_OFFSET_MS = 100;
+const SESSION_UTM_KEYS = [
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_content',
+ 'utm_term',
+] as const;
+
+// UTM tags live on the landing URL only, so without this every later event in
+// the session reports no campaign. The event's own tags win over the session's.
+function inheritSessionUtm(
+ properties: Record<string, unknown>,
+ session: IClickhouseSession
+): Record<string, unknown> {
+ const ownQuery = properties.__query as Record<string, unknown> | undefined;
+ const query = { ...ownQuery };
+ for (const key of SESSION_UTM_KEYS) {
+ if (!query[key] && session[key]) {
+ query[key] = session[key];
+ }
+ }
+ return { ...properties, __query: query };
+}
+
// Strip empty/nullish from B, then deep-merge over A.
const merge = <A, B>(a: Partial<A>, b: Partial<B>): A & B =>
mergeDeepRight(a, reject(anyPass([isEmpty, isNil]))(b)) as A & B;
@@ -335,6 +359,9 @@ async function ingestIncomingEvent(
// describe a row that does not exist.
deviceId: session?.device_id || deviceId,
sessionId: session?.id || sessionId,
+ properties: session
+ ? inheritSessionUtm(baseEvent.properties, session)
+ : baseEvent.properties,
referrer: session?.referrer ?? undefined,
referrerName: session?.referrer_name ?? undefined,
referrerType: session?.referrer_type ?? undefined,
@@ -418,16 +445,19 @@ async function ingestIncomingEvent(
});
}
- // Inherit referrer fields from the canonical session for the actual event.
- // For 'extend' this preserves the original session's referrer across
- // mid-session events; for 'new' / 'boundary' it's the event's own referrer
+ // Inherit referrer and UTM from the canonical session for the actual event.
+ // For 'extend' this preserves the original session's attribution across
+ // mid-session events; for 'new' / 'boundary' it's the event's own
// (which `ingest` just stored on the fresh session).
const finalPayload: IServiceCreateEventPayload = session
- ? merge(baseEvent, {
- referrer: session.current.referrer,
- referrerName: session.current.referrer_name,
- referrerType: session.current.referrer_type,
- } as Partial<IServiceCreateEventPayload>)
+ ? {
+ ...merge(baseEvent, {
+ referrer: session.current.referrer,
+ referrerName: session.current.referrer_name,
+ referrerType: session.current.referrer_type,
+ } as Partial<IServiceCreateEventPayload>),
+ properties: inheritSessionUtm(baseEvent.properties, session.current),
+ }
: baseEvent;
return createEventAndNotify(