Skip to content

πŸ“ˆ Open source, privacy-first web analytics β€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Support experiments & goals for v2 stats API

Blue Mouse3bc746db3365
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index e7741ba81..fe7f6d6df 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -43,6 +43,7 @@ import {
DataType,
getLowestPossibleTimeBucket,
} from './analytics.service'
+import { normalizeFiltersToV1Json } from './v2/query/filters.translator'
import { VALID_PERIODS } from './decorators/validate-period.decorator'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
@@ -1122,7 +1123,11 @@ export class AnalyticsController {
)
const [filtersQuery, filtersParams, appliedFilters] =
- this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS, true)
+ this.analyticsService.getFiltersQuery(
+ normalizeFiltersToV1Json(filters, 'traffic'),
+ DataType.ANALYTICS,
+ true,
+ )
const params = { pid, groupFrom, groupTo, ...filtersParams }
@@ -1198,7 +1203,7 @@ export class AnalyticsController {
)
const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
- filters || '[]',
+ normalizeFiltersToV1Json(filters, 'traffic'),
DataType.ANALYTICS,
)
const params = { pid, groupFrom, groupTo, ...filtersParams }
@@ -2578,7 +2583,10 @@ export class AnalyticsController {
)
const [filtersQuery, filtersParams, appliedFilters, customEVFilterApplied] =
- this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS)
+ this.analyticsService.getFiltersQuery(
+ normalizeFiltersToV1Json(filters, 'traffic'),
+ DataType.ANALYTICS,
+ )
let timeBucket
let diff
@@ -3044,7 +3052,7 @@ export class AnalyticsController {
return this.analyticsService.getDataDeletionPreview(
body.pid,
- body.filters || '[]',
+ normalizeFiltersToV1Json(body.filters, 'traffic'),
body.from || null,
body.to || null,
)
@@ -3068,7 +3076,7 @@ export class AnalyticsController {
await this.analyticsService.deleteData(
body.pid,
- body.filters || '[]',
+ normalizeFiltersToV1Json(body.filters, 'traffic'),
body.from || null,
body.to || null,
body.types,
diff --git a/backend/apps/cloud/src/analytics/v2/__tests__/filters.translator.spec.ts b/backend/apps/cloud/src/analytics/v2/__tests__/filters.translator.spec.ts
index adec3deb3..f2ff9239c 100644
--- a/backend/apps/cloud/src/analytics/v2/__tests__/filters.translator.spec.ts
+++ b/backend/apps/cloud/src/analytics/v2/__tests__/filters.translator.spec.ts
@@ -1,6 +1,10 @@
import { UnprocessableEntityException } from '@nestjs/common'
-import { parseV2Filters, toV1FiltersJson } from '../query/filters.translator'
+import {
+ normalizeFiltersToV1Json,
+ parseV2Filters,
+ toV1FiltersJson,
+} from '../query/filters.translator'
describe('parseV2Filters', () => {
it('returns [] for empty input', () => {
@@ -173,3 +177,36 @@ describe('toV1FiltersJson', () => {
])
})
})
+
+describe('normalizeFiltersToV1Json', () => {
+ it('returns "" for empty input', () => {
+ expect(normalizeFiltersToV1Json(undefined, 'traffic')).toBe('')
+ expect(normalizeFiltersToV1Json('', 'traffic')).toBe('')
+ expect(normalizeFiltersToV1Json('""', 'traffic')).toBe('')
+ expect(normalizeFiltersToV1Json('[]', 'traffic')).toBe('')
+ })
+
+ it('passes legacy v1 filters through untouched (public API back-compat)', () => {
+ const v1 = JSON.stringify([
+ { column: 'cc', filter: 'US', isExclusive: false, isContains: false },
+ ])
+
+ expect(normalizeFiltersToV1Json(v1, 'traffic')).toBe(v1)
+ })
+
+ it('translates v2 filters into the v1 shape', () => {
+ const v2 = JSON.stringify([
+ { dimension: 'country', operator: 'is_not', value: 'US' },
+ ])
+
+ const v1 = JSON.parse(normalizeFiltersToV1Json(v2, 'traffic'))
+
+ expect(v1).toEqual([
+ { column: 'cc', filter: 'US', isExclusive: true, isContains: false },
+ ])
+ })
+
+ it('returns malformed input unchanged for getFiltersQuery to handle', () => {
+ expect(normalizeFiltersToV1Json('not json', 'traffic')).toBe('not json')
+ })
+})
diff --git a/backend/apps/cloud/src/analytics/v2/query/filters.translator.ts b/backend/apps/cloud/src/analytics/v2/query/filters.translator.ts
index daf09d212..9b6f21d19 100644
--- a/backend/apps/cloud/src/analytics/v2/query/filters.translator.ts
+++ b/backend/apps/cloud/src/analytics/v2/query/filters.translator.ts
@@ -202,3 +202,50 @@ export const toV1FiltersJson = (
return JSON.stringify(v1Filters)
}
+
+/**
+ * Normalise a `filters` query param that may be in EITHER the v2 shape
+ * ({ dimension, operator, value, key? }) or the legacy v1 shape
+ * ({ column, filter, isExclusive, isContains }) into the v1 filters JSON string
+ * consumed by AnalyticsService.getFiltersQuery.
+ *
+ * Used by endpoints that are also part of the public v1 API, so existing API
+ * clients sending v1 filters keep working while the dashboard sends v2.
+ */
+export const normalizeFiltersToV1Json = (
+ filters: string | undefined,
+ type: V2DataType,
+ options: { lenient?: boolean } = {},
+): string => {
+ if (!filters || filters === '""') {
+ return ''
+ }
+
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(filters)
+ } catch {
+ // Leave malformed input to getFiltersQuery, which logs and ignores it.
+ return filters
+ }
+
+ if (!Array.isArray(parsed) || parsed.length === 0) {
+ return ''
+ }
+
+ // Legacy v1 clients key filters by `column`; pass those straight through.
+ // v2 clients (and the dashboard) send `dimension` and are translated.
+ const isLegacyV1 = parsed.every(
+ (filter) =>
+ filter &&
+ typeof filter === 'object' &&
+ 'column' in filter &&
+ !('dimension' in filter),
+ )
+
+ if (isLegacyV1) {
+ return filters
+ }
+
+ return toV1FiltersJson(parseV2Filters(filters), type, options)
+}
diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.ts
index c76a3f69a..5ec7dd2e6 100644
--- a/backend/apps/cloud/src/common/constants.ts
+++ b/backend/apps/cloud/src/common/constants.ts
@@ -106,6 +106,41 @@ const TRAFFIC_COLUMNS = [
const TRAFFIC_METAKEY_COLUMNS = ['tag:key', 'tag:value']
const ALL_COLUMNS = [...TRAFFIC_COLUMNS, 'ev', 'entryPage', 'exitPage']
+
+// v2 dimension names allowed in a saved-view filter. Mirrors the traffic
+// dimensions in analytics/v2/registry/dimensions.ts β€” duplicated here because
+// project.service cannot import the registry without creating an
+// analytics.service <-> project.service import cycle.
+const V2_VIEW_FILTER_DIMENSIONS = [
+ 'country',
+ 'region',
+ 'city',
+ 'page',
+ 'host',
+ 'locale',
+ 'browser',
+ 'browser_version',
+ 'os',
+ 'os_version',
+ 'device',
+ 'referrer',
+ 'referrer_name',
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_term',
+ 'utm_content',
+ 'isp',
+ 'organization',
+ 'user_type',
+ 'connection_type',
+ 'entry_page',
+ 'exit_page',
+ 'event',
+ 'event_metadata',
+ 'page_property',
+]
+
const CAPTCHA_COLUMNS = [
'cc',
'br',
@@ -228,6 +263,7 @@ export {
redisUserUsageinfoCacheTimeout,
TRAFFIC_COLUMNS,
TRAFFIC_METAKEY_COLUMNS,
+ V2_VIEW_FILTER_DIMENSIONS,
CAPTCHA_COLUMNS,
ERROR_COLUMNS,
PERFORMANCE_COLUMNS,
diff --git a/backend/apps/cloud/src/experiment/experiment.controller.ts b/backend/apps/cloud/src/experiment/experiment.controller.ts
index 1d77f79af..10b78d9d7 100644
--- a/backend/apps/cloud/src/experiment/experiment.controller.ts
+++ b/backend/apps/cloud/src/experiment/experiment.controller.ts
@@ -43,6 +43,7 @@ import {
DataType,
getLowestPossibleTimeBucket,
} from '../analytics/analytics.service'
+import { normalizeFiltersToV1Json } from '../analytics/v2/query/filters.translator'
import { TimeBucketType } from '../analytics/dto/getData.dto'
import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
@@ -1043,7 +1044,10 @@ export class ExperimentController {
}
const [filtersQuery, filtersParams, appliedFilters] =
- this.analyticsService.getFiltersQuery(filters || '[]', DataType.ANALYTICS)
+ this.analyticsService.getFiltersQuery(
+ normalizeFiltersToV1Json(filters, 'traffic'),
+ DataType.ANALYTICS,
+ )
const isSegmented =
Array.isArray(appliedFilters) && appliedFilters.length > 0
diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.ts
index 8722ad880..8d264580d 100644
--- a/backend/apps/cloud/src/goal/goal.controller.ts
+++ b/backend/apps/cloud/src/goal/goal.controller.ts
@@ -33,6 +33,7 @@ import {
DataType,
getLowestPossibleTimeBucket,
} from '../analytics/analytics.service'
+import { normalizeFiltersToV1Json } from '../analytics/v2/query/filters.translator'
import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import {
@@ -82,12 +83,28 @@ const clampPagination = (take?: number, skip?: number) => {
return { take: safeTake, skip: safeSkip }
}
+// Maps a goal condition `field` to its ClickHouse column. New goals store v2
+// dimension names (page, country, utm_source, ...); the legacy v1 short codes
+// (pg, cc, so, ...) are kept so conditions saved before the v2 migration still
+// resolve.
const GOAL_CONDITION_COLUMNS: Record<string, string> = {
+ // v2 dimension names
page: 'pg',
- pg: 'pg',
event: 'event_name',
- event_name: 'event_name',
host: 'host',
+ country: 'cc',
+ device: 'dv',
+ browser: 'br',
+ os: 'os',
+ referrer: 'ref',
+ utm_source: 'so',
+ utm_medium: 'me',
+ utm_campaign: 'ca',
+ utm_term: 'te',
+ utm_content: 'co',
+ // legacy v1 short codes (existing goals)
+ pg: 'pg',
+ event_name: 'event_name',
ref: 'ref',
so: 'so',
me: 'me',
@@ -97,7 +114,6 @@ const GOAL_CONDITION_COLUMNS: Record<string, string> = {
cc: 'cc',
dv: 'dv',
br: 'br',
- os: 'os',
}
type GoalBreakdownKey =
@@ -875,7 +891,7 @@ export class GoalController {
)
const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
- filters || '[]',
+ normalizeFiltersToV1Json(filters, 'traffic'),
DataType.ANALYTICS,
)
const { query: conversionsSubquery, params: goalParams } =
@@ -1190,7 +1206,7 @@ export class GoalController {
const [selector, groupBy] = this.getGroupSubquery(resolvedTimeBucket)
const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
- filters || '[]',
+ normalizeFiltersToV1Json(filters, 'traffic'),
DataType.ANALYTICS,
)
const { query: conversionsSubquery, params: goalParams } =
diff --git a/backend/apps/cloud/src/project/dto/create-project-view.dto.ts b/backend/apps/cloud/src/project/dto/create-project-view.dto.ts
index 8d89ebbbd..893992d8f 100644
--- a/backend/apps/cloud/src/project/dto/create-project-view.dto.ts
+++ b/backend/apps/cloud/src/project/dto/create-project-view.dto.ts
@@ -12,7 +12,6 @@ import {
import { ApiProperty } from '@nestjs/swagger'
import { ProjectViewType } from '../entity/project-view.entity'
import { ProjectViewCustomEventMetaValueType } from '../entity/project-view-custom-event.entity'
-import { TRAFFIC_COLUMNS } from '../../common/constants'
export class ProjectViewCustomEventDto {
@ApiProperty()
@@ -47,11 +46,14 @@ export class ProjectViewCustomEventDto {
metaValueType: ProjectViewCustomEventMetaValueType
}
+// Saved-view filters are persisted as opaque JSON. New views store the v2
+// filter shape; older views may still hold the legacy { column, filter,
+// isExclusive } shape, which the web normalises on read.
export interface Filter {
- column: keyof typeof TRAFFIC_COLUMNS
- filter: string
- isExclusive: boolean
- isContains?: boolean
+ dimension: string
+ operator: 'is' | 'is_not' | 'contains' | 'contains_not'
+ value: string | null | (string | null)[]
+ key?: string
}
export const MAX_METRICS_IN_VIEW = 3
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index 001967bc2..2721dccd0 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -529,31 +529,37 @@ export class GSCService {
throw new BadRequestException('Invalid filters parameter')
}
- const {
- column,
- filter: value,
- isExclusive,
- isContains,
- } = filter as {
+ const raw = filter as {
+ dimension?: unknown
+ operator?: unknown
+ value?: unknown
column?: unknown
filter?: unknown
isExclusive?: unknown
isContains?: unknown
}
- if (typeof column !== 'string' || typeof value !== 'string') {
- throw new BadRequestException('Invalid filters parameter')
+ // Accept both the v2 shape ({ dimension, operator, value }) and the
+ // legacy v1 shape ({ column, filter, isExclusive, isContains }).
+ const isV2 = typeof raw.dimension === 'string'
+ const filterDimension = isV2 ? raw.dimension : raw.column
+ const value = isV2 ? raw.value : raw.filter
+
+ // GSC only supports single-value string filters; skip null/array values
+ // and dimensions it doesn't understand.
+ if (typeof filterDimension !== 'string' || typeof value !== 'string') {
+ continue
}
if (value.length > MAX_FILTER_EXPRESSION_LENGTH) continue
let dimension: string | undefined
let expression = value
- if (column === 'pg') {
+ if (filterDimension === 'page' || filterDimension === 'pg') {
dimension = 'page'
- } else if (column === 'keywords') {
+ } else if (filterDimension === 'keywords') {
dimension = 'query'
- } else if (column === 'country' || column === 'cc') {
+ } else if (filterDimension === 'country' || filterDimension === 'cc') {
dimension = 'country'
if (expression.length === 2) {
const alpha3 = countries.alpha2ToAlpha3(expression.toUpperCase())
@@ -562,7 +568,7 @@ export class GSCService {
} else {
expression = expression.toLowerCase()
}
- } else if (column === 'device' || column === 'dv') {
+ } else if (filterDimension === 'device' || filterDimension === 'dv') {
dimension = 'device'
expression = expression.toUpperCase()
} else {
@@ -570,9 +576,17 @@ export class GSCService {
}
let operator = 'equals'
- if (isExclusive) {
- operator = isContains ? 'notContains' : 'notEquals'
- } else if (isContains) {
+ if (isV2) {
+ if (raw.operator === 'is_not') {
+ operator = 'notEquals'
+ } else if (raw.operator === 'contains') {
+ operator = 'contains'
+ } else if (raw.operator === 'contains_not') {
+ operator = 'notContains'
+ }
+ } else if (raw.isExclusive) {
+ operator = raw.isContains ? 'notContains' : 'notEquals'
+ } else if (raw.isContains) {
operator = 'contains'
}
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index 9e2c0106e..d2d4f11fc 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -60,8 +60,7 @@ import {
redisUserUsageinfoCacheTimeout,
TRAFFIC_COLUMNS,
EMAIL_ACTION_ENCRYPTION_KEY,
- ALL_COLUMNS,
- TRAFFIC_METAKEY_COLUMNS,
+ V2_VIEW_FILTER_DIMENSIONS,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import { IUsageInfoRedis } from '../user/interfaces'
@@ -1549,11 +1548,8 @@ export class ProjectService {
return []
}
- return _filter(
- filters,
- ({ column }) =>
- _includes(ALL_COLUMNS, column as string) ||
- _includes(TRAFFIC_METAKEY_COLUMNS, column as string),
+ return _filter(filters, ({ dimension }) =>
+ _includes(V2_VIEW_FILTER_DIMENSIONS, dimension),
)
}
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 9b16c8137..1d140ec06 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -35,6 +35,7 @@ import {
DataType,
getLowestPossibleTimeBucket,
} from './analytics.service'
+import { normalizeFiltersToV1Json } from './v2/query/filters.translator'
import { VALID_PERIODS } from './decorators/validate-period.decorator'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
@@ -984,7 +985,11 @@ export class AnalyticsController {
)
const [filtersQuery, filtersParams, parsedFilters] =
- this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS, true)
+ this.analyticsService.getFiltersQuery(
+ normalizeFiltersToV1Json(filters, 'traffic'),
+ DataType.ANALYTICS,
+ true,
+ )
const params = { pid, groupFrom, groupTo, ...filtersParams }
@@ -1058,7 +1063,7 @@ export class AnalyticsController {
)
const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
- filters || '[]',
+ normalizeFiltersToV1Json(filters, 'traffic'),
DataType.ANALYTICS,
)
const params = { pid, groupFrom, groupTo, ...filtersParams }
@@ -1281,7 +1286,7 @@ export class AnalyticsController {
return this.analyticsService.getDataDeletionPreview(
body.pid,
- body.filters || '[]',
+ normalizeFiltersToV1Json(body.filters, 'traffic'),
body.from || null,
body.to || null,
)
@@ -1303,7 +1308,7 @@ export class AnalyticsController {
await this.analyticsService.deleteData(
body.pid,
- body.filters || '[]',
+ normalizeFiltersToV1Json(body.filters, 'traffic'),
body.from || null,
body.to || null,
body.types || ['pageview', 'custom_event'],
diff --git a/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.ts b/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.ts
index adec3deb3..f2ff9239c 100644
--- a/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.ts
+++ b/backend/apps/community/src/analytics/v2/__tests__/filters.translator.spec.ts
@@ -1,6 +1,10 @@
import { UnprocessableEntityException } from '@nestjs/common'
-import { parseV2Filters, toV1FiltersJson } from '../query/filters.translator'
+import {
+ normalizeFiltersToV1Json,
+ parseV2Filters,
+ toV1FiltersJson,
+} from '../query/filters.translator'
describe('parseV2Filters', () => {
it('returns [] for empty input', () => {
@@ -173,3 +177,36 @@ describe('toV1FiltersJson', () => {
])
})
})
+
+describe('normalizeFiltersToV1Json', () => {
+ it('returns "" for empty input', () => {
+ expect(normalizeFiltersToV1Json(undefined, 'traffic')).toBe('')
+ expect(normalizeFiltersToV1Json('', 'traffic')).toBe('')
+ expect(normalizeFiltersToV1Json('""', 'traffic')).toBe('')
+ expect(normalizeFiltersToV1Json('[]', 'traffic')).toBe('')
+ })
+
+ it('passes legacy v1 filters through untouched (public API back-compat)', () => {
+ const v1 = JSON.stringify([
+ { column: 'cc', filter: 'US', isExclusive: false, isContains: false },
+ ])
+
+ expect(normalizeFiltersToV1Json(v1, 'traffic')).toBe(v1)
+ })
+
+ it('translates v2 filters into the v1 shape', () => {
+ const v2 = JSON.stringify([
+ { dimension: 'country', operator: 'is_not', value: 'US' },
+ ])
+
+ const v1 = JSON.parse(normalizeFiltersToV1Json(v2, 'traffic'))
+
+ expect(v1).toEqual([
+ { column: 'cc', filter: 'US', isExclusive: true, isContains: false },
+ ])
+ })
+
+ it('returns malformed input unchanged for getFiltersQuery to handle', () => {
+ expect(normalizeFiltersToV1Json('not json', 'traffic')).toBe('not json')
+ })
+})
diff --git a/backend/apps/community/src/analytics/v2/query/filters.translator.ts b/backend/apps/community/src/analytics/v2/query/filters.translator.ts
index daf09d212..9b6f21d19 100644
--- a/backend/apps/community/src/analytics/v2/query/filters.translator.ts
+++ b/backend/apps/community/src/analytics/v2/query/filters.translator.ts
@@ -202,3 +202,50 @@ export const toV1FiltersJson = (
return JSON.stringify(v1Filters)
}
+
+/**
+ * Normalise a `filters` query param that may be in EITHER the v2 shape
+ * ({ dimension, operator, value, key? }) or the legacy v1 shape
+ * ({ column, filter, isExclusive, isContains }) into the v1 filters JSON string
+ * consumed by AnalyticsService.getFiltersQuery.
+ *
+ * Used by endpoints that are also part of the public v1 API, so existing API
+ * clients sending v1 filters keep working while the dashboard sends v2.
+ */
+export const normalizeFiltersToV1Json = (
+ filters: string | undefined,
+ type: V2DataType,
+ options: { lenient?: boolean } = {},
+): string => {
+ if (!filters || filters === '""') {
+ return ''
+ }
+
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(filters)
+ } catch {
+ // Leave malformed input to getFiltersQuery, which logs and ignores it.
+ return filters
+ }
+
+ if (!Array.isArray(parsed) || parsed.length === 0) {
+ return ''
+ }
+
+ // Legacy v1 clients key filters by `column`; pass those straight through.
+ // v2 clients (and the dashboard) send `dimension` and are translated.
+ const isLegacyV1 = parsed.every(
+ (filter) =>
+ filter &&
+ typeof filter === 'object' &&
+ 'column' in filter &&
+ !('dimension' in filter),
+ )
+
+ if (isLegacyV1) {
+ return filters
+ }
+
+ return toV1FiltersJson(parseV2Filters(filters), type, options)
+}
diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.ts
index 4c779973e..50a635e52 100644
--- a/backend/apps/community/src/common/constants.ts
+++ b/backend/apps/community/src/common/constants.ts
@@ -133,6 +133,40 @@ const ERROR_COLUMNS = [
const ALL_COLUMNS = [...TRAFFIC_COLUMNS, 'ev', 'entryPage', 'exitPage']
+// v2 dimension names allowed in a saved-view filter. Mirrors the traffic
+// dimensions in analytics/v2/registry/dimensions.ts β€” duplicated here because
+// project.service cannot import the registry without creating an
+// analytics.service <-> project.service import cycle.
+const V2_VIEW_FILTER_DIMENSIONS = [
+ 'country',
+ 'region',
+ 'city',
+ 'page',
+ 'host',
+ 'locale',
+ 'browser',
+ 'browser_version',
+ 'os',
+ 'os_version',
+ 'device',
+ 'referrer',
+ 'referrer_name',
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_term',
+ 'utm_content',
+ 'isp',
+ 'organization',
+ 'user_type',
+ 'connection_type',
+ 'entry_page',
+ 'exit_page',
+ 'event',
+ 'event_metadata',
+ 'page_property',
+]
+
const PERFORMANCE_COLUMNS = [
'cc',
'rg',
@@ -170,6 +204,7 @@ export {
ERROR_COLUMNS,
PID_REGEX,
ALL_COLUMNS,
+ V2_VIEW_FILTER_DIMENSIONS,
SELFHOSTED_GEOIP_DB_PATH,
TWO_FACTOR_AUTHENTICATION_APP_NAME,
OIDC_ENABLED,
diff --git a/backend/apps/community/src/experiment/experiment.controller.ts b/backend/apps/community/src/experiment/experiment.controller.ts
index 91725a85a..c190b835e 100644
--- a/backend/apps/community/src/experiment/experiment.controller.ts
+++ b/backend/apps/community/src/experiment/experiment.controller.ts
@@ -36,6 +36,7 @@ import {
DataType,
getLowestPossibleTimeBucket,
} from '../analytics/analytics.service'
+import { normalizeFiltersToV1Json } from '../analytics/v2/query/filters.translator'
import { TimeBucketType } from '../analytics/dto/getData.dto'
import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
@@ -674,7 +675,10 @@ export class ExperimentController {
}
const [filtersQuery, filtersParams, appliedFilters] =
- this.analyticsService.getFiltersQuery(filters || '[]', DataType.ANALYTICS)
+ this.analyticsService.getFiltersQuery(
+ normalizeFiltersToV1Json(filters, 'traffic'),
+ DataType.ANALYTICS,
+ )
const isSegmented =
Array.isArray(appliedFilters) && appliedFilters.length > 0
diff --git a/backend/apps/community/src/goal/goal.controller.ts b/backend/apps/community/src/goal/goal.controller.ts
index 0be7b6976..2641fe998 100644
--- a/backend/apps/community/src/goal/goal.controller.ts
+++ b/backend/apps/community/src/goal/goal.controller.ts
@@ -27,6 +27,7 @@ import {
DataType,
getLowestPossibleTimeBucket,
} from '../analytics/analytics.service'
+import { normalizeFiltersToV1Json } from '../analytics/v2/query/filters.translator'
import { Auth } from '../auth/decorators'
import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
import {
@@ -69,12 +70,28 @@ const clampPagination = (take?: number, skip?: number) => {
return { take: safeTake, skip: safeSkip }
}
+// Maps a goal condition `field` to its ClickHouse column. New goals store v2
+// dimension names (page, country, utm_source, ...); the legacy v1 short codes
+// (pg, cc, so, ...) are kept so conditions saved before the v2 migration still
+// resolve.
const GOAL_CONDITION_COLUMNS: Record<string, string> = {
+ // v2 dimension names
page: 'pg',
- pg: 'pg',
event: 'event_name',
- event_name: 'event_name',
host: 'host',
+ country: 'cc',
+ device: 'dv',
+ browser: 'br',
+ os: 'os',
+ referrer: 'ref',
+ utm_source: 'so',
+ utm_medium: 'me',
+ utm_campaign: 'ca',
+ utm_term: 'te',
+ utm_content: 'co',
+ // legacy v1 short codes (existing goals)
+ pg: 'pg',
+ event_name: 'event_name',
ref: 'ref',
so: 'so',
me: 'me',
@@ -84,7 +101,6 @@ const GOAL_CONDITION_COLUMNS: Record<string, string> = {
cc: 'cc',
dv: 'dv',
br: 'br',
- os: 'os',
}
type GoalBreakdownKey =
@@ -793,7 +809,7 @@ export class GoalController {
)
const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
- filters || '[]',
+ normalizeFiltersToV1Json(filters, 'traffic'),
DataType.ANALYTICS,
)
const { query: conversionsSubquery, params: goalParams } =
@@ -1106,7 +1122,7 @@ export class GoalController {
const [selector, groupBy] = this.getGroupSubquery(resolvedTimeBucket)
const [filtersQuery, filtersParams] = this.analyticsService.getFiltersQuery(
- filters || '[]',
+ normalizeFiltersToV1Json(filters, 'traffic'),
DataType.ANALYTICS,
)
const { query: conversionsSubquery, params: goalParams } =
diff --git a/backend/apps/community/src/project/dto/create-project-view.dto.ts b/backend/apps/community/src/project/dto/create-project-view.dto.ts
index 8d89ebbbd..893992d8f 100644
--- a/backend/apps/community/src/project/dto/create-project-view.dto.ts
+++ b/backend/apps/community/src/project/dto/create-project-view.dto.ts
@@ -12,7 +12,6 @@ import {
import { ApiProperty } from '@nestjs/swagger'
import { ProjectViewType } from '../entity/project-view.entity'
import { ProjectViewCustomEventMetaValueType } from '../entity/project-view-custom-event.entity'
-import { TRAFFIC_COLUMNS } from '../../common/constants'
export class ProjectViewCustomEventDto {
@ApiProperty()
@@ -47,11 +46,14 @@ export class ProjectViewCustomEventDto {
metaValueType: ProjectViewCustomEventMetaValueType
}
+// Saved-view filters are persisted as opaque JSON. New views store the v2
+// filter shape; older views may still hold the legacy { column, filter,
+// isExclusive } shape, which the web normalises on read.
export interface Filter {
- column: keyof typeof TRAFFIC_COLUMNS
- filter: string
- isExclusive: boolean
- isContains?: boolean
+ dimension: string
+ operator: 'is' | 'is_not' | 'contains' | 'contains_not'
+ value: string | null | (string | null)[]
+ key?: string
}
export const MAX_METRICS_IN_VIEW = 3
diff --git a/backend/apps/community/src/project/gsc.service.ts b/backend/apps/community/src/project/gsc.service.ts
index ebd548d21..50e90b4d7 100644
--- a/backend/apps/community/src/project/gsc.service.ts
+++ b/backend/apps/community/src/project/gsc.service.ts
@@ -587,31 +587,37 @@ export class GSCService {
throw new BadRequestException('Invalid filters parameter')
}
- const {
- column,
- filter: value,
- isExclusive,
- isContains,
- } = filter as {
+ const raw = filter as {
+ dimension?: unknown
+ operator?: unknown
+ value?: unknown
column?: unknown
filter?: unknown
isExclusive?: unknown
isContains?: unknown
}
- if (typeof column !== 'string' || typeof value !== 'string') {
- throw new BadRequestException('Invalid filters parameter')
+ // Accept both the v2 shape ({ dimension, operator, value }) and the
+ // legacy v1 shape ({ column, filter, isExclusive, isContains }).
+ const isV2 = typeof raw.dimension === 'string'
+ const filterDimension = isV2 ? raw.dimension : raw.column
+ const value = isV2 ? raw.value : raw.filter
+
+ // GSC only supports single-value string filters; skip null/array values
+ // and dimensions it doesn't understand.
+ if (typeof filterDimension !== 'string' || typeof value !== 'string') {
+ continue
}
if (value.length > MAX_FILTER_EXPRESSION_LENGTH) continue
let dimension: string | undefined
let expression = value
- if (column === 'pg') {
+ if (filterDimension === 'page' || filterDimension === 'pg') {
dimension = 'page'
- } else if (column === 'keywords') {
+ } else if (filterDimension === 'keywords') {
dimension = 'query'
- } else if (column === 'country' || column === 'cc') {
+ } else if (filterDimension === 'country' || filterDimension === 'cc') {
dimension = 'country'
if (expression.length === 2) {
const alpha3 = countries.alpha2ToAlpha3(expression.toUpperCase())
@@ -620,7 +626,7 @@ export class GSCService {
} else {
expression = expression.toLowerCase()
}
- } else if (column === 'device' || column === 'dv') {
+ } else if (filterDimension === 'device' || filterDimension === 'dv') {
dimension = 'device'
expression = expression.toUpperCase()
} else {
@@ -628,9 +634,17 @@ export class GSCService {
}
let operator = 'equals'
- if (isExclusive) {
- operator = isContains ? 'notContains' : 'notEquals'
- } else if (isContains) {
+ if (isV2) {
+ if (raw.operator === 'is_not') {
+ operator = 'notEquals'
+ } else if (raw.operator === 'contains') {
+ operator = 'contains'
+ } else if (raw.operator === 'contains_not') {
+ operator = 'notContains'
+ }
+ } else if (raw.isExclusive) {
+ operator = raw.isContains ? 'notContains' : 'notEquals'
+ } else if (raw.isContains) {
operator = 'contains'
}
diff --git a/backend/apps/community/src/project/project.service.ts b/backend/apps/community/src/project/project.service.ts
index 35994c47d..28ba99865 100644
--- a/backend/apps/community/src/project/project.service.ts
+++ b/backend/apps/community/src/project/project.service.ts
@@ -32,8 +32,7 @@ import {
ORIGINS_REGEX,
getRedisProjectKey,
redisProjectCacheTimeout,
- ALL_COLUMNS,
- TRAFFIC_METAKEY_COLUMNS,
+ V2_VIEW_FILTER_DIMENSIONS,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
import {
@@ -454,11 +453,8 @@ export class ProjectService {
return []
}
- return _filter(
- filters,
- ({ column }) =>
- _includes(ALL_COLUMNS, column as string) ||
- _includes(TRAFFIC_METAKEY_COLUMNS, column as string),
+ return _filter(filters, ({ dimension }) =>
+ _includes(V2_VIEW_FILTER_DIMENSIONS, dimension),
)
}
diff --git a/docs/content/docs/api/stats-v2.mdx b/docs/content/docs/api/stats-v2.mdx
index 06c60e566..97899ae6f 100644
--- a/docs/content/docs/api/stats-v2.mdx
+++ b/docs/content/docs/api/stats-v2.mdx
@@ -57,12 +57,12 @@ Every endpoint returns the same envelope:
`metrics` is a comma-separated list of metric names, validated per data type. Each endpoint has sensible defaults. Discover all metrics for a data type via the [dimensions endpoint](#get-v2projectspiddimensions).
-| Data type | Metrics |
-| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Data type | Metrics |
+| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| traffic | `visitors` (unique sessions), `pageviews`, `users` (unique profiles; breakdown/summary only), `session_duration` (timeseries/summary only), `bounce_rate` (timeseries/summary only), `concurrency` (live visitors over time; timeseries only, ignores filters) |
-| performance | `load_time`, `ttfb`, `dns`, `tls`, `connection`, `response`, `render`, `dom_load` β€” all in seconds, aggregated by `measure` |
-| errors | `occurrences`, `affected_users` |
-| captcha | `events` (breakdown), `generated`, `passed`, `failed`, `validation_failed`, `replayed` (timeseries/summary) |
+| performance | `load_time`, `ttfb`, `dns`, `tls`, `connection`, `response`, `render`, `dom_load` β€” all in seconds, aggregated by `measure` |
+| errors | `occurrences`, `affected_users` |
+| captcha | `events` (breakdown), `generated`, `passed`, `failed`, `validation_failed`, `replayed` (timeseries/summary) |
### Dimensions
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 70c0dcc6d..a973224ff 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -10,6 +10,7 @@ import {
isPersistentSession,
} from '~/utils/session.server'
import { API_URL } from '~/lib/constants'
+import type { V2Filter } from '~/api/v2/types'
// ============================================================================
// MARK: API utils
@@ -725,13 +726,6 @@ export async function getGeneralStats(request: Request): Promise<Stats | null> {
// MARK: Analytics Data API (Deferred Loading)
// ============================================================================
-export interface AnalyticsFilter {
- column: string
- filter: string
- isExclusive: boolean
- isContains?: boolean
-}
-
interface OverallPeriodStats {
all: number
unique?: number
@@ -755,7 +749,7 @@ export interface OverallObject {
export interface AnalyticsParams {
timeBucket: string
period: string
- filters: AnalyticsFilter[]
+ filters: V2Filter[]
from?: string
to?: string
timezone: string
@@ -766,7 +760,7 @@ export interface AnalyticsParams {
includeConcurrency?: boolean
}
-function serializeFiltersForUrl(filters: AnalyticsFilter[]): string {
+function serializeFiltersForUrl(filters: V2Filter[]): string {
return JSON.stringify(filters)
}
@@ -843,7 +837,6 @@ export interface SessionReplaysResponse {
replays: SessionReplayListItem[]
take: number
skip: number
- appliedFilters: AnalyticsFilter[]
}
export async function getSessionReplaysServer(
@@ -903,7 +896,7 @@ export async function getJourneySessionsServer(
take?: number
skip?: number
password?: string
- filters?: AnalyticsFilter[]
+ filters?: V2Filter[]
},
): Promise<ServerFetchResult<JourneySessionsResponse>> {
const step = Math.min(10, Math.max(1, Math.floor(Number(params.step) || 1)))
@@ -1317,7 +1310,7 @@ export async function getGoalStatsServer(
from = '',
to = '',
timezone?: string,
- filters: AnalyticsFilter[] = [],
+ filters: V2Filter[] = [],
): Promise<ServerFetchResult<GoalStats>> {
const params = new URLSearchParams({ period })
if (from) params.append('from', from)
@@ -1345,7 +1338,7 @@ export async function getGoalChartServer(
to = '',
timeBucket = 'day',
timezone?: string,
- filters: AnalyticsFilter[] = [],
+ filters: V2Filter[] = [],
): Promise<ServerFetchResult<{ chart: GoalChartData }>> {
const params = new URLSearchParams({ period, timeBucket })
if (from) params.append('from', from)
@@ -1457,7 +1450,7 @@ export async function getExperimentResultsServer(
from = '',
to = '',
timezone?: string,
- filters: AnalyticsFilter[] = [],
+ filters: V2Filter[] = [],
): Promise<ServerFetchResult<ExperimentResults>> {
const params = new URLSearchParams({ period, timeBucket })
if (from) params.append('from', from)
@@ -1715,7 +1708,6 @@ interface Journey {
export interface JourneysResponse {
journeys: Journey[]
totalSessions: number
- appliedFilters?: AnalyticsFilter[]
}
export async function getJourneysServer(
@@ -1723,7 +1715,7 @@ export async function getJourneysServer(
pid: string,
params: {
period?: string
- filters?: AnalyticsFilter[]
+ filters?: V2Filter[]
from?: string
to?: string
timezone?: string
@@ -1794,7 +1786,7 @@ export async function getDataDeletionPreviewServer(
request: Request,
pid: string,
options: {
- filters?: AnalyticsFilter[]
+ filters?: V2Filter[]
from?: string
to?: string
},
@@ -2002,7 +1994,7 @@ export async function getGSCDashboardServer(
timezone?: string
password?: string
timeBucket?: string
- filters?: AnalyticsFilter[]
+ filters?: V2Filter[]
} = {},
): Promise<ServerFetchResult<GSCDashboardResponse>> {
const queryParams = new URLSearchParams()
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index eadfb8cde..d0686d195 100644
--- a/web/app/hooks/useAnalyticsProxy.ts
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -22,10 +22,10 @@ import type {
RevenueStatus,
RevenueDataResponse,
OverallObject,
- AnalyticsFilter,
DataDeletionPreview,
AnalyticsParams as ServerAnalyticsParams,
} from '~/api/api.server'
+import type { V2Filter } from '~/api/v2/types'
type ClientAnalyticsParams = Partial<
Omit<ServerAnalyticsParams, 'password'>
@@ -549,7 +549,7 @@ export function useDataDeletionPreviewProxy() {
async (
projectId: string,
options: {
- filters?: AnalyticsFilter[]
+ filters?: V2Filter[]
from?: string
to?: string
},
diff --git a/web/app/pages/Project/Settings/components/DeleteDataModal.tsx b/web/app/pages/Project/Settings/components/DeleteDataModal.tsx
index 746fe119b..25b53bc06 100644
--- a/web/app/pages/Project/Settings/components/DeleteDataModal.tsx
+++ b/web/app/pages/Project/Settings/components/DeleteDataModal.tsx
@@ -24,7 +24,6 @@ import { Text } from '~/ui/Text'
import { cn } from '~/utils/generic'
import type { V2Filter } from '~/api/v2/types'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import FilterRowsEditor from '../../View/components/FilterRowsEditor'
@@ -321,8 +320,7 @@ const DeleteDataModal = ({ pid, isOpen, onClose }: DeleteDataModalProps) => {
const handle = setTimeout(() => {
fetchPreview(pid, {
- // the deletion preview endpoint is still v1 β€” convert at the boundary
- filters: filters.map(v2FilterToLegacy),
+ filters,
from: range.from ?? undefined,
to: range.to ?? undefined,
})
@@ -414,7 +412,7 @@ const DeleteDataModal = ({ pid, isOpen, onClose }: DeleteDataModalProps) => {
const formData = new FormData()
formData.set('intent', 'delete-data')
- formData.set('filters', JSON.stringify(filters.map(v2FilterToLegacy)))
+ formData.set('filters', JSON.stringify(filters))
formData.set('types', JSON.stringify([...selectedTypes]))
if (range.from) formData.set('from', range.from)
if (range.to) formData.set('to', range.to)
diff --git a/web/app/pages/Project/View/components/AddAViewModal.tsx b/web/app/pages/Project/View/components/AddAViewModal.tsx
index 790e9cce5..18bf392a7 100644
--- a/web/app/pages/Project/View/components/AddAViewModal.tsx
+++ b/web/app/pages/Project/View/components/AddAViewModal.tsx
@@ -14,7 +14,6 @@ import Input from '~/ui/Input'
import Modal from '~/ui/Modal'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import {
ProjectView,
@@ -338,10 +337,7 @@ const AddAViewModal = ({
const metricsToSubmit = supportsCustomMetrics
? customEvents
: defaultView?.customEvents || []
- formData.append(
- 'filters',
- JSON.stringify(activeFilters.map(v2FilterToLegacy)),
- )
+ formData.append('filters', JSON.stringify(activeFilters))
formData.append('customEvents', JSON.stringify(metricsToSubmit))
formData.append('name', name)
diff --git a/web/app/pages/Project/View/interfaces/traffic.ts b/web/app/pages/Project/View/interfaces/traffic.ts
index 71c094897..6e94a8d9e 100644
--- a/web/app/pages/Project/View/interfaces/traffic.ts
+++ b/web/app/pages/Project/View/interfaces/traffic.ts
@@ -1,6 +1,8 @@
import { TimeBucket } from '~/lib/constants'
+import { V2Filter } from '~/api/v2/types'
-// Legacy (v1) filter shape β€” still used by saved project views (server-side format)
+// Legacy (v1) filter shape β€” views saved before the v2 migration still persist
+// this; newer views persist the v2 shape (see ProjectView.filters).
interface Filter {
column: string
filter: string
@@ -27,7 +29,7 @@ export interface ProjectViewCustomEvent {
export interface ProjectView {
id: string
name: string
- filters?: Filter[]
+ filters?: (Filter | V2Filter)[]
customEvents?: ProjectViewCustomEvent[]
}
diff --git a/web/app/pages/Project/View/utils/projectViewSegments.ts b/web/app/pages/Project/View/utils/projectViewSegments.ts
index a0e478e29..3142b181b 100644
--- a/web/app/pages/Project/View/utils/projectViewSegments.ts
+++ b/web/app/pages/Project/View/utils/projectViewSegments.ts
@@ -7,10 +7,14 @@ import { ProjectView } from '../interfaces/traffic'
type ProjectTab = keyof typeof PROJECT_TABS
-// Saved project views keep the legacy filter shape server-side; convert to
-// the v2 shape at this boundary (unmappable legacy filters are dropped).
+// New project views persist the v2 filter shape; views saved before the v2
+// migration still hold the legacy shape, so normalise both here (unmappable
+// legacy filters are dropped).
export const projectViewFiltersToV2 = (view?: ProjectView): V2Filter[] =>
(view?.filters || []).flatMap((filter) => {
+ if ('dimension' in filter) {
+ return [filter]
+ }
const converted = legacyFilterToV2(filter)
return converted ? [converted] : []
})
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
index 249743885..8bdfa2598 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
@@ -59,7 +59,6 @@ import { Badge } from '~/ui/Badge'
import Modal from '~/ui/Modal'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import { nFormatter } from '~/utils/generic'
import ExperimentSettingsModal from './ExperimentSettingsModal'
@@ -768,8 +767,7 @@ const ExperimentResults = ({
from,
to,
timezone,
- // experiments endpoints are still v1 β€” convert at the boundary
- filters: filters.map(v2FilterToLegacy),
+ filters,
}),
])
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
index e55ca1751..444a9ded7 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
@@ -23,10 +23,10 @@ import { useFetcher, useLocation, useSearchParams } from 'react-router'
import { toast } from 'sonner'
import type {
- AnalyticsFilter,
ExperimentResults as ExperimentResultsSummary,
ExperimentVariantResult,
} from '~/api/api.server'
+import type { V2Filter } from '~/api/v2/types'
import { DOCS_URL } from '~/lib/constants'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import {
@@ -45,7 +45,6 @@ import Modal from '~/ui/Modal'
import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import routes from '~/utils/routes'
import ExperimentResults from './ExperimentResults'
@@ -118,7 +117,7 @@ interface ExperimentRowProps {
from: string
to: string
timezone?: string
- filters: AnalyticsFilter[]
+ filters: V2Filter[]
}
const normaliseProbability = (value: number) => {
@@ -167,7 +166,7 @@ const ExperimentWinningRail = ({
from: string
to: string
timezone?: string
- filters: AnalyticsFilter[]
+ filters: V2Filter[]
}) => {
const { t } = useTranslation()
const {
@@ -846,8 +845,6 @@ const ExperimentsView = ({
const { id } = useCurrentProject()
const { experimentsRefreshTrigger } = useRefreshTriggers()
const { filters, timeBucket } = useViewProjectContext()
- // experiments endpoints are still v1 β€” convert filters at the boundary
- const legacyFilters = useMemo(() => filters.map(v2FilterToLegacy), [filters])
const { t } = useTranslation()
const [searchParams, setSearchParams] = useSearchParams()
const listFetcher = useFetcher<ProjectViewActionData>()
@@ -1308,7 +1305,7 @@ const ExperimentsView = ({
from={from}
to={to}
timezone={timezone}
- filters={legacyFilters}
+ filters={filters}
/>
))}
</ul>
diff --git a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
index 39f559cb6..1738fde77 100644
--- a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
@@ -24,7 +24,7 @@ import Loader from '~/ui/Loader'
import Select from '~/ui/Select'
import { Text } from '~/ui/Text'
import type { V2Filter, V2FilterOperator } from '~/api/v2/types'
-import { legacyFilterToV2, v2FilterToLegacy } from '~/utils/analyticsUrl'
+import { ALL_VALID_DIMENSIONS, V1_TO_V2_DIMENSION } from '~/lib/v2Dimensions'
import FilterRowsEditor from '../../View/components/FilterRowsEditor'
const GOAL_TYPES = [
@@ -134,13 +134,11 @@ const filterToCondition = (filter: V2Filter): GoalCondition | null => {
}
}
- // goal conditions keep the legacy v1 column codes in `field`
- const { column } = v2FilterToLegacy(filter)
-
+ // goal conditions store the v2 dimension name directly in `field`
return {
id: createConditionId(),
eventType: filter.dimension === 'page' ? 'pageview' : 'any',
- field: column,
+ field: filter.dimension,
operator: filterToConditionOperator(filter.operator),
value,
}
@@ -185,15 +183,18 @@ const conditionToFilter = (condition: GoalCondition): V2Filter | null => {
const operator = conditionOperatorToV2Operator(condition.operator)
- // `field` holds a legacy v1 column code; unknown fields stay unmapped
- const converted = legacyFilterToV2({
- column: condition.field,
- filter: condition.value,
- isExclusive: operator === 'is_not' || operator === 'contains_not',
- isContains: operator === 'contains' || operator === 'contains_not',
- })
+ // `field` holds a v2 dimension name for goals saved after the v2 migration,
+ // or a legacy v1 short code for older goals β€” normalise both to the v2 name.
+ const dimension = V1_TO_V2_DIMENSION[condition.field] ?? condition.field
+ if (!ALL_VALID_DIMENSIONS.includes(dimension)) {
+ return null
+ }
- return converted
+ return {
+ dimension,
+ operator,
+ value: condition.value,
+ }
}
interface GoalSettingsModalProps {
diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
index bfcfda928..8194b1652 100644
--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
@@ -81,7 +81,6 @@ import ProgressRing from '~/ui/ProgressRing'
import StatusPage from '~/ui/StatusPage'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import { escapeHtml, nFormatter } from '~/utils/generic'
import countries from '~/utils/isoCountries'
import routes from '~/utils/routes'
@@ -954,8 +953,7 @@ const GoalsViewInner = ({
from,
to,
timezone,
- // goals endpoints are still v1 β€” convert filters at the boundary
- filters: filters.map(v2FilterToLegacy),
+ filters,
})
if (isMountedRef.current) {
setGoalStats((prev) => ({ ...prev, [goalId]: stats }))
@@ -984,8 +982,7 @@ const GoalsViewInner = ({
to,
timeBucket,
timezone,
- // goals endpoints are still v1 β€” convert filters at the boundary
- filters: filters.map(v2FilterToLegacy),
+ filters,
})
if (isMountedRef.current && result) {
setGoalChartData((prev) => ({ ...prev, [goalId]: result.chart }))
diff --git a/web/app/pages/Project/tabs/Journeys/JourneysView.tsx b/web/app/pages/Project/tabs/Journeys/JourneysView.tsx
index 997e00f55..ad2f42a0e 100644
--- a/web/app/pages/Project/tabs/Journeys/JourneysView.tsx
+++ b/web/app/pages/Project/tabs/Journeys/JourneysView.tsx
@@ -20,7 +20,6 @@ import { useTheme } from '~/providers/ThemeProvider'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import { Text } from '~/ui/Text'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import { SessionsDrawer } from '../Traffic/SessionsDrawer'
import { getFormatDate } from '../../View/ViewProject.helpers'
@@ -114,8 +113,7 @@ const JourneysView = ({ tnMapping }: JourneysViewProps) => {
try {
const result = await fetchJourneys(id, {
period,
- // the journeys endpoint is still v1 β€” convert filters at the boundary
- filters: filters.map(v2FilterToLegacy),
+ filters,
from,
to,
timezone,
diff --git a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
index 1a631c191..751d3657b 100644
--- a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
+++ b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
@@ -36,7 +36,6 @@ import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
import StatusPage from '~/ui/StatusPage'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import routes from '~/utils/routes'
import { LoaderView } from '../../View/components/LoaderView'
@@ -187,8 +186,7 @@ const ReplaysViewInner = ({
from,
to,
timezone,
- // the replays endpoint is still v1 β€” convert filters at the boundary
- filters: filters.map(v2FilterToLegacy),
+ filters,
take,
skip,
}
diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsx
index 5fed4ae5d..ecfb0087e 100644
--- a/web/app/pages/Project/tabs/SEO/SEOView.tsx
+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx
@@ -69,7 +69,6 @@ import {
SEO_METRICS,
type SEOMetricKey,
aggregateDateSeries,
- getGSCCompatibleFilters,
hasOrganicPositionData,
} from './seo-utils'
import type { QuadrantData } from './seo-chart-options'
@@ -254,7 +253,6 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
)
const noopFilterLink = useCallback(() => '#', [])
- const gscFilters = useMemo(() => getGSCCompatibleFilters(filters), [filters])
const gscLoading = isLoading || isCompareLoading
const gscError = error || compareError
@@ -275,7 +273,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
to,
timezone,
timeBucket: seoTimeBucket,
- filters: gscFilters,
+ filters,
}
const currentPromise = fetchDashboard(projectId, params)
@@ -309,7 +307,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
compareTo,
timezone,
seoTimeBucket,
- gscFilters,
+ filters,
isActiveCompare,
])
diff --git a/web/app/pages/Project/tabs/SEO/seo-utils.ts b/web/app/pages/Project/tabs/SEO/seo-utils.ts
index e1c3e6ce4..987e47625 100644
--- a/web/app/pages/Project/tabs/SEO/seo-utils.ts
+++ b/web/app/pages/Project/tabs/SEO/seo-utils.ts
@@ -1,8 +1,6 @@
import dayjs from 'dayjs'
import isoWeek from 'dayjs/plugin/isoWeek'
import quarterOfYear from 'dayjs/plugin/quarterOfYear'
-import type { V2Filter } from '~/api/v2/types'
-import { v2FilterToLegacy, type LegacyFilter } from '~/utils/analyticsUrl'
dayjs.extend(isoWeek)
dayjs.extend(quarterOfYear)
@@ -126,24 +124,6 @@ export const aggregateDateSeries = (
})
}
-// The GSC endpoints still consume the legacy v1 filter shape
-export const getGSCCompatibleFilters = (
- filters: V2Filter[],
-): LegacyFilter[] => {
- return filters.flatMap((filter) => {
- if (
- filter.dimension === 'page' ||
- filter.dimension === 'keywords' ||
- filter.dimension === 'country' ||
- filter.dimension === 'device'
- ) {
- return [v2FilterToLegacy(filter)]
- }
-
- return []
- })
-}
-
export const hasOrganicPositionData = (
series: OrganicPositionEntry[],
): boolean =>
diff --git a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx
index fa87a8a1e..8dc1a8c38 100644
--- a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx
+++ b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx
@@ -27,7 +27,6 @@ import { Link } from '~/ui/Link'
import { Text } from '~/ui/Text'
import Flag from '~/ui/Flag'
import { useTheme } from '~/providers/ThemeProvider'
-import { v2FilterToLegacy } from '~/utils/analyticsUrl'
import { getRelativeDateIfPossible } from '~/utils/date'
import { Session } from '../Sessions/Sessions'
@@ -308,8 +307,7 @@ export const SessionsDrawer = ({
timezone,
step: journeyStep,
page: journeyPage,
- // the journey-sessions endpoint is still v1 β€” convert at the boundary
- filters: stableFilters.map(v2FilterToLegacy),
+ filters: stableFilters,
take: SESSIONS_TAKE,
skip: currentSkip,
},
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index 1fc23b09a..42ae49933 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -32,7 +32,6 @@ import {
getRevenueDataServer,
getOverallStatsServer,
type AnalyticsParams,
- type AnalyticsFilter,
type SessionReplaysResponse,
type SessionReplayResponse,
type DeleteSessionReplayResponse,
@@ -60,6 +59,7 @@ import {
type OverallObject,
type DataDeletionPreview,
} from '~/api/api.server'
+import type { V2Filter } from '~/api/v2/types'
import { getProjectPasswordCookie } from '~/utils/session.server'
function formatDateForBackend(dateStr: string | undefined): string | undefined {
@@ -119,7 +119,7 @@ interface ProxyRequest {
from?: string
to?: string
timezone?: string
- filters?: AnalyticsFilter[]
+ filters?: V2Filter[]
take?: number
skip?: number
resultFilter?: string
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index 7ae93b220..521980141 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -20,7 +20,7 @@ import {
type FeatureFlagsResponse,
type GoalsResponse,
} from '~/api/api.server'
-import { parseFiltersFromUrl, v2FilterToLegacy } from '~/utils/analyticsUrl'
+import { parseFiltersFromUrl } from '~/utils/analyticsUrl'
import { useRequiredParams } from '~/hooks/useRequiredParams'
import {
DEFAULT_TIMEZONE,
@@ -498,8 +498,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const from = formatDateForBackend(url.searchParams.get('from') || '')
const to = formatDateForBackend(url.searchParams.get('to') || '')
const timezone = url.searchParams.get('timezone') || userTimezone
- // v1 endpoints still consume the legacy filter shape
- const filters = parseFiltersFromUrl(url.searchParams).map(v2FilterToLegacy)
+ const filters = parseFiltersFromUrl(url.searchParams)
// Ensure the time bucket is valid for the selected period and date range
const timeBucket = getValidTimeBucket(period, urlTimeBucket, from, to)
@@ -589,7 +588,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
'get-project-views',
'get-annotations',
'get-funnels',
- 'get-funnel-data',
'get-project-goals',
'get-goal',
'get-goal-stats',
@@ -2203,45 +2201,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
}
- case 'get-funnel-data': {
- const period = formData.get('period')?.toString() || ''
- const fromDate = formData.get('from')?.toString() || ''
- const toDate = formData.get('to')?.toString() || ''
- const tz = formData.get('timezone')?.toString() || ''
- const funnelId = formData.get('funnelId')?.toString() || ''
- const filters = formData.get('filters')?.toString() || '[]'
- const password = getPassword()
-
- const params = new URLSearchParams({ pid: projectId || '' })
- if (period) params.append('period', period)
- if (fromDate) params.append('from', fromDate)
- if (toDate) params.append('to', toDate)
- if (tz) params.append('timezone', tz)
- if (funnelId) params.append('funnelId', funnelId)
- params.append('filters', filters)
-
- const result = await serverFetch(
- request,
- `log/funnel?${params.toString()}`,
- {
- method: 'GET',
- headers: password ? { 'x-password': password } : undefined,
- },
- )
-
- if (result.error) {
- return data<ProjectViewActionData>(
- { intent, error: result.error as string },
- { status: 400 },
- )
- }
-
- return data<ProjectViewActionData>(
- { intent, success: true, data: result.data },
- { headers: createHeadersWithCookies(result.cookies) },
- )
- }
-
// Alerts (getters)
case 'get-project-alerts': {
const take = Number(formData.get('take') || '25')
diff --git a/web/app/utils/analyticsUrl.ts b/web/app/utils/analyticsUrl.ts
index 61ea5d909..94474fbe2 100644
--- a/web/app/utils/analyticsUrl.ts
+++ b/web/app/utils/analyticsUrl.ts
@@ -179,22 +179,3 @@ export const legacyFilterToV2 = (legacy: LegacyFilter): V2Filter | null => {
...(key ? { key } : {}),
}
}
-
-export const v2FilterToLegacy = (filter: V2Filter): LegacyFilter => {
- const column = filter.key
- ? filter.dimension === 'event_metadata'
- ? `ev:key:${filter.key}`
- : `tag:key:${filter.key}`
- : (Object.entries(V1_TO_V2_DIMENSION).find(
- ([, v2]) => v2 === filter.dimension,
- )?.[0] ?? filter.dimension)
-
- return {
- column,
- filter: filterToUrlValue(filter),
- isExclusive:
- filter.operator === 'is_not' || filter.operator === 'contains_not',
- isContains:
- filter.operator === 'contains' || filter.operator === 'contains_not',
- }
-}