π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Fix PR review stuff
Blue Mouse2811bc5e8e3b
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.tsindex c107994c5..3be59f052 100644--- a/backend/apps/cloud/src/analytics/analytics.controller.ts+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts@@ -278,6 +278,7 @@ export class AnalyticsController {timezone = DEFAULT_TIMEZONE,mode = ChartRenderMode.PERIODICAL,metrics,+ includeConcurrency,} = dataawait this.analyticsService.checkProjectAccess(@@ -385,6 +386,7 @@ export class AnalyticsController {customEVFilterApplied,appliedFilters,mode,+ includeConcurrency === 'true',)}@@ -799,6 +801,7 @@ export class AnalyticsController {filters,timezone = DEFAULT_TIMEZONE,mode = ChartRenderMode.PERIODICAL,+ includeConcurrency,} = dataconst [filtersQuery, filtersParams, appliedFilters, customEVFilterApplied] =@@ -841,6 +844,7 @@ export class AnalyticsController {safeTimezone,customEVFilterApplied,mode,+ includeConcurrency === 'true',)return { ...result, appliedFilters }diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 78112af9a..bc67c40ac 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -139,6 +139,9 @@ const isValidLocale = (lc: string): boolean => {// 2 minutesconst LIVE_SESSION_THRESHOLD_SECONDS = 120+// The concurrency sweep materializes one row per minute of the requested window,+// so cap how far back it can be reconstructed to keep the query bounded+const MAX_CONCURRENCY_WINDOW_MINUTES = 366 * 24 * 60const MAX_FILTERS = 100const MAX_FILTER_VALUES = 100@@ -5516,6 +5519,7 @@ export class AnalyticsService {customEVFilterApplied: boolean,parsedFilters: Array<{ [key: string]: string }>,mode: ChartRenderMode,+ includeConcurrency = false,): Promise<object | void> {let params: unknown = {}let chart: unknown = {}@@ -5542,6 +5546,7 @@ export class AnalyticsService {safeTimezone,customEVFilterApplied,mode,+ includeConcurrency,)// @ts-ignore@@ -5694,7 +5699,7 @@ export class AnalyticsService {FROM session_intervalsUNION ALLSELECT fromMinute + toIntervalMinute(number) AS m, toInt32(0) AS delta- FROM numbers(toUInt64(dateDiff('minute', fromMinute, toMinute)) + 1)+ FROM numbers(least(toUInt64(dateDiff('minute', fromMinute, toMinute)) + 1, ${MAX_CONCURRENCY_WINDOW_MINUTES})))GROUP BY m)@@ -5733,6 +5738,7 @@ export class AnalyticsService {safeTimezone: string,customEVFilterApplied: boolean,mode: ChartRenderMode,+ includeConcurrency = false,): Promise<object | void> {const { xShifted } = this.generateXAxis(timeBucket, from, to, safeTimezone)@@ -5743,9 +5749,17 @@ export class AnalyticsService {customEVFilterApplied,)- // The sessions table has no dimension columns, so concurrency cannot respect- // dashboard filters β return zeros instead of misleading unfiltered data- const shouldComputeConcurrency = !customEVFilterApplied && !filtersQuery+ // Concurrency is only computed when explicitly requested (the live visitors+ // metric is off by default) and within a bounded window β the sweep-line+ // query materializes a row per minute. The sessions table also has no+ // dimension columns, so concurrency cannot respect dashboard filters β+ // return zeros instead of misleading unfiltered data+ const shouldComputeConcurrency =+ includeConcurrency &&+ !customEVFilterApplied &&+ !filtersQuery &&+ dayjs.utc(to).diff(dayjs.utc(from), 'minute') <=+ MAX_CONCURRENCY_WINDOW_MINUTESconst [{ data }, concurrency] = await Promise.all([clickhousediff --git a/backend/apps/cloud/src/analytics/dto/getData.dto.ts b/backend/apps/cloud/src/analytics/dto/getData.dto.tsindex 176fa6e69..5881c0c9e 100644--- a/backend/apps/cloud/src/analytics/dto/getData.dto.ts+++ b/backend/apps/cloud/src/analytics/dto/getData.dto.ts@@ -68,4 +68,12 @@ export class GetDataDto {})@IsOptional()metrics?: string++ @ApiProperty({+ description:+ "Set to 'true' to include the live visitors (concurrency) series in the chart response",+ required: false,+ })+ @IsOptional()+ includeConcurrency?: string}diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.tsindex ca82cbaa2..89d7e51c4 100644--- a/backend/apps/community/src/analytics/analytics.controller.ts+++ b/backend/apps/community/src/analytics/analytics.controller.ts@@ -240,6 +240,7 @@ export class AnalyticsController {timezone = DEFAULT_TIMEZONE,mode = ChartRenderMode.PERIODICAL,metrics,+ includeConcurrency,} = dataawait this.analyticsService.checkProjectAccess(@@ -342,6 +343,7 @@ export class AnalyticsController {customEVFilterApplied,parsedFilters,mode,+ includeConcurrency === 'true',)}@@ -705,6 +707,7 @@ export class AnalyticsController {filters,timezone = DEFAULT_TIMEZONE,mode = ChartRenderMode.PERIODICAL,+ includeConcurrency,} = dataconst [filtersQuery, filtersParams, parsedFilters, customEVFilterApplied] =@@ -737,6 +740,7 @@ export class AnalyticsController {safeTimezone,customEVFilterApplied,mode,+ includeConcurrency === 'true',)return { ...result, appliedFilters: parsedFilters }diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex c7e708d97..1ac033801 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -122,6 +122,9 @@ const isValidLocale = (lc: string): boolean => {// 2 minutesconst LIVE_SESSION_THRESHOLD_SECONDS = 120+// The concurrency sweep materializes one row per minute of the requested window,+// so cap how far back it can be reconstructed to keep the query bounded+const MAX_CONCURRENCY_WINDOW_MINUTES = 366 * 24 * 60const MAX_FILTERS = 100const MAX_FILTER_VALUES = 100@@ -4064,6 +4067,7 @@ export class AnalyticsService {customEVFilterApplied: boolean,parsedFilters: Array<{ [key: string]: string }>,mode: ChartRenderMode,+ includeConcurrency = false,): Promise<object | void> {let params: unknown = {}let chart: unknown = {}@@ -4090,6 +4094,7 @@ export class AnalyticsService {safeTimezone,customEVFilterApplied,mode,+ includeConcurrency,)// @ts-ignore@@ -4242,7 +4247,7 @@ export class AnalyticsService {FROM session_intervalsUNION ALLSELECT fromMinute + toIntervalMinute(number) AS m, toInt32(0) AS delta- FROM numbers(toUInt64(dateDiff('minute', fromMinute, toMinute)) + 1)+ FROM numbers(least(toUInt64(dateDiff('minute', fromMinute, toMinute)) + 1, ${MAX_CONCURRENCY_WINDOW_MINUTES})))GROUP BY m)@@ -4281,6 +4286,7 @@ export class AnalyticsService {safeTimezone: string,customEVFilterApplied: boolean,mode: ChartRenderMode,+ includeConcurrency = false,): Promise<object | void> {const { xShifted } = this.generateXAxis(timeBucket, from, to, safeTimezone)@@ -4291,9 +4297,17 @@ export class AnalyticsService {customEVFilterApplied,)- // The sessions table has no dimension columns, so concurrency cannot respect- // dashboard filters β return zeros instead of misleading unfiltered data- const shouldComputeConcurrency = !customEVFilterApplied && !filtersQuery+ // Concurrency is only computed when explicitly requested (the live visitors+ // metric is off by default) and within a bounded window β the sweep-line+ // query materializes a row per minute. The sessions table also has no+ // dimension columns, so concurrency cannot respect dashboard filters β+ // return zeros instead of misleading unfiltered data+ const shouldComputeConcurrency =+ includeConcurrency &&+ !customEVFilterApplied &&+ !filtersQuery &&+ dayjs.utc(to).diff(dayjs.utc(from), 'minute') <=+ MAX_CONCURRENCY_WINDOW_MINUTESconst [{ data }, concurrency] = await Promise.all([clickhousediff --git a/backend/apps/community/src/analytics/dto/getData.dto.ts b/backend/apps/community/src/analytics/dto/getData.dto.tsindex 176fa6e69..5881c0c9e 100644--- a/backend/apps/community/src/analytics/dto/getData.dto.ts+++ b/backend/apps/community/src/analytics/dto/getData.dto.ts@@ -68,4 +68,12 @@ export class GetDataDto {})@IsOptional()metrics?: string++ @ApiProperty({+ description:+ "Set to 'true' to include the live visitors (concurrency) series in the chart response",+ required: false,+ })+ @IsOptional()+ includeConcurrency?: string}diff --git a/docs/content/docs/analytics-dashboard/live-visitors.mdx b/docs/content/docs/analytics-dashboard/live-visitors.mdxindex e9aa16c25..988561429 100644--- a/docs/content/docs/analytics-dashboard/live-visitors.mdx+++ b/docs/content/docs/analytics-dashboard/live-visitors.mdx@@ -16,7 +16,7 @@ In the top right corner of your dashboard (and on the main Traffic overview), yo## Live Visitors Over Time-The live counter tells you what's happening right now, but you can also chart concurrency historically. Unlike unique visitors (which only count when a session starts), this metric shows how many people were using your site *at the same time* β so you can spot peak load, quiet hours, and how long people actually stay around.+The live counter tells you what's happening right now, but you can also chart concurrency historically. Unlike unique visitors (which only count when a session starts), this metric shows how many people were using your site _at the same time_ β so you can spot peak load, quiet hours, and how long people actually stay around.To enable it:@@ -32,7 +32,7 @@ How to read the chart:A visitor counts as active from their first pageview until their last recorded activity (pageviews, custom events, or the tracking script's periodic heartbeats), so the chart also works for single-page apps where people stay on one page for a long time.:::info-Live visitors can't be combined with dashboard filters (country, page, browser, etc.), as concurrency is reconstructed from session activity that carries no dimension data. The metric toggle is disabled while filters are applied.+Live visitors can't be combined with dashboard filters (country, page, browser, etc.), as concurrency is reconstructed from session activity that carries no dimension data. The metric toggle is disabled while filters are applied. The chart is also limited to time ranges of up to a year β for longer ranges it shows zeros.:::## Live Visitors in Browser Titlediff --git a/docs/content/docs/api/stats.mdx b/docs/content/docs/api/stats.mdxindex 0fe0cc352..1d9dc8fef 100644--- a/docs/content/docs/api/stats.mdx+++ b/docs/content/docs/api/stats.mdx@@ -276,7 +276,7 @@ curl 'https://api.swetrix.com/v1/log?pid=YOUR_PROJECT_ID&timeBucket=day&period=7```:::info-`chart.concurrency` is the number of live (concurrent) visitors over time, reconstructed from session activity. For the `minute` time bucket it's the exact number of visitors active during that minute; for larger buckets it's the peak concurrency within the bucket. When `filters` are applied, this array is zero-filled, as concurrency cannot be segmented by dimensions.+`chart.concurrency` is the number of live (concurrent) visitors over time, reconstructed from session activity. It is only computed when the request sets `includeConcurrency=true`; otherwise the array is zero-filled. For the `minute` time bucket it's the exact number of visitors active during that minute; for larger buckets it's the peak concurrency within the bucket. When `filters` are applied (or the requested time range is longer than a year), this array is zero-filled, as concurrency cannot be segmented by dimensions.:::#### Parameters@@ -349,6 +349,12 @@ The `meta` is an array of objects like:<hr />+**includeConcurrency**++Set to `true` to include the `chart.concurrency` (live visitors over time) series in the response. Reconstructing concurrency from session intervals is relatively expensive, so it's skipped unless explicitly requested.++<hr />+### GET /v1/log/performanceThis endpoint accepts the same parameters as the [`/log` endpoint](#get-v1log).diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 2bf923386..bbcfadc02 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -783,6 +783,8 @@ export interface AnalyticsParams {mode?: 'periodical' | 'cumulative'password?: stringmetrics?: string+ // Concurrency (live visitors) data is only computed by the API when requested+ includeConcurrency?: boolean}function serializeFiltersForUrl(filters: AnalyticsFilter[]): string {@@ -804,6 +806,9 @@ export async function getProjectDataServer(if (params.timezone) queryParams.append('timezone', params.timezone)if (params.mode) queryParams.append('mode', params.mode)if (params.metrics) queryParams.append('metrics', params.metrics)+ if (params.includeConcurrency) {+ queryParams.append('includeConcurrency', 'true')+ }const headers: Record<string, string> = {}if (params.password) {diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex a246de679..3a4707cb8 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -784,8 +784,10 @@ const getSettings = (trendlineTotal: '#eba14b',sessionDuration: '#c945ed',sessionDurationCompare: 'rgba(201, 69, 237, 0.4)',- liveVisitors: '#16A34A',- liveVisitorsCompare: 'rgba(22, 163, 74, 0.4)',+ // Distinct from every CUSTOM_EVENTS_CHART_COLORS entry so the legend+ // stays unambiguous when both series are shown+ liveVisitors: '#10B981',+ liveVisitorsCompare: 'rgba(16, 185, 129, 0.4)',revenue: '#ea580c', // orange-600 for net revenuerefundsAmount: 'rgba(234, 88, 12, 0.25)', // light orange fill for refunds overlay...customEventsColors,diff --git a/web/app/pages/Project/View/interfaces/traffic.ts b/web/app/pages/Project/View/interfaces/traffic.tsindex ce630b6dc..309284007 100644--- a/web/app/pages/Project/View/interfaces/traffic.ts+++ b/web/app/pages/Project/View/interfaces/traffic.ts@@ -60,6 +60,7 @@ export interface TrafficLogResponse {uniques: number[]sdur: number[]bounces?: number[]+ concurrency?: number[]}customs: Customsproperties: Propertiesdiff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsxindex cfe68d217..e661eb6ba 100644--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx@@ -411,11 +411,10 @@ const TrafficViewInner = ({const isPanelsDataEmpty = isPanelsDataEmptyRaw && !hasShownContentRef.current// Chart metrics state- const [activeChartMetrics, setActiveChartMetrics] = useState({+ const [activeChartMetricsState, setActiveChartMetrics] = useState({[CHART_METRICS_MAPPING.unique]: true,[CHART_METRICS_MAPPING.views]: false,[CHART_METRICS_MAPPING.sessionDuration]: false,- [CHART_METRICS_MAPPING.liveVisitors]: false,[CHART_METRICS_MAPPING.bounce]: false,[CHART_METRICS_MAPPING.viewsPerUnique]: false,[CHART_METRICS_MAPPING.trendlines]: false,@@ -423,6 +422,17 @@ const TrafficViewInner = ({[CHART_METRICS_MAPPING.customEvents]: false,[CHART_METRICS_MAPPING.revenue]: false,})++ // Live visitors is URL-driven (like custom events) so the route loader knows+ // to request concurrency data from the API β it is only computed on demand+ const activeChartMetrics = useMemo(+ () => ({+ ...activeChartMetricsState,+ [CHART_METRICS_MAPPING.liveVisitors]:+ searchParams.get('liveVisitors') === 'true',+ }),+ [activeChartMetricsState, searchParams],+ )// Get custom events from URL params (SSR-friendly)const activeChartMetricsCustomEvents = useMemo(() => {const param = searchParams.get('customEvents')@@ -673,25 +683,32 @@ const TrafficViewInner = ({return}+ if (pairID === CHART_METRICS_MAPPING.liveVisitors) {+ const newParams = new URLSearchParams(searchParams.toString())+ if (newParams.get('liveVisitors') === 'true') {+ newParams.delete('liveVisitors')+ } else {+ newParams.set('liveVisitors', 'true')+ }+ setSearchParams(newParams)+ return+ }+setActiveChartMetrics((prev) => ({...prev,[pairID]: !prev[pairID as keyof typeof prev],}))},- [isConflicted, t],+ [isConflicted, t, searchParams, setSearchParams],)// Live visitors cannot be filtered β turn it off if a filter gets applied// while it's active (the toggle itself is disabled in that state)useEffect(() => {- if (- !_isEmpty(filters) &&- activeChartMetrics[CHART_METRICS_MAPPING.liveVisitors]- ) {- setActiveChartMetrics((prev) => ({- ...prev,- [CHART_METRICS_MAPPING.liveVisitors]: false,- }))+ if (!_isEmpty(filters) && searchParams.get('liveVisitors') === 'true') {+ const newParams = new URLSearchParams(searchParams.toString())+ newParams.delete('liveVisitors')+ setSearchParams(newParams)}// eslint-disable-next-line react-hooks/exhaustive-deps}, [filters])diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsxindex 00790f9f2..ed765d5f2 100644--- a/web/app/routes/projects.$id.tsx+++ b/web/app/routes/projects.$id.tsx@@ -608,6 +608,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// Segment custom metrics (JSON-encoded ProjectViewCustomEvent[])const metricsParam = url.searchParams.get('metrics') || undefined+ // Live visitors chart metric β concurrency data is only requested when enabled+ const liveVisitorsEnabled = url.searchParams.get('liveVisitors') === 'true'+const analyticsParams = {timeBucket,period,@@ -617,6 +620,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {timezone,password: password || undefined,metrics: metricsParam,+ includeConcurrency: liveVisitorsEnabled || undefined,}// Initialize deferred data promises