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.

feat(workflows): add utm tags to email links (#110697)

Daniel Marchuk39c5b5153448
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5510073c89ad..493055d53bdf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7547,13 +7547,13 @@ snapshots:
products-workflows-editor-configuration-panel--conditional-branch--light:
hash: v1.k794b7964.3691f905593cd2084ec01847e80b3eeda4c834bd1c34a9d0f37e2d36db9c5f0c.2xvXivEkevaUXKSag8wYob1Hi2ZyfxUcr7VE46qW50w
products-workflows-editor-configuration-panel--email--dark:
- hash: v1.k794b7964.0a80d15de60243a6248418de9b37deb62682560def30870f2cfcd22a0a047026.MXGQk7Iwuqqf5jtKvN0Z5_6ce7ZsVhPczt9YG1-1_aQ
+ hash: v1.k794b7964.8aa43ec8cf9ce9be4b9127e5e9f02585751dcf7a608d721a78139b6d50f7badc.MyDzRS7aT1ol1-R42vCvfzGscOB36K6P73yVH2QlFYU
products-workflows-editor-configuration-panel--email--light:
- hash: v1.k794b7964.c76c115fc4b460ebf446dc8c8acd54688971e26283a01d301685ebeda2d3e2ea.qkOGhLmcF7sP8YNkidOuc8zElAwseH99JkZFujJd6r4
+ hash: v1.k794b7964.b32849126a512eded3c17f06cf3195fba34be7650656fbce62eddfda536c0e23.H6EMRSeFlrHqU3mdJSV__LWPiX1U3V99mmtcop_VDp0
products-workflows-editor-configuration-panel--email-in-side-panel--dark:
- hash: v1.k794b7964.7cc58abcea8f6b3d00f872551245a673d5f9cf2a8d54a9d2471724eb03a44228.5bgFLSmYUiDXVqeW4IHrAc6CZVVkePz7DqPI7Ifije4
+ hash: v1.k794b7964.11641a90642d56a19bcb4c246b090bee8afea1cbe9e8de036d99dbe0317c66b3.XvJ_Ngs1JOs6ANfMLuuunRyPQhizz_q_xQMaIO7R62I
products-workflows-editor-configuration-panel--email-in-side-panel--light:
- hash: v1.k794b7964.9e86cca822a41ea7e1c64e06b6864854ab6b5b1dbb294c9b0f4c31fcbaa18219.mIezlbVnd2sl6GYR87DTOpzdGxEzrcEyp1vIhYqzBYI
+ hash: v1.k794b7964.9b09c56e592e9ffc28a819d33e623f1991a51a17968df8b9496e49e01c3fa823.5ipJ50svyohjEDKIEwZ5h3fHKIwfp9esmAIbrWORhMQ
products-workflows-editor-configuration-panel--logs--dark:
hash: v1.k794b7964.beabe0c2c69154a7e7b8e5709226f710bbb707c7a2a96ea3b908e7b5348ad177.l8BzDM-8b8Z6jYzADnoiRggNuU02m3lgVa6vtNm2VOw
products-workflows-editor-configuration-panel--logs--light:
@@ -7690,6 +7690,10 @@ snapshots:
hash: v1.k794b7964.da6c2d35d62b6b43e01e4b6f7ecc32a981bdc56f110b933a19205ac2d0b5d567.epPMTVeLRSLHG64PRCenl8X9DieogcisrFmsTpmqSN0
products-workflows-steps-trigger-volume--over-the-ai-task-limit--light:
hash: v1.k794b7964.8c8a035a4c109d2ba4954e9622ffa4f34d5192a300ce82e7f2ffecc02d33dc5e.kSIxebraTtjma2-YSM6dC5HpBl4guWxa84_80ajPpcU
+ products-workflows-steps-utm-tag-fields--custom-values--dark:
+ hash: v1.k794b7964.dbc633dbeb5178b3b8e7c987eee3a18c5f06c19913199a5b95093d5887753cd1.lICheCYev7V0-e7t4kRL3YlJyYPKFqc2FR1gLVKVO-8
+ products-workflows-steps-utm-tag-fields--custom-values--light:
+ hash: v1.k794b7964.820ad51684baa61d4a1fdd9e161b86d6dd47262fe0fa677caa42a90f264e5f1f.k4Q7hBIbnDrevkKRCjJOqfGIU5bcBZoxhVZcC3b2zCY
products-workflows-template-card--ai--dark:
hash: v1.k794b7964.5ca1cd71851625754d87c675688f56c0feb039ade940912f8df2ddd171d89d83.5SQmAn1fsl5RQ572BttZHT0wNAtJeZRNP0OqajxrUMc
products-workflows-template-card--ai--light:
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.ts
index 083201c94e96..6f8c8b81a2e4 100644
--- a/nodejs/src/cdp/schema/hogflow.ts
+++ b/nodejs/src/cdp/schema/hogflow.ts
@@ -234,6 +234,17 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
// When false, no open pixel is injected, links are not rewritten, and the send uses the
// untracked SES configuration set. Absent/true means tracked (existing behavior).
tracking_enabled: z.boolean().optional(),
+ // When true, links get utm_source, utm_medium and utm_campaign tags they don't already carry.
+ utm_tags_enabled: z.boolean().optional(),
+ // Liquid templates that replace the default tag values. An empty value keeps the default.
+ utm_params: z
+ .object({
+ utm_source: z.string().optional(),
+ utm_medium: z.string().optional(),
+ utm_campaign: z.string().optional(),
+ utm_content: z.string().optional(),
+ })
+ .optional(),
template_uuid: z.string().optional(), // May be used later to specify a specific template version
template_id: z.literal('template-email'),
inputs: z.record(z.string(), CyclotronInputSchema),
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
index 71d81ef05133..eaf1cd65b207 100644
--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts
@@ -346,7 +346,7 @@ export class HogFunctionHandler implements ActionHandler {
): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction> & { skipped?: boolean }> {
const hogFunction = await instrumentFn(
{ key: 'hogFlow.action.hogFunction.buildHogFunction', sendException: false },
- () => this.hogFlowFunctionsService.buildHogFunction(invocation.hogFlow, action.config)
+ () => this.hogFlowFunctionsService.buildHogFunction(invocation.hogFlow, action.config, action.name)
)
const hogFunctionInvocation = await instrumentFn(
{ key: 'hogFlow.action.hogFunction.buildInvocation', sendException: false },
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
index f86e71bea706..407c2373f9fe 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts
@@ -21,7 +21,11 @@ export class HogFlowFunctionsService {
private hogFunctionExecutor: HogExecutorAsyncService
) {}
- async buildHogFunction(hogFlow: HogFlow, configuration: Action['config']): Promise<HogFunctionType> {
+ async buildHogFunction(
+ hogFlow: HogFlow,
+ configuration: Action['config'],
+ actionName?: string
+ ): Promise<HogFunctionType> {
const template = await this.hogFunctionTemplateManager.getHogFunctionTemplate(configuration.template_id)
if (!template) {
@@ -49,6 +53,8 @@ export class HogFlowFunctionsService {
// send choke point, where only the synthetic hog function is in scope.
metadata: {
...config,
+ hog_flow_name: hogFlow.name,
+ hog_flow_action_name: actionName ?? null,
email_sending_rate_limit: hogFlow.email_sending_rate_limit ?? null,
email_sending_paused_at: hogFlow.email_sending_paused_at ?? null,
email_sending_paused_reason: hogFlow.email_sending_paused_reason ?? null,
diff --git a/nodejs/src/cdp/services/messaging/email.service.test.ts b/nodejs/src/cdp/services/messaging/email.service.test.ts
index 92ff4898c393..a50885b752b7 100644
--- a/nodejs/src/cdp/services/messaging/email.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.test.ts
@@ -8,6 +8,7 @@ import {
CyclotronInvocationQueueParametersEmailType,
} from '~/cdp/schema/cyclotron'
import { CyclotronJobInvocationHogFunction } from '~/cdp/types'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
@@ -23,6 +24,7 @@ import { EmailSuppressionService, emailSuppressionConfigFromEnv } from './email-
import { EmailService, parseAddressList, sanitizeEmailSubject, teamEmailCapBuckets } from './email.service'
import { MailDevAPI } from './helpers/maildev'
import { EmailTrackingCodeSigner } from './helpers/tracking-code'
+import { MessageAssetsService } from './message-assets.service'
class ThrottlingException extends Error {
constructor(message: string) {
@@ -1485,6 +1487,52 @@ describe('EmailService', () => {
expect(headerNames).toContain('X-PostHog-Tracking-Code')
})
+ it.each([
+ {
+ case: 'the workflow and step names',
+ utmParams: undefined,
+ query: 'utm_source=posthog&amp;utm_medium=email&amp;utm_campaign=Spring%20sale&amp;utm_content=Welcome',
+ },
+ {
+ case: 'rendered custom values',
+ utmParams: { utm_source: 'newsletter', utm_campaign: '{{ "pro" | upcase }}' },
+ query: 'utm_source=newsletter&amp;utm_medium=email&amp;utm_campaign=PRO&amp;utm_content=Welcome',
+ },
+ {
+ case: 'a rendered value with characters HTML escapes',
+ utmParams: { utm_campaign: '{{ "Starter & Premium" }}' },
+ query: 'utm_source=posthog&amp;utm_medium=email&amp;utm_campaign=Starter%20%26%20Premium&amp;utm_content=Welcome',
+ },
+ {
+ case: 'the default for a value with a Liquid error',
+ utmParams: { utm_campaign: '{{ person.properties.plan' },
+ query: 'utm_source=posthog&amp;utm_medium=email&amp;utm_campaign=Spring%20sale&amp;utm_content=Welcome',
+ },
+ ])('tags the links with $case when the step turns UTM tags on', async ({ utmParams, query }) => {
+ invocation.hogFunction.metadata = {
+ tracking_enabled: false,
+ utm_tags_enabled: true,
+ utm_params: utmParams,
+ hog_flow_name: 'Spring sale',
+ hog_flow_action_name: 'Welcome',
+ }
+ const messageAssets = new MessageAssetsService({
+ produce: jest.fn().mockResolvedValue(undefined),
+ } as unknown as IngestionOutputs<'message_assets'>)
+ const buildRowForEmail = jest.spyOn(messageAssets, 'buildRowForEmail').mockReturnValue(null)
+ service['messageAssetsService'] = messageAssets
+ const result = await service.executeSendEmail(invocation)
+ expect(result.error).toBeUndefined()
+ const sentCommand = sendEmailSpy.mock.calls[0][0] as { input: any }
+ const taggedHtml = `<body>Hi! <a href="https://example.com?${query}">Click me</a></body>`
+ expect(sentCommand.input.Content.Simple.Body.Html.Data).toEqual(taggedHtml)
+ // The stored copy behind "View email" shows the links the recipient got.
+ expect(buildRowForEmail).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ html: taggedHtml })
+ )
+ })
+
it('falls back to the tracked configuration set when no untracked set is configured, still untracked HTML', async () => {
const result = await service.executeSendEmail(invocation)
expect(result.error).toBeUndefined()
diff --git a/nodejs/src/cdp/services/messaging/email.service.ts b/nodejs/src/cdp/services/messaging/email.service.ts
index 1348f74e4917..8c906c3f8657 100644
--- a/nodejs/src/cdp/services/messaging/email.service.ts
+++ b/nodejs/src/cdp/services/messaging/email.service.ts
@@ -30,6 +30,7 @@ import {
import { mailDevTransport, mailDevWebUrl } from './helpers/maildev'
import { maybeAddPreheaderToEmail } from './helpers/preheader'
import { EmailTrackingCodeSigner, TRACKING_CODE_HEADER_NAME } from './helpers/tracking-code'
+import { addUtmTagsToEmail, renderUtmOverrides, resolveUtmTags } from './helpers/utm'
import { MessageAssetsService } from './message-assets.service'
import { RecipientTokensService } from './recipient-tokens.service'
@@ -345,7 +346,7 @@ export class EmailService {
private integrationManager: IntegrationManagerService,
private teamWorkflowsConfigService: TeamWorkflowsConfigService,
encryptionSaltKeys: string,
- siteUrl: string,
+ private siteUrl: string,
private trackingCodeSigner: EmailTrackingCodeSigner,
private emailSuppressionService: EmailSuppressionService,
private recipientsManager: RecipientsManagerService,
@@ -570,12 +571,39 @@ export class EmailService {
return result
}
+ // Tagged before click tracking wraps the links, so the tags land on the destination URL.
+ const metadata = invocation.hogFunction.metadata
+ const sendParams =
+ metadata?.utm_tags_enabled === true && params.html
+ ? {
+ ...params,
+ html: addUtmTagsToEmail(
+ params.html,
+ resolveUtmTags(
+ {
+ utm_source: 'posthog',
+ utm_medium: 'email',
+ utm_campaign: metadata.hog_flow_name ?? invocation.hogFunction.name,
+ utm_content: metadata.hog_flow_action_name ?? '',
+ },
+ renderUtmOverrides(metadata.utm_params, invocation.state.globals, (key, message) =>
+ addLog(
+ 'warn',
+ `Used the default ${key} because its value has an error: ${message}`
+ )
+ )
+ ),
+ this.siteUrl
+ ),
+ }
+ : params
+
switch (integration.config.provider ?? 'ses') {
case 'maildev':
- await this.sendEmailWithMaildev(result, params, from, trackingEnabled, isTest)
+ await this.sendEmailWithMaildev(result, sendParams, from, trackingEnabled, isTest)
break
case 'ses':
- await this.sendEmailWithSES(result, params, from, trackingEnabled, isTest)
+ await this.sendEmailWithSES(result, sendParams, from, trackingEnabled, isTest)
break
case 'unsupported':
@@ -587,7 +615,7 @@ export class EmailService {
// "View email" chip, so suppressing it for skipped captures keeps the chip
// from 404-ing on click.
if (!isTest && this.messageAssetsService) {
- assetRow = this.messageAssetsService.buildRowForEmail(invocation, params)
+ assetRow = this.messageAssetsService.buildRowForEmail(invocation, sendParams)
}
const viewEmailToken = assetRow ? ` [Email:${invocation.id}:${invocation.state.actionId ?? ''}]` : ''
addLog('info', `Email sent to ${params.to.email} from ${from.name} <${from.email}>${viewEmailToken}`)
diff --git a/nodejs/src/cdp/services/messaging/helpers/utm.test.ts b/nodejs/src/cdp/services/messaging/helpers/utm.test.ts
new file mode 100644
index 000000000000..c54085f50584
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/helpers/utm.test.ts
@@ -0,0 +1,101 @@
+import { addUtmTagsToEmail, resolveUtmTags } from './utm'
+
+const TAGS = { utm_source: 'posthog', utm_medium: 'email', utm_campaign: 'Spring sale', utm_content: '' }
+const SITE_URL = 'https://us.posthog.com'
+const QUERY = 'utm_source=posthog&amp;utm_medium=email&amp;utm_campaign=Spring%20sale'
+
+describe('addUtmTagsToEmail', () => {
+ it.each([
+ {
+ case: 'a plain link',
+ html: '<a href="https://example.com/pricing">x</a>',
+ expected: `<a href="https://example.com/pricing?${QUERY}">x</a>`,
+ },
+ {
+ case: 'a link with a query and a fragment',
+ html: '<a href="https://example.com/p?a=1&amp;b=2#plans">x</a>',
+ expected: `<a href="https://example.com/p?a=1&amp;b=2&amp;${QUERY}#plans">x</a>`,
+ },
+ {
+ case: 'a link that already sets its campaign',
+ html: "<a class='btn' href='https://example.com/?utm_campaign=launch'>x</a>",
+ expected:
+ "<a class='btn' href='https://example.com/?utm_campaign=launch&amp;utm_source=posthog&amp;utm_medium=email'>x</a>",
+ },
+ {
+ case: 'a link that already has every tag',
+ html: '<a href="https://example.com/?utm_source=a&utm_medium=b&utm_campaign=c">x</a>',
+ expected: '<a href="https://example.com/?utm_source=a&utm_medium=b&utm_campaign=c">x</a>',
+ },
+ {
+ case: 'the unsubscribe link on the PostHog host',
+ html: '<a href="https://us.posthog.com/messaging-preferences/abc/">Unsubscribe</a>',
+ expected: '<a href="https://us.posthog.com/messaging-preferences/abc/">Unsubscribe</a>',
+ },
+ {
+ case: 'mailto, relative and anchor links',
+ html: '<a href="mailto:[email protected]">m</a><a href="/docs">r</a><a href="#top">a</a>',
+ expected: '<a href="mailto:[email protected]">m</a><a href="/docs">r</a><a href="#top">a</a>',
+ },
+ {
+ case: 'a link marked data-ph-no-utm',
+ html: '<a data-ph-no-utm href="https://example.com/pricing">x</a>',
+ expected: '<a data-ph-no-utm href="https://example.com/pricing">x</a>',
+ },
+ {
+ case: 'a link with data-href before href',
+ html: '<a data-href="x" href="https://example.com/pricing">x</a>',
+ expected: `<a data-href="x" href="https://example.com/pricing?${QUERY}">x</a>`,
+ },
+ {
+ case: 'a link whose title mentions data-ph-no-utm',
+ html: '<a title="add data-ph-no-utm to skip" href="https://example.com/pricing">x</a>',
+ expected: `<a title="add data-ph-no-utm to skip" href="https://example.com/pricing?${QUERY}">x</a>`,
+ },
+ {
+ case: 'an <abbr> next to a link',
+ html: '<abbr title="x">PH</abbr><a href="https://example.com/pricing">x</a>',
+ expected: `<abbr title="x">PH</abbr><a href="https://example.com/pricing?${QUERY}">x</a>`,
+ },
+ {
+ case: 'a quoted > inside the tag',
+ html: '<a title="a > b" href="https://example.com/pricing">x</a>',
+ expected: `<a title="a > b" href="https://example.com/pricing?${QUERY}">x</a>`,
+ },
+ {
+ case: 'an unclosed tag after a link',
+ html: '<a href="https://example.com/pricing">x</a> <a <a <a',
+ expected: `<a href="https://example.com/pricing?${QUERY}">x</a> <a <a <a`,
+ },
+ {
+ case: 'an unrendered template tag',
+ html: '<a href="https://example.com/{{ person.id }}">x</a>',
+ expected: '<a href="https://example.com/{{ person.id }}">x</a>',
+ },
+ ])('tags $case', ({ html, expected }) => {
+ expect(addUtmTagsToEmail(html, TAGS, SITE_URL)).toEqual(expected)
+ })
+
+ it.each([
+ {
+ case: 'no custom values',
+ rendered: undefined,
+ expected: { utm_campaign: 'Spring sale', utm_content: 'Send email' },
+ },
+ {
+ case: 'a custom campaign and content',
+ rendered: { utm_campaign: 'pro-plan', utm_content: ' hero ' },
+ expected: { utm_campaign: 'pro-plan', utm_content: 'hero' },
+ },
+ {
+ case: 'a value that rendered empty',
+ rendered: { utm_campaign: ' ' },
+ expected: { utm_campaign: 'Spring sale' },
+ },
+ ])('resolves the tags from $case', ({ rendered, expected }) => {
+ expect(resolveUtmTags({ ...TAGS, utm_content: 'Send email' }, rendered)).toMatchObject({
+ utm_source: 'posthog',
+ ...expected,
+ })
+ })
+})
diff --git a/nodejs/src/cdp/services/messaging/helpers/utm.ts b/nodejs/src/cdp/services/messaging/helpers/utm.ts
new file mode 100644
index 000000000000..ac341e164bcd
--- /dev/null
+++ b/nodejs/src/cdp/services/messaging/helpers/utm.ts
@@ -0,0 +1,167 @@
+import { HogFunctionInvocationGlobalsWithInputs } from '~/cdp/types'
+import { LiquidRenderer } from '~/cdp/utils/liquid'
+
+import { decodeHtmlEntitiesInHref } from '../email-tracking.service'
+
+export type UtmTags = {
+ utm_source: string
+ utm_medium: string
+ utm_campaign: string
+ utm_content: string
+}
+
+const UTM_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content'] as const
+
+// One attribute per match, so `href` and `data-ph-no-utm` count only as attribute names, never as text
+// inside another attribute's value or as part of a longer name like `data-href`.
+const ATTRIBUTE_REGEX = /\s([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g
+
+/**
+ * Renders each custom value as Liquid with the recipient's data. A value that fails to render is
+ * reported and left out, so one bad template keeps its default instead of failing the send.
+ */
+export const renderUtmOverrides = (
+ raw: unknown,
+ globals: HogFunctionInvocationGlobalsWithInputs,
+ onError: (key: string, message: string) => void
+): Record<string, string> => {
+ const rendered: Record<string, string> = {}
+ if (!raw || typeof raw !== 'object') {
+ return rendered
+ }
+ for (const key of UTM_KEYS) {
+ const value = (raw as Record<string, unknown>)[key]
+ if (typeof value !== 'string' || !value.trim()) {
+ continue
+ }
+ try {
+ // Liquid escapes HTML in what it renders, and a URL needs the plain text.
+ rendered[key] = decodeHtmlEntitiesInHref(LiquidRenderer.renderWithHogFunctionGlobals(value, globals))
+ } catch (error) {
+ onError(key, error instanceof Error ? error.message : String(error))
+ }
+ }
+ return rendered
+}
+
+/** The defaults, with each custom value that rendered to something non-empty in place of its default. */
+export const resolveUtmTags = (defaults: UtmTags, rendered: unknown): UtmTags => {
+ const custom = rendered && typeof rendered === 'object' ? (rendered as Record<string, unknown>) : {}
+ const tags = { ...defaults }
+ for (const key of UTM_KEYS) {
+ const value = custom[key]
+ if (typeof value === 'string' && value.trim()) {
+ tags[key] = value.trim()
+ }
+ }
+ return tags
+}
+
+const hostOf = (url: string): string | null => {
+ try {
+ return new URL(url).host
+ } catch {
+ return null
+ }
+}
+
+/**
+ * Appends each UTM tag the link does not already carry. Returns null when the link stays as is:
+ * not an absolute http(s) URL, a link to PostHog itself (unsubscribe and preference pages), an
+ * unrendered template tag, or a link that already has every tag.
+ */
+export const addUtmTagsToUrl = (url: string, tags: UtmTags, siteHost: string | null): string | null => {
+ if (url.includes('{{') || url.includes('{%')) {
+ return null
+ }
+ let parsed: URL
+ try {
+ parsed = new URL(url)
+ } catch {
+ return null
+ }
+ if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || parsed.host === siteHost) {
+ return null
+ }
+ const missing = Object.entries(tags).filter(([key, value]) => value && !parsed.searchParams.has(key))
+ if (missing.length === 0) {
+ return null
+ }
+ // Append to the original string rather than serializing the URL, so the rest of the link stays byte for byte.
+ const hashIndex = url.indexOf('#')
+ const base = hashIndex === -1 ? url : url.slice(0, hashIndex)
+ const hash = hashIndex === -1 ? '' : url.slice(hashIndex)
+ const separator = !base.includes('?') ? '?' : base.endsWith('?') || base.endsWith('&') ? '' : '&'
+ const query = missing.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
+ return `${base}${separator}${query}${hash}`
+}
+
+/** Index of the `>` that closes the tag opened before `from`, skipping quoted values, or -1 if it never closes. */
+const findTagEnd = (html: string, from: number): number => {
+ let quote: string | null = null
+ for (let i = from; i < html.length; i++) {
+ const char = html[i]
+ if (quote) {
+ if (char === quote) {
+ quote = null
+ }
+ } else if (char === '"' || char === "'") {
+ quote = char
+ } else if (char === '>') {
+ return i
+ }
+ }
+ return -1
+}
+
+const tagAnchor = (anchor: string, tags: UtmTags, siteHost: string | null): string => {
+ const attributes = [...anchor.matchAll(ATTRIBUTE_REGEX)]
+ if (attributes.some((attribute) => attribute[1].toLowerCase() === 'data-ph-no-utm')) {
+ return anchor
+ }
+ const href = attributes.find((attribute) => attribute[1].toLowerCase() === 'href')
+ const value = href ? (href[2] ?? href[3]) : undefined
+ if (!href || value === undefined) {
+ return anchor
+ }
+ const tagged = addUtmTagsToUrl(decodeHtmlEntitiesInHref(value), tags, siteHost)
+ if (tagged === null) {
+ return anchor
+ }
+ const quote = href[2] !== undefined ? '"' : "'"
+ const encoded = tagged
+ .replace(/&/g, '&amp;')
+ .replace(quote === '"' ? /"/g : /'/g, quote === '"' ? '&quot;' : '&#39;')
+ const start = href.index! + href[0].indexOf('=')
+ return anchor.slice(0, start) + `=${quote}${encoded}${quote}` + anchor.slice(href.index! + href[0].length)
+}
+
+// One forward pass rather than a regex, so a body full of unclosed `<a` tags costs linear time instead
+// of rescanning the rest of the email for each one and stalling the worker.
+export const addUtmTagsToEmail = (html: string, tags: UtmTags, siteUrl: string): string => {
+ const siteHost = hostOf(siteUrl)
+ const lower = html.toLowerCase()
+ let output = ''
+ let cursor = 0
+ while (cursor < html.length) {
+ const start = lower.indexOf('<a', cursor)
+ if (start === -1) {
+ break
+ }
+ const after = lower[start + 2]
+ if (after !== undefined && !/[\s>/]/.test(after)) {
+ // `<abbr>`, `<area>` and other tags that only start with "a".
+ output += html.slice(cursor, start + 2)
+ cursor = start + 2
+ continue
+ }
+ const end = findTagEnd(html, start + 2)
+ if (end === -1) {
+ // The tag never closes, so it is not a link, and the rest of the email is left as is.
+ break
+ }
+ output += html.slice(cursor, start) + tagAnchor(html.slice(start, end + 1), tags, siteHost)
+ cursor = end + 1
+ }
+ return output + html.slice(cursor)
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts b/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts
index e5322bc26185..154ec7237f22 100644
--- a/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastTestSendLogic.ts
@@ -9,12 +9,18 @@ import { userLogic } from 'scenes/userLogic'
import { UserType } from '~/types'
+import type { HogFlowApi } from '../generated/api.schemas'
import { HogflowTestResult } from '../Workflows/hogflows/steps/types'
import { createExampleEvent } from '../Workflows/hogflows/testEventFactory'
import type { HogFlow, HogFlowAction, HogFlowEdge } from '../Workflows/hogflows/types'
import { EXIT_NODE_ID, NEW_WORKFLOW, TRIGGER_NODE_ID } from '../Workflows/workflowLogic'
import { BroadcastPreviewPerson, broadcastPreviewLogic } from './broadcastPreviewLogic'
-import { BroadcastEmailValue, BroadcastWizardLogicProps, broadcastWizardLogic } from './broadcastWizardLogic'
+import {
+ BroadcastEmailSettings,
+ BroadcastEmailValue,
+ BroadcastWizardLogicProps,
+ broadcastWizardLogic,
+} from './broadcastWizardLogic'
// Fixed id for the single email action in the synthetic test flow. The edges below reference it,
// and it goes over as `current_action_id` so the worker runs just this node.
@@ -38,7 +44,9 @@ export function findTestSendSkipReason(result: HogflowTestResult | null): string
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastTestSendLogicValues {
previewPerson: BroadcastPreviewPerson | null // broadcastPreviewLogic
+ broadcast: HogFlowApi | null // broadcastWizardLogic
email: BroadcastEmailValue // broadcastWizardLogic
+ emailSettings: BroadcastEmailSettings // broadcastWizardLogic
name: string // broadcastWizardLogic
currentTeamId: number | null // teamLogic
user: UserType | null // userLogic
@@ -125,7 +133,7 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
connect((props: BroadcastWizardLogicProps) => ({
values: [
broadcastWizardLogic(props),
- ['email', 'name'],
+ ['broadcast', 'email', 'emailSettings', 'name'],
broadcastPreviewLogic(props),
['previewPerson'],
teamLogic,
@@ -152,7 +160,8 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
{
clearTestSendResult: () => null,
sendTestEmail: async (): Promise<HogflowTestResult> => {
- const { email, name, previewPerson, recipientEmail, currentTeamId } = values
+ const { broadcast, email, emailSettings, name, previewPerson, recipientEmail, currentTeamId } =
+ values
const emailAction: HogFlowAction = {
id: TEST_EMAIL_ACTION_ID,
@@ -163,6 +172,15 @@ export const broadcastTestSendLogic = kea<broadcastTestSendLogicType>([
updated_at: 0,
config: {
template_id: 'template-email',
+ // The test shows the links as the audience gets them.
+ utm_tags_enabled: emailSettings.utmTagsEnabled,
+ // The default content tag is the email step's name, so the test uses the real step's name.
+ utm_params: {
+ utm_content:
+ broadcast?.actions?.find((action) => action.type === 'function_email')?.name ??
+ 'Send email',
+ ...emailSettings.utmParams,
+ },
inputs: {
email: {
value: {
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 8df604b3ecc5..8a5674a58e97 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -47,6 +47,7 @@ import {
parseRRuleToState,
stateToRRule,
} from '../Workflows/hogflows/steps/components/rrule-helpers'
+import type { UtmTagValues } from '../Workflows/hogflows/steps/components/UtmTagFields'
import { ResourceSaveQueue } from '../Workflows/resourceSaveQueue'
import { confirmArchiveBroadcast, confirmDeleteBroadcast, restoreBroadcast } from './broadcastLifecycle'
import {
@@ -119,12 +120,16 @@ export interface BroadcastEmailSettings {
messageCategoryId: string | null
messageCategoryType: string | null
trackingEnabled: boolean
+ utmTagsEnabled: boolean
+ utmParams: UtmTagValues
}
export const DEFAULT_BROADCAST_EMAIL_SETTINGS: BroadcastEmailSettings = {
messageCategoryId: null,
messageCategoryType: null,
trackingEnabled: true,
+ utmTagsEnabled: false,
+ utmParams: {},
}
function readEmailSettings(broadcast: HogFlowApi): BroadcastEmailSettings | null {
@@ -136,6 +141,8 @@ function readEmailSettings(broadcast: HogFlowApi): BroadcastEmailSettings | null
messageCategoryId: config.message_category_id ?? null,
messageCategoryType: config.message_category_type ?? null,
trackingEnabled: config.tracking_enabled !== false,
+ utmTagsEnabled: config.utm_tags_enabled === true,
+ utmParams: config.utm_params ?? {},
}
}
@@ -147,6 +154,8 @@ function emailSettingsConfig(settings: BroadcastEmailSettings | undefined): Reco
message_category_id: settings.messageCategoryId ?? undefined,
message_category_type: settings.messageCategoryType ?? undefined,
tracking_enabled: settings.trackingEnabled,
+ utm_tags_enabled: settings.utmTagsEnabled,
+ utm_params: settings.utmParams,
}
}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
index 73307df309fb..f5c438fd5475 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
@@ -119,7 +119,7 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
it.each([
['a new broadcast', null],
['a workflow shaped like a broadcast', { origin_product: null, actions: [trigger(), email(), exit], edges }],
- ])('saves the message category and tracking onto the email step of %s', (_, existing) => {
+ ])('saves the message category, tracking and UTM tags onto the email step of %s', (_, existing) => {
const payload = buildBroadcastPayload({
name: 'Newsletter',
audienceProperties: [],
@@ -127,7 +127,13 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
conversion: DEFAULT_BROADCAST_CONVERSION,
email: DEFAULT_BROADCAST_EMAIL,
emailRateLimit: null,
- emailSettings: { messageCategoryId: 'cat-1', messageCategoryType: 'marketing', trackingEnabled: false },
+ emailSettings: {
+ messageCategoryId: 'cat-1',
+ messageCategoryType: 'marketing',
+ trackingEnabled: false,
+ utmTagsEnabled: true,
+ utmParams: { utm_campaign: '{{ person.properties.plan }}' },
+ },
broadcast: existing as unknown as HogFlowApi | null,
})
@@ -136,6 +142,8 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
message_category_id: 'cat-1',
message_category_type: 'marketing',
tracking_enabled: false,
+ utm_tags_enabled: true,
+ utm_params: { utm_campaign: '{{ person.properties.plan }}' },
})
})
})
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
index 1054e754f017..3d148159a8c2 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastContentStep.tsx
@@ -11,10 +11,12 @@ import { IntegrationType } from '~/types'
import { EmailSetupModal } from '../../Channels/EmailSetup/EmailSetupModal'
import { buildSampleGlobals } from '../../Workflows/hogflows/steps/components/HogFlowFunctionConfiguration'
+import { UtmTagFields } from '../../Workflows/hogflows/steps/components/UtmTagFields'
import { BroadcastEmailValue, DEFAULT_BROADCAST_EMAIL, broadcastWizardLogic } from '../broadcastWizardLogic'
export function BroadcastContentStep(): JSX.Element {
- const { email, stepValidationErrors, selectedSender, emailSettings } = useValues(broadcastWizardLogic)
+ const { broadcast, email, name, stepValidationErrors, selectedSender, emailSettings } =
+ useValues(broadcastWizardLogic)
const { setEmail, setEmailSettings } = useActions(broadcastWizardLogic)
const { integrations, integrationsLoading } = useValues(integrationsLogic)
const { loadIntegrations } = useActions(integrationsLogic)
@@ -118,6 +120,23 @@ export function BroadcastContentStep(): JSX.Element {
Links stay as written and no tracking pixel is added, so this broadcast shows no opens or clicks.
</span>
)}
+ <LemonSwitch
+ label="Add UTM tags to links"
+ checked={emailSettings.utmTagsEnabled}
+ onChange={(utmTagsEnabled) => setEmailSettings({ utmTagsEnabled })}
+ bordered
+ data-attr="broadcast-utm-tags-toggle"
+ />
+ {emailSettings.utmTagsEnabled && (
+ <UtmTagFields
+ value={emailSettings.utmParams}
+ onChange={(utmParams) => setEmailSettings({ utmParams })}
+ campaignDefault={name || 'Broadcast name'}
+ contentDefault={
+ broadcast?.actions?.find((action) => action.type === 'function_email')?.name ?? 'Send email'
+ }
+ />
+ )}
</div>
)
}
diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
index 88bd90795e41..6dc9e78ad638 100644
--- a/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastReviewStep.tsx
@@ -148,6 +148,7 @@ export function BroadcastReviewStep(): JSX.Element {
{!emailSettings.trackingEnabled && (
<div className="text-xs text-secondary">Open and click tracking is off.</div>
)}
+ {emailSettings.utmTagsEnabled && <div className="text-xs text-secondary">Links get UTM tags.</div>}
<BroadcastEmailPreview />
</ReviewRow>
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index 2f0b20877b29..f869f1b6e805 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -732,6 +732,15 @@ export interface hogFlowEditorLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string
@@ -1588,6 +1597,15 @@ export interface hogFlowEditorLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
index 0f4944dcb2f5..9e0ccede72f2 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
@@ -27,6 +27,7 @@ import { CategorySelect } from 'products/workflows/frontend/OptOuts/CategorySele
import { workflowLogic } from '../../workflowLogic'
import { HogFlowPropertyFilters } from '../filters/HogFlowFilters'
import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { UtmTagFields } from '../steps/components/UtmTagFields'
import { useHogFlowStep } from '../steps/HogFlowSteps'
import { isEmailAction, isOptOutEligibleAction } from '../steps/types'
import type { HogFlowAction } from '../types'
@@ -156,6 +157,36 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
}}
/>
</div>
+ <div className="flex gap-2 justify-between items-center px-2 py-1">
+ <LemonLabel info="Adds UTM tags to each link, so visits from this email show up as their own campaign in web analytics. Tags already on a link are kept. Links to PostHog, such as the unsubscribe link, are not changed. Add data-ph-no-utm to a link to leave it as is.">
+ Add UTM tags to links
+ </LemonLabel>
+ <LemonSwitch
+ checked={action.config.utm_tags_enabled === true}
+ onChange={(checked) => {
+ setWorkflowAction(action.id, {
+ ...action,
+ config: { ...action.config, utm_tags_enabled: checked },
+ })
+ }}
+ data-attr="workflow-email-utm-tags-toggle"
+ />
+ </div>
+ {action.config.utm_tags_enabled === true && (
+ <div className="px-2 pb-2">
+ <UtmTagFields
+ value={action.config.utm_params ?? {}}
+ onChange={(utmParams) => {
+ setWorkflowAction(action.id, {
+ ...action,
+ config: { ...action.config, utm_params: utmParams },
+ })
+ }}
+ campaignDefault={workflow.name || 'Workflow name'}
+ contentDefault={action.name}
+ />
+ </div>
+ )}
</>
)}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.stories.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.stories.tsx
new file mode 100644
index 000000000000..74deab4b6872
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.stories.tsx
@@ -0,0 +1,22 @@
+import { Meta, StoryFn } from '@storybook/react'
+import { useState } from 'react'
+
+import { UtmTagFields, UtmTagValues } from './UtmTagFields'
+
+const meta: Meta<typeof UtmTagFields> = {
+ title: 'Products/Workflows/Steps/UTM tag fields',
+ component: UtmTagFields,
+}
+export default meta
+
+const Template: StoryFn<{ initial: UtmTagValues }> = ({ initial }) => {
+ const [value, setValue] = useState<UtmTagValues>(initial)
+ return (
+ <div className="w-120">
+ <UtmTagFields value={value} onChange={setValue} campaignDefault="Spring sale" contentDefault="Send email" />
+ </div>
+ )
+}
+
+export const CustomValues = Template.bind({})
+CustomValues.args = { initial: { utm_source: 'newsletter', utm_campaign: '{{ person.properties.plan }}' } }
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx
new file mode 100644
index 000000000000..4cb08c5060e2
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/UtmTagFields.tsx
@@ -0,0 +1,61 @@
+import { LemonInput } from '@posthog/lemon-ui'
+
+export type UtmTagKey = 'utm_source' | 'utm_medium' | 'utm_campaign' | 'utm_content'
+export type UtmTagValues = Partial<Record<UtmTagKey, string>>
+
+const UTM_TAG_KEYS: UtmTagKey[] = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content']
+
+export interface UtmTagFieldsProps {
+ value: UtmTagValues
+ onChange: (value: UtmTagValues) => void
+ /** What utm_campaign and utm_content get when left empty. */
+ campaignDefault: string
+ contentDefault: string
+}
+
+export function UtmTagFields({ value, onChange, campaignDefault, contentDefault }: UtmTagFieldsProps): JSX.Element {
+ const defaults: Record<UtmTagKey, string> = {
+ utm_source: 'posthog',
+ utm_medium: 'email',
+ utm_campaign: campaignDefault,
+ utm_content: contentDefault,
+ }
+ const values = UTM_TAG_KEYS.map((key) => [key, (value[key] || defaults[key]).trim()] as const).filter(
+ ([, tagValue]) => tagValue
+ )
+ // Encoded like the sent links, except variables, which stay readable because they differ per person.
+ const example = values
+ .map(([key, tagValue]) => `${key}=${tagValue.includes('{{') ? tagValue : encodeURIComponent(tagValue)}`)
+ .join('&')
+ const hasVariables = values.some(([, tagValue]) => tagValue.includes('{{'))
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-1 items-center">
+ {UTM_TAG_KEYS.map((key) => (
+ <div key={key} className="contents">
+ <span className="text-xs font-mono text-secondary">{key}</span>
+ <LemonInput
+ size="small"
+ value={value[key] ?? ''}
+ placeholder={defaults[key] || 'Not set'}
+ onChange={(next) => {
+ const { [key]: _, ...rest } = value
+ onChange(next.trim() ? { ...rest, [key]: next } : rest)
+ }}
+ data-attr={`email-utm-${key.replace('utm_', '')}`}
+ />
+ </div>
+ ))}
+ </div>
+ <span className="text-xs text-secondary">
+ Leave a field empty to use the value shown. Fields accept variables like{' '}
+ <code>{'{{ person.properties.plan }}'}</code>.
+ </span>
+ <span className="text-xs text-secondary break-all">
+ Example: https://example.com/?{example}
+ {hasVariables ? ' (variables are filled in for each person)' : ''}
+ </span>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
index 3b0050207b1a..b31782d37a71 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepDelayLogic.ts
@@ -465,6 +465,15 @@ export interface stepDelayLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
) => {
actionId: string
@@ -761,6 +770,15 @@ export interface stepDelayLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
} // workflowLogic
setDelayMode: (
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
index 17bea541cd16..943e20296f02 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/stepWaitUntilTimeWindowLogic.ts
@@ -391,6 +391,15 @@ export interface stepWaitUntilTimeWindowLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
>
) => {
@@ -688,6 +697,15 @@ export interface stepWaitUntilTimeWindowLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
>
} // workflowLogic
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
index 80281ad8c82c..a975deb1db88 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts
@@ -368,6 +368,17 @@ export const HogFlowActionSchema = z.discriminatedUnion('type', [
// untracked SES configuration set. Absent/true means tracked. Keep in sync with
// nodejs/src/cdp/schema/hogflow.ts.
tracking_enabled: z.boolean().optional(),
+ // When true, links get the UTM tags they don't already carry. Keep in sync with nodejs/src/cdp/schema/hogflow.ts.
+ utm_tags_enabled: z.boolean().optional(),
+ // Templates that replace the default tag values. An empty value keeps the default.
+ utm_params: z
+ .object({
+ utm_source: z.string().optional(),
+ utm_medium: z.string().optional(),
+ utm_campaign: z.string().optional(),
+ utm_content: z.string().optional(),
+ })
+ .optional(),
template_uuid: z.string().optional(), // May be used later to specify a specific template version
template_id: z.literal('template-email'),
inputs: z.record(z.string(), CyclotronInputSchema),
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index 0c4def52a7b6..b510ab90be76 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -593,6 +593,15 @@ export interface workflowLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string
@@ -1449,6 +1458,15 @@ export interface workflowLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string
@@ -2351,6 +2369,15 @@ export interface workflowLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
>
}
@@ -2733,6 +2760,15 @@ export interface workflowLogicActions {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
}
setWorkflowActionEdges: (
diff --git a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
index e89687bc2d00..ff94e1b27a8f 100644
--- a/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowMetricsSummaryLogic.ts
@@ -482,6 +482,15 @@ export interface workflowMetricsSummaryLogicValues {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string
@@ -707,6 +716,15 @@ export interface workflowMetricsSummaryLogicMeta {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string
@@ -840,6 +858,15 @@ export interface workflowMetricsSummaryLogicMeta {
template_id: 'template-email'
template_uuid?: string | undefined
tracking_enabled?: boolean | undefined
+ utm_params?:
+ | {
+ utm_campaign?: string | undefined
+ utm_content?: string | undefined
+ utm_medium?: string | undefined
+ utm_source?: string | undefined
+ }
+ | undefined
+ utm_tags_enabled?: boolean | undefined
}
created_at?: number | undefined
description: string