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!

simplify

Blue Mouse4970c6dda59c
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index c7e01e932..0f440424c 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -1116,12 +1116,7 @@ export class AnalyticsController {
errorDTO.profileId,
)
- await this.analyticsService.recordSession(
- psid,
- errorDTO.pid,
- profileId,
- false,
- )
+ await this.analyticsService.recordSession(psid, errorDTO.pid, profileId)
const { city, region, regionCode, country } = getGeoDetails(ip, errorDTO.tz)
@@ -1256,12 +1251,7 @@ export class AnalyticsController {
eventsDTO.profileId,
)
- await this.analyticsService.recordSession(
- psid,
- eventsDTO.pid,
- profileId,
- false,
- )
+ await this.analyticsService.recordSession(psid, eventsDTO.pid, profileId)
const transformed = customEventTransformer(
psid,
@@ -1380,7 +1370,7 @@ export class AnalyticsController {
logDTO.profileId,
)
- await this.analyticsService.recordSession(psid, logDTO.pid, profileId, true)
+ await this.analyticsService.recordSession(psid, logDTO.pid, profileId)
if (!unique && logDTO.unique) {
throw new ForbiddenException(
@@ -1521,7 +1511,7 @@ export class AnalyticsController {
ip,
)
- await this.analyticsService.recordSession(psid, logDTO.pid, profileId, true)
+ await this.analyticsService.recordSession(psid, logDTO.pid, profileId)
const { city, region, regionCode, country } = getGeoDetails(ip)
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index b930b3501..dcd8b1c08 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -1222,11 +1222,31 @@ export class AnalyticsService {
psid: string,
pid: string,
profileId: string,
- isPageview: boolean = true,
): Promise<void> {
const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
try {
+ const query = `
+ SELECT firstSeen
+ FROM sessions FINAL
+ WHERE psid = {psid:UInt64}
+ AND pid = {pid:FixedString(12)}
+ LIMIT 1
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { psid, pid },
+ })
+ .then(resultSet =>
+ resultSet.json<{
+ firstSeen: string
+ }>(),
+ )
+
+ const existingSession = data[0]
+
await clickhouse.insert({
table: 'sessions',
format: 'JSONEachRow',
@@ -1235,10 +1255,8 @@ export class AnalyticsService {
psid,
pid,
profileId,
- firstSeen: now,
+ firstSeen: existingSession?.firstSeen ?? now,
lastSeen: now,
- pageviews: isPageview ? 1 : 0,
- events: isPageview ? 0 : 1,
},
],
clickhouse_settings: { async_insert: 1 },
@@ -1256,7 +1274,6 @@ export class AnalyticsService {
const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
try {
- // Read current session data to preserve pageviews/events counts
// TODO: Potentially slow because every write request reads from the database - consider caching or other optimisation
const query = `
SELECT firstSeen, pageviews, events
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index ba34d0ecc..cc4ffc843 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -923,12 +923,7 @@ export class AnalyticsController {
eventsDTO.profileId,
)
- await this.analyticsService.recordSession(
- psid,
- eventsDTO.pid,
- profileId,
- false,
- )
+ await this.analyticsService.recordSession(psid, eventsDTO.pid, profileId)
const transformed = customEventTransformer(
psid,
@@ -1046,7 +1041,7 @@ export class AnalyticsController {
logDTO.profileId,
)
- await this.analyticsService.recordSession(psid, logDTO.pid, profileId, true)
+ await this.analyticsService.recordSession(psid, logDTO.pid, profileId)
if (unique && logDTO.unique) {
throw new ForbiddenException(
@@ -1188,7 +1183,7 @@ export class AnalyticsController {
ip,
)
- await this.analyticsService.recordSession(psid, logDTO.pid, profileId, true)
+ await this.analyticsService.recordSession(psid, logDTO.pid, profileId)
const { city, region, regionCode, country } = getGeoDetails(ip, null)
@@ -1491,12 +1486,7 @@ export class AnalyticsController {
errorDTO.profileId,
)
- await this.analyticsService.recordSession(
- psid,
- errorDTO.pid,
- profileId,
- false,
- )
+ await this.analyticsService.recordSession(psid, errorDTO.pid, profileId)
const { city, region, regionCode, country } = getGeoDetails(ip, errorDTO.tz)
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index d3295f106..708830575 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -1235,11 +1235,31 @@ export class AnalyticsService {
psid: string,
pid: string,
profileId: string,
- isPageview: boolean = true,
): Promise<void> {
const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
try {
+ const query = `
+ SELECT firstSeen
+ FROM sessions FINAL
+ WHERE psid = {psid:UInt64}
+ AND pid = {pid:FixedString(12)}
+ LIMIT 1
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { psid, pid },
+ })
+ .then(resultSet =>
+ resultSet.json<{
+ firstSeen: string
+ }>(),
+ )
+
+ const existingSession = data[0]
+
await clickhouse.insert({
table: 'sessions',
format: 'JSONEachRow',
@@ -1248,10 +1268,8 @@ export class AnalyticsService {
psid,
pid,
profileId,
- firstSeen: now,
+ firstSeen: existingSession?.firstSeen ?? now,
lastSeen: now,
- pageviews: isPageview ? 1 : 0,
- events: isPageview ? 0 : 1,
},
],
clickhouse_settings: { async_insert: 1 },
@@ -1270,10 +1288,9 @@ export class AnalyticsService {
const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
try {
- // Read current session data to preserve pageviews/events counts
// TODO: Potentially slow because every write request reads from the database - consider caching or other optimisation
const query = `
- SELECT firstSeen, pageviews, events
+ SELECT firstSeen
FROM sessions FINAL
WHERE psid = {psid:UInt64}
AND pid = {pid:FixedString(12)}
@@ -1288,8 +1305,6 @@ export class AnalyticsService {
.then(resultSet =>
resultSet.json<{
firstSeen: string
- pageviews: number
- events: number
}>(),
)
@@ -1305,8 +1320,6 @@ export class AnalyticsService {
profileId,
firstSeen: existingSession?.firstSeen ?? now,
lastSeen: now,
- pageviews: existingSession?.pageviews ?? 0,
- events: existingSession?.events ?? 0,
},
],
clickhouse_settings: { async_insert: 1 },
diff --git a/backend/migrations/clickhouse/2025_12_02_profile_id.js b/backend/migrations/clickhouse/2025_12_02_profile_id.js
index 16512f006..9cfed73ad 100644
--- a/backend/migrations/clickhouse/2025_12_02_profile_id.js
+++ b/backend/migrations/clickhouse/2025_12_02_profile_id.js
@@ -1,16 +1,10 @@
const { queriesRunner, dbName } = require('./setup')
const queries = [
- // Add profileId column to analytics table
`ALTER TABLE ${dbName}.analytics ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
-
- // Add profileId column to customEV table
`ALTER TABLE ${dbName}.customEV ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
-
- // Add profileId column to errors table
`ALTER TABLE ${dbName}.errors ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
- // Create sessions table with ReplacingMergeTree for tracking session state
// ReplacingMergeTree automatically keeps the latest row by lastSeen for each (pid, psid) pair
`CREATE TABLE IF NOT EXISTS ${dbName}.sessions
(
@@ -18,27 +12,19 @@ const queries = [
pid FixedString(12),
profileId Nullable(String),
firstSeen DateTime('UTC'),
- lastSeen DateTime('UTC'),
- pageviews UInt32 DEFAULT 1,
- events UInt32 DEFAULT 0
+ lastSeen DateTime('UTC')
)
ENGINE = ReplacingMergeTree(lastSeen)
ORDER BY (pid, psid)
PARTITION BY toYYYYMM(firstSeen);`,
- // Migrate data from old session_durations table to new sessions table
- // Join with analytics to get actual timestamps - use MAX(created) as lastSeen
- // Compute firstSeen by subtracting duration from lastSeen
- // profileId is null for historical data (will be populated on new events)
- `INSERT INTO ${dbName}.sessions (psid, pid, profileId, firstSeen, lastSeen, pageviews, events)
+ `INSERT INTO ${dbName}.sessions (psid, pid, profileId, firstSeen, lastSeen)
SELECT
sd.psid,
sd.pid,
NULL as profileId,
subtractSeconds(COALESCE(a.last_seen, now()), sd.duration) as firstSeen,
- COALESCE(a.last_seen, now()) as lastSeen,
- 1 as pageviews,
- 0 as events
+ COALESCE(a.last_seen, now()) as lastSeen
FROM ${dbName}.session_durations sd
LEFT JOIN (
SELECT pid, psid, MAX(created) as last_seen
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 6720b5df1..d37b03369 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -4028,7 +4028,9 @@ const ViewProjectContent = () => {
</Link>
<RefreshStatsButton onRefresh={refreshStats} />
</div>
- {activeSession?.details ? <SessionDetails details={activeSession?.details} /> : null}
+ {activeSession?.details ? (
+ <SessionDetails details={activeSession?.details} pages={activeSession?.pages} />
+ ) : null}
{!_isEmpty(activeSession?.chart) ? (
<div className='relative'>
<SessionChart
diff --git a/web/app/pages/Project/View/components/SessionDetails.tsx b/web/app/pages/Project/View/components/SessionDetails.tsx
index 7f563be39..79946002b 100644
--- a/web/app/pages/Project/View/components/SessionDetails.tsx
+++ b/web/app/pages/Project/View/components/SessionDetails.tsx
@@ -1,7 +1,10 @@
import cx from 'clsx'
+import dayjs from 'dayjs'
import _capitalize from 'lodash/capitalize'
+import _isEmpty from 'lodash/isEmpty'
import _size from 'lodash/size'
import _truncate from 'lodash/truncate'
+import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { SessionDetails as Details } from '~/lib/models/Project'
@@ -10,16 +13,45 @@ import { getLocaleDisplayName, getStringFromTime, getTimeFromSeconds } from '~/u
import CCRow from './CCRow'
import { MetricCard, MetricCardSelect } from './MetricCards'
+interface PageflowItem {
+ type: 'pageview' | 'event' | 'error'
+ value: string
+ created: string
+}
+
interface SessionDetailsProps {
details: Details
+ pages?: PageflowItem[]
}
-export const SessionDetails = ({ details }: SessionDetailsProps) => {
+export const SessionDetails = ({ details, pages }: SessionDetailsProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
+ // Calculate session duration from pages if sdur is 0 or not available
+ const sessionDuration = useMemo(() => {
+ if (details.sdur && details.sdur > 0) {
+ return details.sdur
+ }
+
+ // Fallback: calculate duration from pageview timestamps only (for consistency with session list)
+ if (!_isEmpty(pages)) {
+ const pageviews = pages!.filter((p) => p.type === 'pageview')
+ if (pageviews.length >= 1) {
+ const firstPageview = pageviews[0]
+ const lastPageview = pageviews[pageviews.length - 1]
+ const diffSeconds = dayjs(lastPageview.created).diff(dayjs(firstPageview.created), 'seconds')
+ if (diffSeconds > 0) {
+ return diffSeconds
+ }
+ }
+ }
+
+ return 0
+ }, [details.sdur, pages])
+
const geo = [
{
label: t('project.mapping.cc'),
@@ -186,8 +218,8 @@ export const SessionDetails = ({ details }: SessionDetailsProps) => {
<span className='mr-1.5 h-2.5 w-2.5 animate-pulse rounded-full bg-red-500' />
{t('dashboard.live').toUpperCase()}
</span>
- ) : details.sdur !== undefined ? (
- getStringFromTime(getTimeFromSeconds(details.sdur))
+ ) : sessionDuration > 0 ? (
+ getStringFromTime(getTimeFromSeconds(sessionDuration))
) : (
'N/A'
)