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!

Session replays tab

Blue Mouse5026267de761
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 1c00542f0..35f6765eb 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -76,6 +76,7 @@ import { GetSessionsDto } from './dto/get-sessions.dto'
import { GetSessionDto } from './dto/get-session.dto'
import {
GetSessionReplayDto,
+ GetSessionReplaysDto,
SessionReplayExportStartDto,
SessionReplayChunkDto,
SessionReplayStartDto,
@@ -2380,6 +2381,86 @@ export class AnalyticsController {
return { sessions, appliedFilters, take, skip }
}
+ @Get('session-replays')
+ @Auth(true, true)
+ async getSessionReplays(
+ @Query() data: GetSessionReplaysDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const { pid, period, from, to, filters, timezone = DEFAULT_TIMEZONE } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ const take = this.analyticsService.getSafeNumber(data.take, 30)
+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)
+
+ if (take > 150) {
+ throw new BadRequestException(
+ 'The maximum number of session replays to return is 150',
+ )
+ }
+
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, take: ${take}, skip: ${skip}`,
+ 'GET /analytics/session-replays',
+ )
+
+ const [filtersQuery, filtersParams, appliedFilters, customEVFilterApplied] =
+ this.analyticsService.getFiltersQuery(filters, DataType.ANALYTICS)
+
+ let timeBucket
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ ['pageview', 'custom_event', 'error'] as const,
+ )
+
+ timeBucket = res.timeBucket[0]
+ diff = res.diff
+ } else {
+ timeBucket = getLowestPossibleTimeBucket(period, from, to)
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const paramsData = {
+ params: {
+ pid,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ ...filtersParams,
+ },
+ }
+
+ const replays = await this.analyticsService.getSessionReplaysList(
+ filtersQuery,
+ paramsData,
+ safeTimezone,
+ take,
+ skip,
+ customEVFilterApplied,
+ )
+
+ return { replays, appliedFilters, take, skip }
+ }
+
@Get('errors')
@Auth(true, true)
async getErrors(
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index fa51b9448..6c34c6382 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -6316,6 +6316,238 @@ export class AnalyticsService {
return data
}
+ async getSessionReplaysList(
+ filtersQuery: string,
+ paramsData: any,
+ safeTimezone: string,
+ take = 30,
+ skip = 0,
+ customEVFilterApplied = false,
+ ): Promise<object[]> {
+ const primaryEventsSubquery = this.buildSessionsListPrimaryEventsSubquery(
+ filtersQuery,
+ customEVFilterApplied,
+ 'traffic',
+ )
+
+ const query = `
+ WITH filtered_sessions AS (
+ SELECT
+ psidCasted,
+ pid,
+ argMaxIf(profileId, created_for_grouping, profileId IS NOT NULL AND profileId != '') AS profileId,
+ any(cc) AS cc,
+ any(os) AS os,
+ any(br) AS br,
+ min(created_for_grouping) AS sessionStart,
+ max(created_for_grouping) AS lastActivity
+ FROM (${primaryEventsSubquery}) AS primary_events
+ GROUP BY psidCasted, pid
+ ),
+ replay_summary AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ replayId,
+ argMax(privacyMode, created) AS privacyMode,
+ count() AS chunkCount,
+ sum(eventCount) AS eventCount,
+ min(firstEventTimestamp) AS firstEventTimestamp,
+ max(lastEventTimestamp) AS lastEventTimestamp,
+ min(created) AS replayCreatedAt,
+ max(created) AS lastReplayCreatedAt,
+ max(expiresAt) AS replayExpiresAt
+ FROM session_replay_chunks
+ WHERE pid = {pid:FixedString(12)}
+ AND expiresAt > now()
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid, replayId
+ ),
+ pageview_counts AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ count() as count
+ FROM events
+ WHERE pid = {pid:FixedString(12)} AND type = 'pageview' AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid
+ ),
+ event_counts AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ count() as count
+ FROM events
+ WHERE pid = {pid:FixedString(12)} AND type = 'custom_event' AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid
+ ),
+ error_counts AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ count() as count
+ FROM events
+ WHERE pid = {pid:FixedString(12)} AND type = 'error' AND psid IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY psidCasted, pid
+ ),
+ revenue_totals AS (
+ SELECT
+ psidCasted,
+ pid,
+ sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) - sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END) as revenue,
+ sum(CASE WHEN type = 'refund' THEN abs(amount) ELSE 0 END) as refunds
+ FROM (
+ SELECT
+ CAST(session_id, 'String') AS psidCasted,
+ pid,
+ argMax(type, synced_at) AS type,
+ argMax(amount, synced_at) AS amount
+ FROM revenue
+ WHERE pid = {pid:FixedString(12)} AND session_id IS NOT NULL
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND revenue.type IN ('sale', 'refund')
+ GROUP BY psidCasted, pid, transaction_id
+ )
+ GROUP BY psidCasted, pid
+ ),
+ session_duration_agg AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,
+ argMax(profileId, lastSeen) as profileId
+ FROM sessions
+ WHERE pid = {pid:FixedString(12)}
+ GROUP BY psidCasted, pid
+ ),
+ replays_enriched AS (
+ SELECT
+ rs.psidCasted AS psidCasted,
+ rs.pid AS pid,
+ rs.replayId AS replayId,
+ rs.privacyMode AS privacyMode,
+ rs.chunkCount AS chunkCount,
+ rs.eventCount AS eventCount,
+ rs.firstEventTimestamp AS firstEventTimestamp,
+ rs.lastEventTimestamp AS lastEventTimestamp,
+ rs.replayCreatedAt AS replayCreatedAt,
+ rs.lastReplayCreatedAt AS lastReplayCreatedAt,
+ rs.replayExpiresAt AS replayExpiresAt,
+ fs.cc AS cc,
+ fs.os AS os,
+ fs.br AS br,
+ COALESCE(pc.count, 0) AS pageviews,
+ COALESCE(ec.count, 0) AS customEvents,
+ COALESCE(errc.count, 0) AS errors,
+ toFloat64(COALESCE(rt.revenue, toDecimal64(0, 4))) AS revenue,
+ toFloat64(COALESCE(rt.refunds, toDecimal64(0, 4))) AS refunds,
+ fs.sessionStart AS sessionStart,
+ fs.lastActivity AS lastActivity,
+ sda.avg_duration AS sdur,
+ coalesce(nullIf(sda.profileId, ''), fs.profileId) AS profileId
+ FROM replay_summary rs
+ INNER JOIN filtered_sessions fs ON rs.psidCasted = fs.psidCasted AND rs.pid = fs.pid
+ LEFT JOIN pageview_counts pc ON rs.psidCasted = pc.psidCasted AND rs.pid = pc.pid
+ LEFT JOIN event_counts ec ON rs.psidCasted = ec.psidCasted AND rs.pid = ec.pid
+ LEFT JOIN error_counts errc ON rs.psidCasted = errc.psidCasted AND rs.pid = errc.pid
+ LEFT JOIN revenue_totals rt ON rs.psidCasted = rt.psidCasted AND rs.pid = rt.pid
+ LEFT JOIN session_duration_agg sda ON rs.psidCasted = sda.psidCasted AND rs.pid = sda.pid
+ ),
+ first_session_per_profile AS (
+ SELECT
+ profileId,
+ argMin(CAST(psid, 'String'), firstSeen) AS firstPsid
+ FROM sessions FINAL
+ WHERE pid = {pid:FixedString(12)}
+ AND profileId IS NOT NULL
+ AND profileId != ''
+ GROUP BY profileId
+ )
+ SELECT
+ re.psidCasted AS psid,
+ re.replayId,
+ re.privacyMode,
+ re.chunkCount,
+ re.eventCount,
+ re.firstEventTimestamp,
+ re.lastEventTimestamp,
+ re.replayCreatedAt,
+ re.lastReplayCreatedAt,
+ re.replayExpiresAt,
+ re.cc,
+ re.os,
+ re.br,
+ re.pageviews,
+ re.customEvents,
+ re.errors,
+ re.revenue,
+ re.refunds,
+ re.sessionStart,
+ re.lastActivity,
+ if(dateDiff('second', re.lastActivity, now()) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,
+ re.sdur,
+ re.profileId AS profileId,
+ if(startsWith(ifNull(re.profileId, ''), '${AnalyticsService.PROFILE_PREFIX_USER}'), 1, 0) AS isIdentified,
+ if(
+ ifNull(re.profileId, '') = '',
+ 0,
+ if(isNull(fsp.firstPsid) OR fsp.firstPsid = '' OR fsp.firstPsid = re.psidCasted, 1, 0)
+ ) AS isFirstSession
+ FROM replays_enriched re
+ LEFT JOIN first_session_per_profile fsp ON re.profileId = fsp.profileId
+ ORDER BY re.lastReplayCreatedAt DESC, re.replayId DESC
+ LIMIT {take:UInt32}
+ OFFSET {skip:UInt32}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ ...paramsData.params,
+ timezone: safeTimezone,
+ take,
+ skip,
+ },
+ })
+ .then((resultSet) => resultSet.json<any>())
+
+ return data.map((row: any) => {
+ const firstTimestamp =
+ row.firstEventTimestamp === null ||
+ typeof row.firstEventTimestamp === 'undefined'
+ ? Number.NaN
+ : Number(row.firstEventTimestamp)
+ const lastTimestamp =
+ row.lastEventTimestamp === null ||
+ typeof row.lastEventTimestamp === 'undefined'
+ ? Number.NaN
+ : Number(row.lastEventTimestamp)
+ const sessionDuration = Number(row.sdur) || 0
+ const replayDuration =
+ Number.isFinite(firstTimestamp) &&
+ Number.isFinite(lastTimestamp) &&
+ lastTimestamp > firstTimestamp
+ ? Math.round((lastTimestamp - firstTimestamp) / 1000)
+ : sessionDuration
+
+ return {
+ ...row,
+ hasReplay: 1,
+ chunkCount: Number(row.chunkCount) || 0,
+ eventCount: Number(row.eventCount) || 0,
+ replayDuration,
+ replayStart:
+ Number.isFinite(firstTimestamp) && firstTimestamp > 0
+ ? dayjs.utc(firstTimestamp).format('YYYY-MM-DD HH:mm:ss')
+ : row.replayCreatedAt,
+ }
+ })
+ }
+
private buildSessionsListPrimaryEventsSubquery(
filtersQuery: string,
customEVFilterApplied: boolean,
diff --git a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
index 858c244f4..3a8989731 100644
--- a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
@@ -1,4 +1,4 @@
-import { ApiProperty } from '@nestjs/swagger'
+import { ApiProperty, PickType } from '@nestjs/swagger'
import {
ArrayMaxSize,
IsArray,
@@ -16,6 +16,7 @@ import {
import { Type } from 'class-transformer'
import { PID_REGEX } from '../../common/constants'
+import { GetDataDto } from './getData.dto'
const SESSION_REPLAY_PRIVACY_MODES = ['total', 'normal', 'free-love'] as const
@@ -88,4 +89,24 @@ export class GetSessionReplayDto {
replayId?: string
}
+export class GetSessionReplaysDto extends PickType(GetDataDto, [
+ 'pid',
+ 'period',
+ 'from',
+ 'to',
+ 'filters',
+ 'timezone',
+] as const) {
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ @Max(150)
+ take: number
+
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ skip: number
+}
+
export class SessionReplayExportStartDto extends GetSessionReplayDto {}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index a506d6aef..924769694 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -995,6 +995,27 @@ export interface SessionsResponse {
appliedFilters: AnalyticsFilter[]
}
+export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+
+export interface SessionReplayListItem extends Session {
+ replayId: string
+ privacyMode: SessionReplayPrivacy
+ chunkCount: number
+ eventCount: number
+ replayStart: string
+ replayCreatedAt: string
+ lastReplayCreatedAt: string
+ firstEventTimestamp?: number | string | null
+ lastEventTimestamp?: number | string | null
+}
+
+export interface SessionReplaysResponse {
+ replays: SessionReplayListItem[]
+ take: number
+ skip: number
+ appliedFilters: AnalyticsFilter[]
+}
+
export type SessionEventType = 'traffic' | 'performance' | 'error'
export async function getSessionsServer(
@@ -1033,6 +1054,38 @@ export async function getSessionsServer(
)
}
+export async function getSessionReplaysServer(
+ request: Request,
+ pid: string,
+ params: AnalyticsParams & {
+ take?: number
+ skip?: number
+ },
+): Promise<ServerFetchResult<SessionReplaysResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('period', params.period)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+ queryParams.append('take', String(params.take || 30))
+ queryParams.append('skip', String(params.skip || 0))
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<SessionReplaysResponse>(
+ request,
+ `log/session-replays?${queryParams.toString()}`,
+ {
+ headers,
+ },
+ )
+}
+
export interface FunnelSessionsResponse {
sessions: Session[]
take: number
@@ -1129,8 +1182,6 @@ interface PageflowItem {
currency?: string
}
-export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
-
export interface SessionReplayMetadata {
hasReplay: boolean
replayId: string
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index 39a6b60df..39a294c42 100644
--- a/web/app/hooks/useAnalyticsProxy.ts
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -2,6 +2,7 @@ import { useCallback, useRef, useState } from 'react'
import type {
SessionsResponse,
+ SessionReplaysResponse,
SessionReplayResponse,
SessionReplayExportResponse,
ErrorsResponse,
@@ -104,6 +105,38 @@ export function useSessionsProxy() {
return { fetchSessions, data, error, isLoading }
}
+export function useSessionReplaysProxy() {
+ const [data, setData] = useState<SessionReplaysResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchSessionReplays = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<SessionReplaysResponse>({
+ action: 'getSessionReplays',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
+
+ return { fetchSessionReplays, data, error, isLoading }
+}
+
export function useSessionReplayProxy() {
const [data, setData] = useState<SessionReplayResponse | null>(null)
const [error, setError] = useState<string | null>(null)
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 92bd4a747..0aa5b662f 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -561,6 +561,7 @@ const SELFHOSTED_PROJECT_TABS = {
funnels: 'funnels',
profiles: 'profiles',
sessions: 'sessions',
+ replays: 'replays',
errors: 'errors',
goals: 'goals',
experiments: 'experiments',
@@ -575,6 +576,7 @@ const PRODUCTION_PROJECT_TABS = {
profiles: 'profiles',
funnels: 'funnels',
sessions: 'sessions',
+ replays: 'replays',
errors: 'errors',
goals: 'goals',
experiments: 'experiments',
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index ddaeb7032..41e8f7e46 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -20,6 +20,7 @@ import {
FlaskIcon,
IdentificationCardIcon,
UserListIcon,
+ MonitorPlayIcon,
ToggleRightIcon,
MagnifyingGlassIcon,
} from '@phosphor-icons/react'
@@ -92,6 +93,7 @@ import FunnelsView from '../tabs/Funnels/FunnelsView'
import GoalsView from '../tabs/Goals/GoalsView'
import PerformanceView from '../tabs/Performance/PerformanceView'
import ProfilesView from '../tabs/Profiles/ProfilesView'
+import ReplaysView from '../tabs/Replays/ReplaysView'
import SessionsView from '../tabs/Sessions/SessionsView'
import SEOView from '../tabs/SEO/SEOView'
import TrafficView from '../tabs/Traffic/TrafficView'
@@ -196,6 +198,7 @@ interface RefreshTriggersContextType {
trafficRefreshTrigger: number
funnelsRefreshTrigger: number
profilesRefreshTrigger: number
+ replaysRefreshTrigger: number
seoRefreshTrigger: number
}
@@ -264,6 +267,7 @@ const defaultRefreshTriggersContext: RefreshTriggersContextType = {
trafficRefreshTrigger: 0,
funnelsRefreshTrigger: 0,
profilesRefreshTrigger: 0,
+ replaysRefreshTrigger: 0,
seoRefreshTrigger: 0,
}
@@ -352,6 +356,7 @@ const ViewProjectContent = () => {
const [trafficRefreshTrigger, setTrafficRefreshTrigger] = useState(0)
const [funnelsRefreshTrigger, setFunnelsRefreshTrigger] = useState(0)
const [profilesRefreshTrigger, setProfilesRefreshTrigger] = useState(0)
+ const [replaysRefreshTrigger, setReplaysRefreshTrigger] = useState(0)
const [seoRefreshTrigger, setSeoRefreshTrigger] = useState(0)
const [activeChartMetrics] = useState<
Record<keyof typeof CHART_METRICS_MAPPING, boolean>
@@ -765,6 +770,11 @@ const ViewProjectContent = () => {
label: t('dashboard.sessions'),
icon: UserListIcon,
},
+ {
+ id: PROJECT_TABS.replays,
+ label: t('dashboard.replays'),
+ icon: MonitorPlayIcon,
+ },
{
id: PROJECT_TABS.errors,
label: t('dashboard.errors'),
@@ -937,6 +947,11 @@ const ViewProjectContent = () => {
return
}
+ if (activeTab === PROJECT_TABS.replays) {
+ setReplaysRefreshTrigger((prev) => prev + 1)
+ return
+ }
+
if (activeTab === PROJECT_TABS.errors) {
setErrorsRefreshTrigger((prev) => prev + 1)
return
@@ -1298,6 +1313,7 @@ const ViewProjectContent = () => {
trafficRefreshTrigger,
funnelsRefreshTrigger,
profilesRefreshTrigger,
+ replaysRefreshTrigger,
seoRefreshTrigger,
}),
[
@@ -1311,6 +1327,7 @@ const ViewProjectContent = () => {
trafficRefreshTrigger,
funnelsRefreshTrigger,
profilesRefreshTrigger,
+ replaysRefreshTrigger,
seoRefreshTrigger,
],
)
@@ -1596,6 +1613,9 @@ const ViewProjectContent = () => {
rotateXAxis={rotateXAxis}
/>
) : null}
+ {activeTab === PROJECT_TABS.replays ? (
+ <ReplaysView tnMapping={tnMapping} />
+ ) : null}
{activeTab === PROJECT_TABS.errors ? (
<ErrorsView />
) : null}
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index 742691dc5..3f48ae512 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -69,6 +69,7 @@ const ICON_COLORS: Record<string, string> = {
// Product Analytics
profiles: 'text-fuchsia-500',
sessions: 'text-indigo-500',
+ replays: 'text-sky-500',
errors: 'text-red-500',
goals: 'text-purple-500',
experiments: 'text-pink-500',
@@ -439,6 +440,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
[
PROJECT_TABS.profiles,
PROJECT_TABS.sessions,
+ PROJECT_TABS.replays,
PROJECT_TABS.errors,
PROJECT_TABS.goals,
PROJECT_TABS.experiments,
diff --git a/web/app/pages/Project/View/utils/projectViewSegments.ts b/web/app/pages/Project/View/utils/projectViewSegments.ts
index e59f10999..b2ef79e9b 100644
--- a/web/app/pages/Project/View/utils/projectViewSegments.ts
+++ b/web/app/pages/Project/View/utils/projectViewSegments.ts
@@ -48,6 +48,7 @@ const SEO_FILTER_COLUMNS = ['pg', 'keywords', 'cc', 'dv']
const ANALYTICS_TABS = new Set<ProjectTab>([
PROJECT_TABS.traffic,
PROJECT_TABS.sessions,
+ PROJECT_TABS.replays,
PROJECT_TABS.profiles,
PROJECT_TABS.funnels,
PROJECT_TABS.goals,
@@ -59,6 +60,7 @@ const FILTER_OPTIONS_BY_TAB: Partial<Record<ProjectTab, string[]>> = {
[PROJECT_TABS.performance]: PERFORMANCE_FILTER_COLUMNS,
[PROJECT_TABS.seo]: ['pg', 'cc', 'dv'],
[PROJECT_TABS.sessions]: FILTERS_PANELS_ORDER,
+ [PROJECT_TABS.replays]: FILTERS_PANELS_ORDER,
[PROJECT_TABS.profiles]: FILTERS_PANELS_ORDER,
[PROJECT_TABS.funnels]: FILTERS_PANELS_ORDER,
[PROJECT_TABS.goals]: FILTERS_PANELS_ORDER,
diff --git a/web/app/pages/Project/tabs/Replays/NoReplays.tsx b/web/app/pages/Project/tabs/Replays/NoReplays.tsx
new file mode 100644
index 000000000..b6a0a750e
--- /dev/null
+++ b/web/app/pages/Project/tabs/Replays/NoReplays.tsx
@@ -0,0 +1,51 @@
+import { FunnelIcon, MonitorPlayIcon } from '@phosphor-icons/react'
+import _isEmpty from 'lodash/isEmpty'
+import { memo } from 'react'
+import { useTranslation } from 'react-i18next'
+
+import Filters from '~/pages/Project/View/components/Filters'
+import { Filter } from '~/pages/Project/View/interfaces/traffic'
+import { typeNameMapping } from '~/pages/Project/View/ViewProject.helpers'
+import { Text } from '~/ui/Text'
+
+interface NoReplaysProps {
+ filters: Filter[]
+}
+
+const NoReplays = ({ filters }: NoReplaysProps) => {
+ const { t } = useTranslation('common')
+ const tnMapping = typeNameMapping(t)
+ const hasFilters = !_isEmpty(filters)
+
+ return (
+ <>
+ {hasFilters ? <Filters tnMapping={tnMapping} /> : null}
+ <div className='mx-auto w-full max-w-2xl py-16 text-center'>
+ <div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-900'>
+ {hasFilters ? (
+ <FunnelIcon className='size-7 text-gray-700 dark:text-gray-200' />
+ ) : (
+ <MonitorPlayIcon className='size-7 text-gray-700 dark:text-gray-200' />
+ )}
+ </div>
+ <Text as='h3' size='xl' weight='medium' className='tracking-tight'>
+ {hasFilters
+ ? t('project.noReplaysFiltersTitle')
+ : t('project.noReplaysTitle')}
+ </Text>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
+ {hasFilters
+ ? t('project.noReplaysFiltersDesc')
+ : t('project.noReplaysContent')}
+ </Text>
+ </div>
+ </>
+ )
+}
+
+export default memo(NoReplays)
diff --git a/web/app/pages/Project/tabs/Replays/Replays.tsx b/web/app/pages/Project/tabs/Replays/Replays.tsx
new file mode 100644
index 000000000..dbcb4e0ea
--- /dev/null
+++ b/web/app/pages/Project/tabs/Replays/Replays.tsx
@@ -0,0 +1,444 @@
+import cx from 'clsx'
+import dayjs from 'dayjs'
+import duration from 'dayjs/plugin/duration'
+import relativeTime from 'dayjs/plugin/relativeTime'
+import utc from 'dayjs/plugin/utc'
+import _map from 'lodash/map'
+import {
+ CaretRightIcon,
+ CursorClickIcon,
+ FileTextIcon,
+ ListBulletsIcon,
+ MonitorPlayIcon,
+ PlayIcon,
+ UserIcon,
+ WarningIcon,
+} from '@phosphor-icons/react'
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useLocation } from 'react-router'
+
+import type { SessionReplayListItem } from '~/api/api.server'
+import Flag from '~/ui/Flag'
+import Button from '~/ui/Button'
+import { Text } from '~/ui/Text'
+import Tooltip from '~/ui/Tooltip'
+import { BrowserIcon, OSIcon } from '~/pages/Project/tabs/SharedIcons'
+import { PROJECT_TABS } from '~/lib/constants'
+import { useTheme } from '~/providers/ThemeProvider'
+import { getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
+import countries from '~/utils/isoCountries'
+import { getProfileDisplayName, ProfileAvatar } from '~/utils/profileAvatars'
+
+dayjs.extend(duration)
+dayjs.extend(relativeTime)
+dayjs.extend(utc)
+
+const CURRENCY_SYMBOLS: Record<string, string> = {
+ USD: '$',
+ EUR: '€',
+ GBP: '£',
+ CAD: 'CA$',
+ AUD: 'A$',
+}
+
+const getCurrencySymbol = (currency?: string) =>
+ CURRENCY_SYMBOLS[currency || 'USD'] || CURRENCY_SYMBOLS.USD
+
+interface ReplaysProps {
+ replays: SessionReplayListItem[]
+ timeFormat: '12-hour' | '24-hour'
+ timezone: string
+ currency?: string
+ onWatchReplay: (replay: SessionReplayListItem) => void
+}
+
+interface ReplayRowProps extends Omit<ReplaysProps, 'replays'> {
+ replay: SessionReplayListItem
+}
+
+const formatDate = (
+ value: string | null | undefined,
+ language: string,
+ timeFormat: '12-hour' | '24-hour',
+ timezone: string,
+) => {
+ if (!value) return null
+
+ const date = dayjs.utc(value)
+ if (!date.isValid()) return null
+
+ return date.toDate().toLocaleDateString(language, {
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: 'numeric',
+ hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
+ timeZone: timezone,
+ })
+}
+
+export const ReplayRow = ({
+ replay,
+ timeFormat,
+ timezone,
+ currency,
+ onWatchReplay,
+}: ReplayRowProps) => {
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const location = useLocation()
+ const { theme } = useTheme()
+ const currencySymbol = getCurrencySymbol(currency)
+
+ const displayName = useMemo(() => {
+ if (!replay.profileId) {
+ return t('project.unknownUser')
+ }
+
+ return getProfileDisplayName(
+ replay.profileId,
+ Boolean(replay.isIdentified),
+ )
+ }, [replay.profileId, replay.isIdentified, t])
+
+ const replayStartedAt = useMemo(
+ () =>
+ formatDate(
+ replay.replayStart || replay.replayCreatedAt,
+ language,
+ timeFormat,
+ timezone,
+ ),
+ [language, replay.replayCreatedAt, replay.replayStart, timeFormat, timezone],
+ )
+ const replayExpiresAt = useMemo(
+ () =>
+ formatDate(replay.replayExpiresAt, language, timeFormat, timezone),
+ [language, replay.replayExpiresAt, timeFormat, timezone],
+ )
+ const durationString = useMemo(() => {
+ if (!replay.replayDuration || replay.replayDuration <= 0) return null
+ return getStringFromTime(getTimeFromSeconds(replay.replayDuration))
+ }, [replay.replayDuration])
+
+ const sessionParams = new URLSearchParams(location.search)
+ sessionParams.set('tab', PROJECT_TABS.sessions)
+ sessionParams.set('psid', replay.psid)
+ sessionParams.delete('profileId')
+ sessionParams.delete('replayId')
+
+ const profileParams = new URLSearchParams(location.search)
+ profileParams.set('tab', PROJECT_TABS.profiles)
+ if (replay.profileId) {
+ profileParams.set('profileId', replay.profileId)
+ }
+ profileParams.delete('psid')
+ profileParams.delete('replayId')
+
+ return (
+ <li className='mb-2'>
+ <div className='relative flex items-center justify-between gap-x-4 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 transition-colors hover:bg-gray-200/70 sm:px-5 dark:border-slate-800/60 dark:bg-slate-900/25 dark:hover:bg-slate-900/60'>
+ <div className='flex min-w-0 flex-1 items-center gap-x-3.5'>
+ <div className='relative shrink-0'>
+ {replay.profileId ? (
+ <ProfileAvatar profileId={replay.profileId} size={32} />
+ ) : (
+ <div className='flex h-8 w-8 items-center justify-center rounded-full bg-gray-100 ring-1 ring-gray-200/50 dark:bg-slate-800 dark:ring-slate-700/50'>
+ <Text size='xs' weight='medium' colour='secondary'>
+ ?
+ </Text>
+ </div>
+ )}
+ </div>
+
+ <div className='flex min-w-0 flex-1 flex-col justify-center gap-2'>
+ <div className='flex flex-wrap items-start justify-between gap-2 sm:gap-4'>
+ <div className='flex min-w-0 items-center gap-2'>
+ <Text size='sm' weight='semibold' truncate>
+ {displayName}
+ </Text>
+ <Text
+ as='span'
+ size='xs'
+ weight='medium'
+ colour='secondary'
+ className='hidden items-center gap-1 sm:flex'
+ >
+ <MonitorPlayIcon className='size-3.5' />
+ {durationString || t('project.sessionReplay.replay')}
+ </Text>
+ </div>
+
+ <div className='mt-0.5 flex shrink-0 items-center sm:hidden'>
+ <Text size='xs' colour='secondary' className='text-[11px]'>
+ {replayStartedAt}
+ </Text>
+ </div>
+ </div>
+
+ <div className='flex items-center justify-between gap-4'>
+ <div className='flex flex-wrap items-center gap-x-3 gap-y-2'>
+ <div className='flex items-center gap-1.5'>
+ <Tooltip
+ text={
+ replay.cc
+ ? countries.getName(replay.cc, language) || replay.cc
+ : t('project.unknownCountry')
+ }
+ tooltipNode={
+ <div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'>
+ <Flag
+ country={replay.cc}
+ size={14}
+ className='rounded-[2px]'
+ aria-hidden='true'
+ />
+ </div>
+ }
+ />
+ <Tooltip
+ text={replay.os || t('project.unknown')}
+ tooltipNode={
+ <div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'>
+ <OSIcon
+ os={replay.os}
+ theme={theme}
+ className='size-3.5'
+ />
+ </div>
+ }
+ />
+ <Tooltip
+ text={replay.br || t('project.unknown')}
+ tooltipNode={
+ <div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'>
+ <BrowserIcon
+ browser={replay.br}
+ className='size-3.5'
+ />
+ </div>
+ }
+ />
+ </div>
+
+ <div className='h-3 w-px bg-gray-200 dark:bg-slate-700' />
+
+ <div className='flex items-center gap-3'>
+ <Tooltip
+ text={t('project.sessionReplay.eventsCount', {
+ count: replay.eventCount,
+ })}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ weight='medium'
+ className='flex items-center gap-1'
+ >
+ <MonitorPlayIcon className='size-3.5' />
+ {replay.eventCount}
+ </Text>
+ }
+ />
+
+ <Tooltip
+ text={t('dashboard.pageviews')}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ weight='medium'
+ className='flex items-center gap-1'
+ >
+ <FileTextIcon className='size-3.5' />
+ {replay.pageviews}
+ </Text>
+ }
+ />
+
+ {replay.customEvents > 0 ? (
+ <Tooltip
+ text={t('dashboard.events')}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ weight='medium'
+ className='flex items-center gap-1'
+ >
+ <CursorClickIcon className='size-3.5' />
+ {replay.customEvents}
+ </Text>
+ }
+ />
+ ) : null}
+
+ {replay.revenue != null && replay.revenue !== 0 ? (
+ <Tooltip
+ text={t('dashboard.revenue')}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ weight='medium'
+ colour='inherit'
+ className={cx('flex items-center gap-1', {
+ 'text-emerald-600 dark:text-emerald-500':
+ replay.revenue > 0,
+ 'text-amber-600 dark:text-amber-500':
+ replay.revenue < 0,
+ })}
+ >
+ {replay.revenue < 0 ? '-' : ''}
+ {currencySymbol}
+ {Math.abs(replay.revenue).toFixed(2)}
+ </Text>
+ }
+ />
+ ) : null}
+
+ {replay.errors > 0 ? (
+ <Tooltip
+ text={t('dashboard.errors')}
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour='error'
+ weight='medium'
+ className='flex items-center gap-1'
+ >
+ <WarningIcon className='size-3.5' />
+ {replay.errors}
+ </Text>
+ }
+ />
+ ) : null}
+ </div>
+
+ {replayExpiresAt ? (
+ <>
+ <div className='hidden h-3 w-px bg-gray-200 sm:block dark:bg-slate-700' />
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ className='hidden sm:inline'
+ >
+ {t('project.sessionReplay.expiresAt', {
+ date: replayExpiresAt,
+ })}
+ </Text>
+ </>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div className='hidden shrink-0 items-center gap-x-2 sm:flex'>
+ <div className='mr-1 flex flex-col items-end'>
+ <Text as='p' size='xs' colour='secondary' className='text-[11px]'>
+ {replayStartedAt}
+ </Text>
+ {durationString ? (
+ <Text as='p' size='xs' colour='secondary' className='text-[11px]'>
+ {durationString}
+ </Text>
+ ) : null}
+ </div>
+ <Tooltip
+ text={t('project.watchReplay')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={t('project.watchReplay')}
+ className='active:scale-[0.97]'
+ onClick={() => onWatchReplay(replay)}
+ >
+ <PlayIcon className='size-4' />
+ </Button>
+ }
+ />
+ <Tooltip
+ text={t('project.viewSession')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={t('project.viewSession')}
+ to={{ search: sessionParams.toString() }}
+ className='active:scale-[0.97]'
+ >
+ <ListBulletsIcon className='size-4' />
+ </Button>
+ }
+ />
+ {replay.profileId ? (
+ <Tooltip
+ text={t('project.goToProfile')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={t('project.goToProfile')}
+ to={{ search: profileParams.toString() }}
+ className='active:scale-[0.97]'
+ >
+ <UserIcon className='size-4' />
+ </Button>
+ }
+ />
+ ) : null}
+ <CaretRightIcon className='size-4 text-gray-400' aria-hidden='true' />
+ </div>
+
+ <div className='flex shrink-0 items-center gap-1 sm:hidden'>
+ <Button
+ variant='icon'
+ aria-label={t('project.watchReplay')}
+ className='active:scale-[0.97]'
+ onClick={() => onWatchReplay(replay)}
+ >
+ <PlayIcon className='size-4' />
+ </Button>
+ <Button
+ variant='icon'
+ aria-label={t('project.viewSession')}
+ to={{ search: sessionParams.toString() }}
+ className='active:scale-[0.97]'
+ >
+ <ListBulletsIcon className='size-4' />
+ </Button>
+ </div>
+ </div>
+ </li>
+ )
+}
+
+export const Replays = ({
+ replays,
+ timeFormat,
+ timezone,
+ currency,
+ onWatchReplay,
+}: ReplaysProps) => {
+ return (
+ <ul className='flex flex-col'>
+ {_map(replays, (replay) => (
+ <ReplayRow
+ key={`${replay.psid}:${replay.replayId}`}
+ replay={replay}
+ timeFormat={timeFormat}
+ timezone={timezone}
+ currency={currency}
+ onWatchReplay={onWatchReplay}
+ />
+ ))}
+ </ul>
+ )
+}
diff --git a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
new file mode 100644
index 000000000..811ff3308
--- /dev/null
+++ b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
@@ -0,0 +1,358 @@
+import _isEmpty from 'lodash/isEmpty'
+import { Component, lazy, Suspense, use, useEffect, useMemo, useRef, useState } from 'react'
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useLoaderData, useRevalidator, useSearchParams } from 'react-router'
+
+import type {
+ SessionReplayListItem,
+ SessionReplayMetadata,
+ SessionReplaysResponse,
+} from '~/api/api.server'
+import { useSessionReplaysProxy } from '~/hooks/useAnalyticsProxy'
+import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
+import Filters from '~/pages/Project/View/components/Filters'
+import ProjectViewHeaderActions from '~/pages/Project/View/components/ProjectViewHeaderActions'
+import {
+ useRefreshTriggers,
+ useViewProjectContext,
+} from '~/pages/Project/View/ViewProject'
+import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import type { ProjectLoaderData } from '~/routes/projects.$id'
+import InfiniteScrollTrigger from '~/ui/InfiniteScrollTrigger'
+import LoadingBar from '~/ui/LoadingBar'
+import StatusPage from '~/ui/StatusPage'
+import routes from '~/utils/routes'
+
+import { LoaderView } from '../../View/components/LoaderView'
+import NoReplays from './NoReplays'
+import { Replays } from './Replays'
+
+const SessionReplayModal = lazy(() => import('../Sessions/SessionReplayModal'))
+
+const REPLAYS_TAKE = 30
+
+interface ReplaysErrorBoundaryState {
+ hasError: boolean
+ error: Error | null
+}
+
+class ReplaysErrorBoundary extends Component<
+ { children: ReactNode },
+ ReplaysErrorBoundaryState
+> {
+ constructor(props: { children: ReactNode }) {
+ super(props)
+ this.state = { hasError: false, error: null }
+ }
+
+ static getDerivedStateFromError(error: Error): ReplaysErrorBoundaryState {
+ return { hasError: true, error }
+ }
+
+ render() {
+ if (this.state.hasError) {
+ return (
+ <StatusPage
+ type='error'
+ title='Failed to load replays'
+ description={
+ this.state.error?.message || 'An unexpected error occurred'
+ }
+ actions={[
+ {
+ label: 'Reload page',
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
+ { label: 'Support', to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return this.props.children
+ }
+}
+
+interface ReplaysViewProps {
+ tnMapping: Record<string, string>
+}
+
+interface DeferredReplaysData {
+ replaysData: SessionReplaysResponse | null
+}
+
+function ReplaysDataResolver({
+ children,
+}: {
+ children: (data: DeferredReplaysData) => React.ReactNode
+}) {
+ const { replaysData: replaysDataPromise } =
+ useLoaderData<ProjectLoaderData>()
+
+ const replaysData = replaysDataPromise ? use(replaysDataPromise) : null
+
+ return <>{children({ replaysData })}</>
+}
+
+const getReplayMetadata = (
+ replay: SessionReplayListItem | null,
+ replayId: string,
+): SessionReplayMetadata => ({
+ hasReplay: true,
+ replayId: replay?.replayId || replayId,
+ privacyMode: replay?.privacyMode || 'normal',
+ chunkCount: replay?.chunkCount || 0,
+ eventCount: replay?.eventCount || 0,
+ replayDuration: replay?.replayDuration || 0,
+ replayExpiresAt: replay?.replayExpiresAt || '',
+})
+
+function ReplaysViewWrapper(props: ReplaysViewProps) {
+ return (
+ <ReplaysErrorBoundary>
+ <Suspense fallback={<LoaderView />}>
+ <ReplaysDataResolver>
+ {(deferredData) => (
+ <ReplaysViewInner {...props} deferredData={deferredData} />
+ )}
+ </ReplaysDataResolver>
+ </Suspense>
+ </ReplaysErrorBoundary>
+ )
+}
+
+interface ReplaysViewInnerProps extends ReplaysViewProps {
+ deferredData: DeferredReplaysData
+}
+
+const ReplaysViewInner = ({
+ tnMapping,
+ deferredData,
+}: ReplaysViewInnerProps) => {
+ const { id, project } = useCurrentProject()
+ const revalidator = useRevalidator()
+ const { replaysRefreshTrigger } = useRefreshTriggers()
+ const { timezone, period, dateRange, filters, timeFormat } =
+ useViewProjectContext()
+ const { t } = useTranslation('common')
+ const [searchParams, setSearchParams] = useSearchParams()
+ const replaysProxy = useSessionReplaysProxy()
+
+ const [replays, setReplays] = useState<SessionReplayListItem[]>(
+ () => deferredData.replaysData?.replays || [],
+ )
+ const [replaysSkip, setReplaysSkip] = useState(REPLAYS_TAKE)
+ const [canLoadMoreReplays, setCanLoadMoreReplays] = useState(
+ () => (deferredData.replaysData?.replays?.length || 0) >= REPLAYS_TAKE,
+ )
+ const [error, setError] = useState<string | null>(null)
+ const isMountedRef = useRef(true)
+ const requestIdRef = useRef(0)
+ const hasShownContentRef = useRef(
+ !_isEmpty(deferredData.replaysData?.replays || []),
+ )
+
+ const activePSID = searchParams.get('psid')
+ const activeReplayId = searchParams.get('replayId')
+ const activeReplay = useMemo(() => {
+ if (!activePSID || !activeReplayId) return null
+
+ return (
+ replays.find(
+ (replay) =>
+ replay.psid === activePSID && replay.replayId === activeReplayId,
+ ) || null
+ )
+ }, [activePSID, activeReplayId, replays])
+
+ const replaysLoading =
+ revalidator.state === 'loading' || replaysProxy.isLoading
+
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
+
+ useEffect(() => {
+ if (deferredData.replaysData && revalidator.state === 'idle') {
+ const replaysList = deferredData.replaysData.replays || []
+ setReplays(replaysList)
+ setReplaysSkip(REPLAYS_TAKE)
+ setCanLoadMoreReplays(replaysList.length >= REPLAYS_TAKE)
+ hasShownContentRef.current = !_isEmpty(replaysList)
+ setError(null)
+ }
+ }, [deferredData.replaysData, revalidator.state])
+
+ const getReplaysParams = (take: number, skip: number) => {
+ let from: string | undefined
+ let to: string | undefined
+
+ if (dateRange) {
+ from = getFormatDate(dateRange[0])
+ to = getFormatDate(dateRange[1])
+ }
+
+ return {
+ timeBucket: 'day',
+ period: period === 'custom' ? '' : period,
+ from,
+ to,
+ timezone,
+ filters,
+ take,
+ skip,
+ }
+ }
+
+ const loadReplays = async (
+ forcedSkip?: number,
+ override?: boolean,
+ options: { take?: number; limit?: number } = {},
+ ) => {
+ if (replaysLoading) return
+
+ const requestId = ++requestIdRef.current
+ const skip = typeof forcedSkip === 'number' ? forcedSkip : replaysSkip
+ const take = options.take || REPLAYS_TAKE
+
+ const data = await replaysProxy.fetchSessionReplays(
+ id,
+ getReplaysParams(take, skip),
+ )
+
+ if (requestId !== requestIdRef.current || !isMountedRef.current) {
+ return
+ }
+
+ if (!data) {
+ setError(replaysProxy.error || t('apiNotifications.somethingWentWrong'))
+ return
+ }
+
+ const newReplays = data.replays || []
+ const visibleReplays =
+ typeof options.limit === 'number'
+ ? newReplays.slice(0, options.limit)
+ : newReplays
+
+ setError(null)
+
+ if (override) {
+ setReplays(visibleReplays)
+ setReplaysSkip(visibleReplays.length)
+ hasShownContentRef.current = !_isEmpty(visibleReplays)
+ } else {
+ setReplays((prev) => {
+ const existingIds = new Set(
+ prev.map((replay) => `${replay.psid}:${replay.replayId}`),
+ )
+ const uniqueNewReplays = visibleReplays.filter(
+ (replay) => !existingIds.has(`${replay.psid}:${replay.replayId}`),
+ )
+ return [...prev, ...uniqueNewReplays]
+ })
+ setReplaysSkip((prev) => prev + visibleReplays.length)
+ }
+
+ if (typeof options.limit === 'number') {
+ setCanLoadMoreReplays(newReplays.length > options.limit)
+ } else {
+ setCanLoadMoreReplays(newReplays.length >= take)
+ }
+ }
+
+ useEffect(() => {
+ if (replaysRefreshTrigger > 0) {
+ const limit = Math.max(replays.length, REPLAYS_TAKE)
+ loadReplays(0, true, { take: limit + 1, limit })
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [replaysRefreshTrigger])
+
+ const openReplay = (replay: SessionReplayListItem) => {
+ const params = new URLSearchParams(searchParams)
+ params.set('psid', replay.psid)
+ params.set('replayId', replay.replayId)
+ setSearchParams(params)
+ }
+
+ const closeReplay = () => {
+ const params = new URLSearchParams(searchParams)
+ params.delete('psid')
+ params.delete('replayId')
+ setSearchParams(params)
+ }
+
+ if (error && !replaysLoading) {
+ return (
+ <StatusPage
+ type='error'
+ title={t('apiNotifications.somethingWentWrong')}
+ description={t('apiNotifications.errorCode', { error })}
+ actions={[
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
+ { label: t('notFoundPage.support'), to: routes.contact },
+ ]}
+ />
+ )
+ }
+
+ return (
+ <>
+ <DashboardHeader
+ showLiveVisitors
+ rightContent={<ProjectViewHeaderActions tnMapping={tnMapping} />}
+ />
+ {replaysLoading && !_isEmpty(replays) ? <LoadingBar /> : null}
+ {!_isEmpty(replays) ? (
+ <Filters className='mb-3' tnMapping={tnMapping} />
+ ) : null}
+ {replaysLoading && _isEmpty(replays) ? <LoaderView /> : null}
+ {!replaysLoading && _isEmpty(replays) && !hasShownContentRef.current ? (
+ <NoReplays filters={filters} />
+ ) : null}
+ <Replays
+ replays={replays}
+ timeFormat={timeFormat}
+ timezone={timezone}
+ currency={project?.revenueCurrency}
+ onWatchReplay={openReplay}
+ />
+ <InfiniteScrollTrigger
+ hasMore={canLoadMoreReplays}
+ isLoading={replaysLoading}
+ onLoadMore={() => loadReplays()}
+ disabled={replaysLoading}
+ className={replaysLoading && _isEmpty(replays) ? 'hidden' : ''}
+ spinnerClassName='mr-0! ml-0!'
+ />
+ {activePSID && activeReplayId ? (
+ <Suspense fallback={null}>
+ <SessionReplayModal
+ isOpen
+ onClose={closeReplay}
+ projectId={id}
+ psid={activePSID}
+ replay={getReplayMetadata(activeReplay, activeReplayId)}
+ replayId={activeReplayId}
+ timeFormat={timeFormat}
+ />
+ </Suspense>
+ ) : null}
+ </>
+ )
+}
+
+const ReplaysView = ReplaysViewWrapper
+
+export default ReplaysView
diff --git a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
index 0fb86a5f3..f60f60c6e 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
@@ -138,6 +138,7 @@ interface SessionReplayModalProps {
projectId: string
psid: string
replay?: SessionReplayMetadata | null
+ replayId?: string
pages?: PageflowEvent[]
timeFormat: '12-hour' | '24-hour'
}
@@ -1012,6 +1013,7 @@ export const SessionReplayModal = ({
projectId,
psid,
replay,
+ replayId,
pages = [],
timeFormat,
}: SessionReplayModalProps) => {
@@ -1152,7 +1154,8 @@ export const SessionReplayModal = ({
!canControlReplay
const speedLabel =
speed === 1 ? t('project.sessionReplay.normalSpeed') : `${speed}×`
- const exportToastId = `session-replay-export-${psid}`
+ const selectedReplayId = replayId || replay?.replayId
+ const exportToastId = `session-replay-export-${psid}-${selectedReplayId || 'latest'}`
const clearExportPoll = useCallback(() => {
if (exportPollTimeout.current) {
@@ -1208,7 +1211,7 @@ export const SessionReplayModal = ({
setIsControlsFocused(false)
setPlayerSize({ width: 0, height: 0 })
- fetchSessionReplay(projectId, psid, replay?.replayId)
+ fetchSessionReplay(projectId, psid, selectedReplayId)
.then((result) => {
if (cancelled) return
if (!result) {
@@ -1232,7 +1235,7 @@ export const SessionReplayModal = ({
return () => {
cancelled = true
}
- }, [fetchSessionReplay, isOpen, projectId, psid, replay?.replayId, t])
+ }, [fetchSessionReplay, isOpen, projectId, psid, selectedReplayId, t])
useEffect(() => {
if (!isOpen || !hasEvents || !playerRoot.current) return
@@ -1720,7 +1723,7 @@ export const SessionReplayModal = ({
const status = await startSessionReplayExport(
projectId,
psid,
- replay?.replayId,
+ selectedReplayId,
)
setIsExportStarting(false)
@@ -1745,7 +1748,7 @@ export const SessionReplayModal = ({
isReplayExporting,
projectId,
psid,
- replay?.replayId,
+ selectedReplayId,
startExportPolling,
startSessionReplayExport,
t,
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index d7cb34e66..ec074ce9b 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -6,6 +6,7 @@ import {
import {
getSessionsServer,
+ getSessionReplaysServer,
getSessionReplayServer,
getFunnelSessionsServer,
getGoalSessionsServer,
@@ -44,6 +45,7 @@ import {
type AnalyticsParams,
type AnalyticsFilter,
type SessionsResponse,
+ type SessionReplaysResponse,
type SessionReplayResponse,
type FunnelSessionsResponse,
type GoalSessionsResponse,
@@ -99,6 +101,7 @@ function formatDateForBackend(dateStr: string | undefined): string | undefined {
interface ProxyRequest {
action:
| 'getSessions'
+ | 'getSessionReplays'
| 'getSessionReplay'
| 'getErrors'
| 'getFeatureFlagStats'
@@ -217,6 +220,22 @@ export async function action({ request }: ActionFunctionArgs) {
? result.error.join(', ')
: result.error
: null,
+ })
+ }
+
+ case 'getSessionReplays': {
+ const result = await getSessionReplaysServer(
+ request,
+ projectId,
+ analyticsParams,
+ )
+ return data<ProxyResponse<SessionReplaysResponse>>({
+ data: result.data,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index fd4919200..ae6ac0a33 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -20,6 +20,7 @@ import {
getPerfDataServer,
getPerformanceOverallStatsServer,
getSessionsServer,
+ getSessionReplaysServer,
getSessionServer,
getErrorsServer,
getErrorServer,
@@ -32,6 +33,7 @@ import {
type PerformanceDataResponse,
type PerformanceOverallObject,
type SessionsResponse,
+ type SessionReplaysResponse,
type SessionDetailsResponse,
type ErrorsResponse,
type ErrorDetailsResponse,
@@ -349,6 +351,7 @@ export const meta: MetaFunction<typeof loader> = ({ data, location }) => {
...(seoTabId ? { [seoTabId]: t('project.seo.title') } : {}),
[PROJECT_TABS.profiles]: t('dashboard.profiles'),
[PROJECT_TABS.sessions]: t('dashboard.sessions'),
+ [PROJECT_TABS.replays]: t('dashboard.replays'),
[PROJECT_TABS.errors]: t('dashboard.errors'),
[PROJECT_TABS.funnels]: t('dashboard.funnels'),
[PROJECT_TABS.goals]: t('dashboard.goals'),
@@ -489,6 +492,7 @@ export interface ProjectLoaderData {
> | null>
// Sessions data
sessionsData?: Promise<SessionsResponse | null>
+ replaysData?: Promise<SessionReplaysResponse | null>
sessionDetails?: Promise<SessionDetailsResponse | null>
// Errors data
errorsData?: Promise<ErrorsResponse | null>
@@ -626,6 +630,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
| Promise<Record<string, PerformanceOverallObject> | null>
| undefined
let sessionsData: Promise<SessionsResponse | null> | undefined
+ let replaysData: Promise<SessionReplaysResponse | null> | undefined
let sessionDetails: Promise<SessionDetailsResponse | null> | undefined
let errorsData: Promise<ErrorsResponse | null> | undefined
let errorDetails: Promise<ErrorDetailsResponse | null> | undefined
@@ -733,6 +738,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
password || undefined,
).then((res) => res.data)
}
+ } else if (tab === PROJECT_TABS.replays) {
+ replaysData = getSessionReplaysServer(
+ request,
+ projectId,
+ analyticsParams,
+ ).then((res) => res.data)
} else if (tab === PROJECT_TABS.errors) {
errorsData = getErrorsServer(request, projectId, analyticsParams).then(
(res) => res.data,
@@ -812,6 +823,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
perfCompareData,
perfOverallCompareStats,
sessionsData,
+ replaysData,
sessionDetails,
errorsData,
errorDetails,
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 1a945a1a2..fe9c3a71f 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1183,6 +1183,7 @@
"profiles": "Profiles",
"funnels": "Funnels",
"sessions": "Sessions",
+ "replays": "Replays",
"xOccurrences": "{{x}} occurrences",
"errors": "Errors",
"xPageviews": "{{x}} pageviews",
@@ -1979,8 +1980,10 @@
"sessionActivity": "Session activity",
"sessionReplay": {
"available": "Replay available",
+ "replay": "Replay",
"duration": "Replay duration: {{duration}}",
"expiresAt": "Expires {{date}}",
+ "eventsCount": "{{count}} replay events",
"title": "Session replay",
"loadError": "Could not load replay",
"playerError": "Could not initialise replay player",
@@ -2113,6 +2116,10 @@
"noSessionsFound": "No sessions found for this period.",
"exploreSessions": "View sessions",
"noSessionsFiltersDesc": "No sessions match this period and filter set. Try changing the date range or filters.",
+ "noReplaysTitle": "No replays yet",
+ "noReplaysContent": "No session replays were recorded for this period. Try a different date range.",
+ "noReplaysFiltersTitle": "No replays found",
+ "noReplaysFiltersDesc": "No replays match this period and filter set. Try changing the date range or filters.",
"noCaptchaEv": "No CAPTCHA events were recorded for this period.\nIf you have not set up CAPTCHA yet, see the <url>docs</url> to add it to your app.",
"mapping": {
"cc": "Country",