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!

feat: Session replays

Blue Moused33237171314
diff --git a/backend/.env.example b/backend/.env.example
index a665fd4f2..6577ba87d 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -109,6 +109,26 @@ EMAIL_ACTION_ENCRYPTION_KEY=
# Swetrix Enterprise (Cloud)
SWETRIX_LICENSE_KEY=
+# Cloudflare R2 storage defaults. Session Replay uses these when the
+# SESSION_REPLAY_R2_* variables below are not set.
+R2_ACCOUNT_ID=
+R2_ENDPOINT=
+R2_BUCKET=
+R2_ACCESS_KEY_ID=
+R2_SECRET_ACCESS_KEY=
+
+# Cloudflare R2 storage for Session Replays.
+# If SESSION_REPLAY_R2_ENDPOINT is empty and SESSION_REPLAY_R2_ACCOUNT_ID is set,
+# the endpoint defaults to https://${SESSION_REPLAY_R2_ACCOUNT_ID}.r2.cloudflarestorage.com.
+# For EU jurisdiction buckets, set SESSION_REPLAY_R2_ENDPOINT explicitly to
+# https://${SESSION_REPLAY_R2_ACCOUNT_ID}.eu.r2.cloudflarestorage.com.
+# Do not include the bucket path in SESSION_REPLAY_R2_ENDPOINT.
+SESSION_REPLAY_R2_ACCOUNT_ID=
+SESSION_REPLAY_R2_ENDPOINT=
+SESSION_REPLAY_R2_BUCKET=
+SESSION_REPLAY_R2_ACCESS_KEY_ID=
+SESSION_REPLAY_R2_SECRET_ACCESS_KEY=
+
# OpenRouter API key for AI features
OPENROUTER_API_KEY=
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 3280fc9ec..0b626b576 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -71,6 +71,11 @@ import {
} from './interfaces'
import { GetSessionsDto } from './dto/get-sessions.dto'
import { GetSessionDto } from './dto/get-session.dto'
+import {
+ GetSessionReplayDto,
+ SessionReplayChunkDto,
+ SessionReplayStartDto,
+} from './dto/session-replay.dto'
import { GetProfilesDto } from './dto/get-profiles.dto'
import { GetProfileDto, GetProfileSessionsDto } from './dto/get-profile.dto'
import { ErrorDto } from './dto/error.dto'
@@ -1485,6 +1490,101 @@ export class AnalyticsController {
return this.analyticsService.getBotStats(pid, period)
}
+ @Post('session-replay/start')
+ @Public()
+ async startSessionReplay(
+ @Body() replayDTO: SessionReplayStartDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ) {
+ const { 'user-agent': userAgent, origin } = headers
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ await checkRateLimit(ip, 'session-replay-start', 120, 60)
+ await checkRateLimit(replayDTO.pid, 'session-replay-start', 2000, 60)
+
+ const botResult = await this.analyticsService.checkBot(
+ replayDTO.pid,
+ userAgent,
+ headers,
+ ip,
+ headers.referer || headers.referrer,
+ replayDTO.pg,
+ 'session_replay',
+ )
+
+ if (botResult.isBot) {
+ return BOT_RESPONSE
+ }
+
+ const project = await this.analyticsService.validate(replayDTO, origin, ip)
+ const { country } = getIPDetails(ip, replayDTO.tz)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
+ this.logger.log(
+ `pid: ${replayDTO.pid}, replayId: ${replayDTO.replayId}`,
+ 'POST /analytics/session-replay/start',
+ )
+
+ return this.analyticsService.startSessionReplay(
+ project,
+ replayDTO.pid,
+ replayDTO.replayId,
+ replayDTO.privacy,
+ userAgent,
+ ip,
+ replayDTO.profileId,
+ )
+ }
+
+ @Post('session-replay/chunk')
+ @Public()
+ async uploadSessionReplayChunk(
+ @Body() replayDTO: SessionReplayChunkDto,
+ @Headers() headers,
+ @Ip() reqIP,
+ ) {
+ const { 'user-agent': userAgent, origin } = headers
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+
+ await checkRateLimit(ip, 'session-replay-chunk', 600, 60)
+ await checkRateLimit(replayDTO.pid, 'session-replay-chunk', 5000, 60)
+
+ const botResult = await this.analyticsService.checkBot(
+ replayDTO.pid,
+ userAgent,
+ headers,
+ ip,
+ headers.referer || headers.referrer,
+ replayDTO.pg,
+ 'session_replay',
+ )
+
+ if (botResult.isBot) {
+ return BOT_RESPONSE
+ }
+
+ const project = await this.analyticsService.validate(replayDTO, origin, ip)
+ const { country } = getIPDetails(ip, replayDTO.tz)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
+ this.logger.log(
+ `pid: ${replayDTO.pid}, replayId: ${replayDTO.replayId}, chunkIndex: ${replayDTO.chunkIndex}`,
+ 'POST /analytics/session-replay/chunk',
+ )
+
+ return this.analyticsService.storeSessionReplayChunk(
+ project,
+ replayDTO.pid,
+ replayDTO.replayId,
+ replayDTO.privacy,
+ replayDTO.chunkIndex,
+ replayDTO.events,
+ userAgent,
+ ip,
+ )
+ }
+
@Post('error')
@Public()
async logError(@Body() errorDTO: ErrorDto, @Headers() headers, @Ip() reqIP) {
@@ -2635,6 +2735,31 @@ export class AnalyticsController {
return result
}
+ @Get('session-replay')
+ @Auth(true, true)
+ async getSessionReplay(
+ @Query() data: GetSessionReplayDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const { pid, psid, replayId } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ this.logger.log(
+ `pid: ${pid}, psid: ${psid}, replayId: ${replayId || 'latest'}`,
+ 'GET /analytics/session-replay',
+ )
+
+ return this.analyticsService.getSessionReplay(pid, psid, replayId)
+ }
+
@Get('profiles')
@Auth(true, true)
async getProfiles(
diff --git a/backend/apps/cloud/src/analytics/analytics.module.ts b/backend/apps/cloud/src/analytics/analytics.module.ts
index 3e348ce82..b8125aa36 100644
--- a/backend/apps/cloud/src/analytics/analytics.module.ts
+++ b/backend/apps/cloud/src/analytics/analytics.module.ts
@@ -7,6 +7,7 @@ import { BotDetectionService } from './bot-detection.service'
import { HeartbeatGateway } from './heartbeat.gateway'
import { SaltService } from './salt.service'
import { Salt } from './entities/salt.entity'
+import { SessionReplayR2Service } from './session-replay-r2.service'
import { UserModule } from '../user/user.module'
import { AppLoggerModule } from '../logger/logger.module'
import { ProjectModule } from '../project/project.module'
@@ -26,6 +27,7 @@ import { ExperimentModule } from '../experiment/experiment.module'
AnalyticsService,
BotDetectionService,
SaltService,
+ SessionReplayR2Service,
HeartbeatGateway,
],
exports: [AnalyticsService, BotDetectionService, SaltService],
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 596c10901..2739749f1 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -1,4 +1,5 @@
import crypto from 'crypto'
+import { gzipSync, gunzipSync } from 'zlib'
import _isEmpty from 'lodash/isEmpty'
import _split from 'lodash/split'
import _reverse from 'lodash/reverse'
@@ -33,10 +34,15 @@ import {
HttpStatus,
UnprocessableEntityException,
PreconditionFailedException,
+ PayloadTooLargeException,
} from '@nestjs/common'
import { isbot } from 'isbot'
-import { DEFAULT_TIMEZONE, PlanCode } from '../user/entities/user.entity'
+import {
+ DEFAULT_TIMEZONE,
+ PlanCode,
+ getSessionReplayQuota,
+} from '../user/entities/user.entity'
import {
redis,
UNIQUE_SESSION_LIFE_TIME,
@@ -113,6 +119,8 @@ import { ProjectViewCustomEventDto } from '../project/dto/create-project-view.dt
import { UAParser } from '@ua-parser-js/pro-business'
import { extensions } from './utils/ua-parser'
import { In, Not } from 'typeorm'
+import { SessionReplayR2Service } from './session-replay-r2.service'
+import { SessionReplayPrivacyMode } from './dto/session-replay.dto'
dayjs.extend(utc)
dayjs.extend(dayjsTimezone)
@@ -131,6 +139,10 @@ const isValidLocale = (lc: string): boolean => {
const LIVE_SESSION_THRESHOLD_SECONDS = 120
const MAX_FILTERS = 100
const MAX_FILTER_VALUES = 100
+const SESSION_REPLAY_RETENTION_VALUES = [30, 90, 365, 1825] as const
+const MAX_SESSION_REPLAY_EVENTS_PER_CHUNK = 1000
+const MAX_SESSION_REPLAY_CHUNK_BYTES = 900 * 1024
+const SESSION_REPLAY_CLEANUP_BATCH_SIZE = 500
const SOFTWARE_WITH_PATCH_VERSION = ['GameVault']
@@ -438,6 +450,7 @@ export class AnalyticsService {
private readonly saltService: SaltService,
private readonly botDetectionService: BotDetectionService,
private readonly logger: AppLoggerService,
+ private readonly sessionReplayStorage: SessionReplayR2Service,
) {}
async checkBot(
@@ -685,7 +698,11 @@ export class AnalyticsService {
}
async validate(
- logDTO: PageviewsDto | EventsDto | ErrorDto,
+ logDTO:
+ | PageviewsDto
+ | EventsDto
+ | ErrorDto
+ | { pid: string; lc?: string | null },
origin: string,
ip?: string,
): Promise<Project> {
@@ -1634,6 +1651,406 @@ export class AnalyticsService {
}
}
+ isValidSessionReplayRetentionDays(
+ value: number,
+ ): value is 30 | 90 | 365 | 1825 {
+ return SESSION_REPLAY_RETENTION_VALUES.includes(value as any)
+ }
+
+ private getSessionReplayRetention(project: Project): {
+ retentionDays: number
+ expiresAt: string
+ } {
+ const retentionDays = this.isValidSessionReplayRetentionDays(
+ project.sessionReplayRetentionDays,
+ )
+ ? project.sessionReplayRetentionDays
+ : 30
+
+ return {
+ retentionDays,
+ expiresAt: dayjs
+ .utc()
+ .add(retentionDays, 'day')
+ .format('YYYY-MM-DD HH:mm:ss'),
+ }
+ }
+
+ private async resolveReplaySession(
+ pid: string,
+ userAgent: string,
+ ip: string,
+ ): Promise<string> {
+ const [, psid] = await this.generateAndStoreSessionId(pid, userAgent, ip)
+ return psid
+ }
+
+ async startSessionReplay(
+ project: Project,
+ pid: string,
+ replayId: string,
+ privacy: SessionReplayPrivacyMode,
+ userAgent: string,
+ ip: string,
+ profileId?: string,
+ ) {
+ if (!this.sessionReplayStorage.isConfigured()) {
+ throw new InternalServerErrorException(
+ 'Session replay storage is not configured',
+ )
+ }
+
+ const psid = await this.resolveReplaySession(pid, userAgent, ip)
+ const resolvedProfileId = await this.generateProfileId(
+ pid,
+ userAgent,
+ ip,
+ profileId,
+ )
+
+ await this.recordSessionActivity(psid, pid, resolvedProfileId)
+
+ const retention = this.getSessionReplayRetention(project)
+
+ return {
+ replayId,
+ psid,
+ privacy,
+ ...retention,
+ }
+ }
+
+ private getSessionReplayObjectKey(
+ pid: string,
+ psid: string,
+ replayId: string,
+ chunkIndex: number,
+ ): string {
+ const date = dayjs.utc()
+ return [
+ 'session-replays',
+ pid,
+ date.format('YYYY'),
+ date.format('MM'),
+ psid,
+ replayId,
+ `${chunkIndex}.json.gz`,
+ ].join('/')
+ }
+
+ private getReplayUsageKey(pid: string, psid: string, replayId: string) {
+ return `session-replay:usage:${dayjs.utc().format('YYYY-MM')}:${pid}:${psid}:${replayId}`
+ }
+
+ private getReplayUsageTtlSeconds() {
+ return Math.max(60, dayjs.utc().endOf('month').diff(dayjs.utc(), 'second'))
+ }
+
+ private async getMonthlyReplayUsage(pid: string): Promise<number> {
+ const monthStart = dayjs
+ .utc()
+ .startOf('month')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT uniqExact(concat(toString(psid), ':', replayId)) AS usage
+ FROM session_replay_chunks
+ WHERE pid = {pid:FixedString(12)}
+ AND created >= {monthStart:DateTime}
+ `,
+ query_params: { pid, monthStart },
+ })
+ .then((resultSet) => resultSet.json<{ usage: number }>())
+
+ return Number(data[0]?.usage) || 0
+ }
+
+ private async reserveReplayUsage(
+ project: Project,
+ pid: string,
+ psid: string,
+ replayId: string,
+ ): Promise<{ reserved: boolean; key?: string }> {
+ const key = this.getReplayUsageKey(pid, psid, replayId)
+ const result = await redis.set(
+ key,
+ '1',
+ 'EX',
+ this.getReplayUsageTtlSeconds(),
+ 'NX',
+ )
+
+ if (result !== 'OK') {
+ return { reserved: false }
+ }
+
+ const quota = getSessionReplayQuota(project.admin)
+ if (quota !== 'custom') {
+ const usage = await this.getMonthlyReplayUsage(pid)
+ if (usage >= quota) {
+ await redis.del(key)
+ throw new HttpException(
+ 'Monthly session replay quota exceeded',
+ HttpStatus.PAYMENT_REQUIRED,
+ )
+ }
+ }
+
+ return { reserved: true, key }
+ }
+
+ async storeSessionReplayChunk(
+ project: Project,
+ pid: string,
+ replayId: string,
+ privacy: SessionReplayPrivacyMode,
+ chunkIndex: number,
+ events: Record<string, unknown>[],
+ userAgent: string,
+ ip: string,
+ ) {
+ if (!this.sessionReplayStorage.isConfigured()) {
+ throw new InternalServerErrorException(
+ 'Session replay storage is not configured',
+ )
+ }
+
+ if (events.length > MAX_SESSION_REPLAY_EVENTS_PER_CHUNK) {
+ throw new BadRequestException('Session replay chunk has too many events')
+ }
+
+ const psid = await this.resolveReplaySession(pid, userAgent, ip)
+ const retention = this.getSessionReplayRetention(project)
+ const payload = JSON.stringify({ events })
+ const uncompressedBytes = Buffer.byteLength(payload)
+
+ if (uncompressedBytes > MAX_SESSION_REPLAY_CHUNK_BYTES) {
+ throw new PayloadTooLargeException('Session replay chunk is too large')
+ }
+
+ const usageReservation = await this.reserveReplayUsage(
+ project,
+ pid,
+ psid,
+ replayId,
+ )
+ const objectKey = this.getSessionReplayObjectKey(
+ pid,
+ psid,
+ replayId,
+ chunkIndex,
+ )
+ const compressed = gzipSync(Buffer.from(payload))
+ const timestamps = events
+ .map((event) =>
+ typeof event.timestamp === 'number' ? event.timestamp : null,
+ )
+ .filter((timestamp): timestamp is number => timestamp !== null)
+
+ try {
+ await this.sessionReplayStorage.putObject(objectKey, compressed)
+
+ await clickhouse.insert({
+ table: 'session_replay_chunks',
+ format: 'JSONEachRow',
+ values: [
+ {
+ pid,
+ psid,
+ replayId,
+ chunkIndex,
+ objectKey,
+ privacyMode: privacy,
+ eventCount: events.length,
+ uncompressedBytes,
+ compressedBytes: compressed.byteLength,
+ firstEventTimestamp: timestamps.length
+ ? Math.min(...timestamps)
+ : null,
+ lastEventTimestamp: timestamps.length
+ ? Math.max(...timestamps)
+ : null,
+ created: dayjs.utc().format('YYYY-MM-DD HH:mm:ss'),
+ expiresAt: retention.expiresAt,
+ },
+ ],
+ clickhouse_settings: { async_insert: 1, wait_for_async_insert: 1 },
+ })
+ } catch (reason) {
+ await Promise.allSettled([
+ usageReservation.key ? redis.del(usageReservation.key) : undefined,
+ this.sessionReplayStorage.deleteObject(objectKey),
+ ])
+ throw reason
+ }
+
+ return {
+ replayId,
+ psid,
+ chunkIndex,
+ eventCount: events.length,
+ ...retention,
+ countedUsage: usageReservation.reserved,
+ }
+ }
+
+ async getSessionReplaySummary(pid: string, psid: string) {
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT
+ replayId,
+ anyLast(privacyMode) AS privacyMode,
+ count() AS chunkCount,
+ sum(eventCount) AS eventCount,
+ min(firstEventTimestamp) AS firstEventTimestamp,
+ max(lastEventTimestamp) AS lastEventTimestamp,
+ max(expiresAt) AS replayExpiresAt,
+ max(created) AS lastCreated
+ FROM session_replay_chunks
+ WHERE pid = {pid:FixedString(12)}
+ AND psid = toUInt64OrNull({psid:String})
+ AND expiresAt > now()
+ GROUP BY replayId
+ ORDER BY lastCreated DESC
+ LIMIT 1
+ `,
+ query_params: { pid, psid },
+ })
+ .then((resultSet) =>
+ resultSet.json<{
+ replayId: string
+ privacyMode: SessionReplayPrivacyMode
+ chunkCount: number
+ eventCount: number
+ firstEventTimestamp: number | string | null
+ lastEventTimestamp: number | string | null
+ replayExpiresAt: string
+ }>(),
+ )
+
+ const replay = data[0]
+ if (!replay) {
+ return null
+ }
+
+ const first = Number(replay.firstEventTimestamp)
+ const last = Number(replay.lastEventTimestamp)
+ const duration =
+ Number.isFinite(first) && Number.isFinite(last) && last > first
+ ? Math.round((last - first) / 1000)
+ : await this.getSessionDurationFromClickHouse(psid, pid)
+
+ return {
+ hasReplay: true,
+ replayId: replay.replayId,
+ privacyMode: replay.privacyMode,
+ chunkCount: Number(replay.chunkCount) || 0,
+ eventCount: Number(replay.eventCount) || 0,
+ replayDuration: duration || 0,
+ replayExpiresAt: replay.replayExpiresAt,
+ }
+ }
+
+ async getSessionReplay(
+ pid: string,
+ psid: string,
+ replayId?: string,
+ ): Promise<{
+ replay: Awaited<ReturnType<AnalyticsService['getSessionReplaySummary']>>
+ events: Record<string, unknown>[]
+ }> {
+ const selectedReplayId =
+ replayId || (await this.getSessionReplaySummary(pid, psid))?.replayId
+
+ if (!selectedReplayId) {
+ return { replay: null, events: [] }
+ }
+
+ const { data: chunks } = await clickhouse
+ .query({
+ query: `
+ SELECT objectKey
+ FROM session_replay_chunks
+ WHERE pid = {pid:FixedString(12)}
+ AND psid = toUInt64OrNull({psid:String})
+ AND replayId = {replayId:String}
+ AND expiresAt > now()
+ ORDER BY chunkIndex ASC
+ `,
+ query_params: { pid, psid, replayId: selectedReplayId },
+ })
+ .then((resultSet) => resultSet.json<{ objectKey: string }>())
+
+ const events: Record<string, unknown>[] = []
+
+ for (const chunk of chunks) {
+ const compressed = await this.sessionReplayStorage.getObject(
+ chunk.objectKey,
+ )
+ if (!compressed) continue
+
+ const parsed = JSON.parse(gunzipSync(compressed).toString('utf8')) as {
+ events?: Record<string, unknown>[]
+ }
+
+ if (Array.isArray(parsed.events)) {
+ events.push(...parsed.events)
+ }
+ }
+
+ events.sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0))
+
+ return {
+ replay: await this.getSessionReplaySummary(pid, psid),
+ events,
+ }
+ }
+
+ async cleanupExpiredSessionReplays(
+ limit = SESSION_REPLAY_CLEANUP_BATCH_SIZE,
+ ): Promise<number> {
+ if (!this.sessionReplayStorage.isConfigured()) {
+ return 0
+ }
+
+ const { data } = await clickhouse
+ .query({
+ query: `
+ SELECT objectKey
+ FROM session_replay_chunks
+ WHERE expiresAt <= now()
+ LIMIT {limit:UInt32}
+ `,
+ query_params: { limit },
+ })
+ .then((resultSet) => resultSet.json<{ objectKey: string }>())
+
+ if (_isEmpty(data)) {
+ return 0
+ }
+
+ const objectKeys = data.map((row) => row.objectKey)
+
+ await Promise.allSettled(
+ objectKeys.map((objectKey) =>
+ this.sessionReplayStorage.deleteObject(objectKey),
+ ),
+ )
+
+ await clickhouse.command({
+ query: `
+ ALTER TABLE session_replay_chunks
+ DELETE WHERE objectKey IN ({objectKeys:Array(String)})
+ `,
+ query_params: { objectKeys },
+ })
+
+ return objectKeys.length
+ }
+
formatFunnel(data: IFunnelCHResponse[], pages: string[]): IFunnel[] {
const funnel = _map(data, (row, index) => {
const value = pages[index]
@@ -5684,6 +6101,8 @@ export class AnalyticsService {
isLive = lastActivityTime.isAfter(liveThresholdTime)
}
+ const replay = await this.getSessionReplaySummary(pid, psid)
+
return {
pages: this.processPageflow(pages),
details: {
@@ -5694,6 +6113,7 @@ export class AnalyticsService {
psid,
chart: chartData,
timeBucket,
+ replay,
}
}
@@ -5788,6 +6208,19 @@ export class AnalyticsService {
WHERE pid = {pid:FixedString(12)}
GROUP BY psidCasted, pid
),
+ replay_summary AS (
+ SELECT
+ CAST(psid, 'String') AS psidCasted,
+ pid,
+ countDistinct(replayId) AS replayCount,
+ min(firstEventTimestamp) AS firstReplayTimestamp,
+ max(lastEventTimestamp) AS lastReplayTimestamp,
+ max(expiresAt) AS replayExpiresAt
+ FROM session_replay_chunks
+ WHERE pid = {pid:FixedString(12)}
+ AND expiresAt > now()
+ GROUP BY psidCasted, pid
+ ),
first_session_per_profile AS (
SELECT
profileId,
@@ -5813,13 +6246,27 @@ export class AnalyticsService {
dsf.sessionStart AS sessionStart,
dsf.lastActivity AS lastActivity,
sda.avg_duration AS sdur,
- coalesce(nullIf(sda.profileId, ''), dsf.profileId) AS profileId
+ coalesce(nullIf(sda.profileId, ''), dsf.profileId) AS profileId,
+ COALESCE(rs.replayCount, 0) AS replayCount,
+ if(
+ COALESCE(rs.replayCount, 0) = 0,
+ NULL,
+ if(
+ isNull(rs.firstReplayTimestamp)
+ OR isNull(rs.lastReplayTimestamp)
+ OR rs.lastReplayTimestamp <= rs.firstReplayTimestamp,
+ ifNull(sda.avg_duration, 0),
+ intDiv(rs.lastReplayTimestamp - rs.firstReplayTimestamp, 1000)
+ )
+ ) AS replayDuration,
+ rs.replayExpiresAt AS replayExpiresAt
FROM distinct_sessions_filtered dsf
LEFT JOIN pageview_counts pc ON dsf.psidCasted = pc.psidCasted AND dsf.pid = pc.pid
LEFT JOIN event_counts ec ON dsf.psidCasted = ec.psidCasted AND dsf.pid = ec.pid
LEFT JOIN error_counts errc ON dsf.psidCasted = errc.psidCasted AND dsf.pid = errc.pid
LEFT JOIN revenue_totals rt ON dsf.psidCasted = rt.psidCasted AND dsf.pid = rt.pid
LEFT JOIN session_duration_agg sda ON dsf.psidCasted = sda.psidCasted AND dsf.pid = sda.pid
+ LEFT JOIN replay_summary rs ON dsf.psidCasted = rs.psidCasted AND dsf.pid = rs.pid
)
SELECT
se.psidCasted AS psid,
@@ -5841,7 +6288,10 @@ export class AnalyticsService {
ifNull(se.profileId, '') = '',
0,
if(isNull(fsp.firstPsid) OR fsp.firstPsid = '' OR fsp.firstPsid = se.psidCasted, 1, 0)
- ) AS isFirstSession
+ ) AS isFirstSession,
+ if(se.replayCount > 0, 1, 0) AS hasReplay,
+ se.replayDuration,
+ se.replayExpiresAt
FROM sessions_enriched se
LEFT JOIN first_session_per_profile fsp ON se.profileId = fsp.profileId
WHERE se.psidCasted IS NOT NULL
diff --git a/backend/apps/cloud/src/analytics/bot-detection.service.ts b/backend/apps/cloud/src/analytics/bot-detection.service.ts
index 0e740b7e1..2485bb6c8 100644
--- a/backend/apps/cloud/src/analytics/bot-detection.service.ts
+++ b/backend/apps/cloud/src/analytics/bot-detection.service.ts
@@ -23,6 +23,7 @@ export type BotEndpoint =
| 'feature_flag'
| 'heartbeat'
| 'noscript'
+ | 'session_replay'
interface BotDetectionInput {
pid: string
diff --git a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
new file mode 100644
index 000000000..6a5a96697
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
@@ -0,0 +1,89 @@
+import { ApiProperty } from '@nestjs/swagger'
+import {
+ ArrayMaxSize,
+ IsArray,
+ IsIn,
+ IsInt,
+ IsNotEmpty,
+ IsObject,
+ IsOptional,
+ IsString,
+ Matches,
+ Max,
+ MaxLength,
+ Min,
+} from 'class-validator'
+import { Type } from 'class-transformer'
+
+import { PID_REGEX } from '../../common/constants'
+
+const SESSION_REPLAY_PRIVACY_MODES = ['total', 'normal', 'free-love'] as const
+
+export type SessionReplayPrivacyMode =
+ (typeof SESSION_REPLAY_PRIVACY_MODES)[number]
+
+export class SessionReplayStartDto {
+ @ApiProperty({ required: true, description: 'The project ID' })
+ @IsNotEmpty()
+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
+ pid: string
+
+ @ApiProperty({ required: true })
+ @IsString()
+ @MaxLength(80)
+ replayId: string
+
+ @ApiProperty({ enum: SESSION_REPLAY_PRIVACY_MODES, default: 'normal' })
+ @IsIn(SESSION_REPLAY_PRIVACY_MODES)
+ privacy: SessionReplayPrivacyMode
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(2048)
+ pg?: string
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(64)
+ lc?: string
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(80)
+ tz?: string
+
+ @IsOptional()
+ @IsString()
+ @MaxLength(256)
+ profileId?: string
+}
+
+export class SessionReplayChunkDto extends SessionReplayStartDto {
+ @Type(() => Number)
+ @IsInt()
+ @Min(0)
+ @Max(100000)
+ chunkIndex: number
+
+ @IsArray()
+ @ArrayMaxSize(1000)
+ @IsObject({ each: true })
+ events: Record<string, unknown>[]
+}
+
+export class GetSessionReplayDto {
+ @ApiProperty({ required: true, description: 'The project ID' })
+ @IsNotEmpty()
+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
+ pid: string
+
+ @ApiProperty()
+ @IsNotEmpty()
+ psid: string
+
+ @ApiProperty({ required: false })
+ @IsOptional()
+ @IsString()
+ @MaxLength(80)
+ replayId?: string
+}
diff --git a/backend/apps/cloud/src/analytics/session-replay-r2.service.ts b/backend/apps/cloud/src/analytics/session-replay-r2.service.ts
new file mode 100644
index 000000000..7479ee516
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/session-replay-r2.service.ts
@@ -0,0 +1,160 @@
+import crypto from 'crypto'
+import { Injectable } from '@nestjs/common'
+
+interface R2Config {
+ endpoint: string
+ bucket: string
+ accessKeyId: string
+ secretAccessKey: string
+}
+
+type HeaderMap = Record<string, string>
+
+const sha256Hex = (value: Buffer | string) =>
+ crypto.createHash('sha256').update(value).digest('hex')
+
+const hmac = (key: Buffer | string, value: string) =>
+ crypto.createHmac('sha256', key).update(value).digest()
+
+const encodeKeyPath = (key: string) =>
+ key.split('/').map(encodeURIComponent).join('/')
+
+@Injectable()
+export class SessionReplayR2Service {
+ private getConfig(): R2Config | null {
+ const accountId =
+ process.env.SESSION_REPLAY_R2_ACCOUNT_ID || process.env.R2_ACCOUNT_ID
+ const endpoint =
+ process.env.SESSION_REPLAY_R2_ENDPOINT ||
+ process.env.R2_ENDPOINT ||
+ (accountId ? `https://${accountId}.r2.cloudflarestorage.com` : '')
+ const bucket = process.env.SESSION_REPLAY_R2_BUCKET || process.env.R2_BUCKET
+ const accessKeyId =
+ process.env.SESSION_REPLAY_R2_ACCESS_KEY_ID ||
+ process.env.R2_ACCESS_KEY_ID
+ const secretAccessKey =
+ process.env.SESSION_REPLAY_R2_SECRET_ACCESS_KEY ||
+ process.env.R2_SECRET_ACCESS_KEY
+
+ if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) {
+ return null
+ }
+
+ return {
+ endpoint: endpoint.replace(/\/+$/, ''),
+ bucket,
+ accessKeyId,
+ secretAccessKey,
+ }
+ }
+
+ isConfigured(): boolean {
+ return Boolean(this.getConfig())
+ }
+
+ async putObject(
+ key: string,
+ body: Buffer,
+ contentType = 'application/json',
+ ): Promise<void> {
+ const response = await this.signedFetch('PUT', key, body, {
+ 'content-type': contentType,
+ })
+
+ if (!response.ok) {
+ throw new Error(`R2 PUT failed with status ${response.status}`)
+ }
+ }
+
+ async getObject(key: string): Promise<Buffer | null> {
+ const response = await this.signedFetch('GET', key)
+
+ if (response.status === 404) {
+ return null
+ }
+
+ if (!response.ok) {
+ throw new Error(`R2 GET failed with status ${response.status}`)
+ }
+
+ return Buffer.from(await response.arrayBuffer())
+ }
+
+ async deleteObject(key: string): Promise<void> {
+ const response = await this.signedFetch('DELETE', key)
+
+ if (!response.ok && response.status !== 404) {
+ throw new Error(`R2 DELETE failed with status ${response.status}`)
+ }
+ }
+
+ private async signedFetch(
+ method: 'PUT' | 'GET' | 'DELETE',
+ key: string,
+ body?: Buffer,
+ extraHeaders: HeaderMap = {},
+ ): Promise<Response> {
+ const config = this.getConfig()
+ if (!config) {
+ throw new Error('R2 session replay storage is not configured')
+ }
+
+ const payloadHash = sha256Hex(body || '')
+ const now = new Date()
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '')
+ const dateStamp = amzDate.slice(0, 8)
+ const url = new URL(
+ `${config.endpoint}/${config.bucket}/${encodeKeyPath(key)}`,
+ )
+
+ const headers: HeaderMap = {
+ host: url.host,
+ 'x-amz-content-sha256': payloadHash,
+ 'x-amz-date': amzDate,
+ ...extraHeaders,
+ }
+ const signedHeaderKeys = Object.keys(headers)
+ .map((header) => header.toLowerCase())
+ .sort()
+ const canonicalHeaders = signedHeaderKeys
+ .map((header) => `${header}:${headers[header].trim()}\n`)
+ .join('')
+ const signedHeaders = signedHeaderKeys.join(';')
+ const credentialScope = `${dateStamp}/auto/s3/aws4_request`
+ const canonicalRequest = [
+ method,
+ url.pathname,
+ '',
+ canonicalHeaders,
+ signedHeaders,
+ payloadHash,
+ ].join('\n')
+ const stringToSign = [
+ 'AWS4-HMAC-SHA256',
+ amzDate,
+ credentialScope,
+ sha256Hex(canonicalRequest),
+ ].join('\n')
+ const dateKey = hmac(`AWS4${config.secretAccessKey}`, dateStamp)
+ const regionKey = hmac(dateKey, 'auto')
+ const serviceKey = hmac(regionKey, 's3')
+ const signingKey = hmac(serviceKey, 'aws4_request')
+ const signature = crypto
+ .createHmac('sha256', signingKey)
+ .update(stringToSign)
+ .digest('hex')
+
+ headers.authorization = [
+ `AWS4-HMAC-SHA256 Credential=${config.accessKeyId}/${credentialScope}`,
+ `SignedHeaders=${signedHeaders}`,
+ `Signature=${signature}`,
+ ].join(', ')
+ const requestBody = body ? new Uint8Array(body) : undefined
+
+ return fetch(url, {
+ method,
+ headers,
+ body: requestBody,
+ })
+ }
+}
diff --git a/backend/apps/cloud/src/logger/logger.service.ts b/backend/apps/cloud/src/logger/logger.service.ts
index fc224839c..50aeb58a6 100644
--- a/backend/apps/cloud/src/logger/logger.service.ts
+++ b/backend/apps/cloud/src/logger/logger.service.ts
@@ -3,7 +3,7 @@ import { Logger } from '@nestjs/common'
import { isDevelopment } from '../common/constants'
export class AppLoggerService extends Logger {
- log(value, route, forceLog = false) {
+ log(value, route?: string, forceLog = false) {
if (isDevelopment || forceLog) {
Logger.log(value, route)
}
diff --git a/backend/apps/cloud/src/main.ts b/backend/apps/cloud/src/main.ts
index 47d577cd6..f376827f5 100644
--- a/backend/apps/cloud/src/main.ts
+++ b/backend/apps/cloud/src/main.ts
@@ -2,6 +2,7 @@ import './instrument'
import { NestFactory } from '@nestjs/core'
import { ValidationPipe, VersioningType } from '@nestjs/common'
+import { NestExpressApplication } from '@nestjs/platform-express'
import cookieParser from 'cookie-parser'
import express from 'express'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
@@ -13,9 +14,10 @@ import { validateLicense } from './common/license'
async function bootstrap() {
validateLicense()
- const app = await NestFactory.create(AppModule)
+ const app = await NestFactory.create<NestExpressApplication>(AppModule)
app.use(cookieParser())
+ app.useBodyParser('json', { limit: '1mb' })
app.useGlobalPipes(new ValidationPipe())
app.enableVersioning({
diff --git a/backend/apps/cloud/src/project/dto/update-project.dto.ts b/backend/apps/cloud/src/project/dto/update-project.dto.ts
index b3789b222..ede7fff04 100644
--- a/backend/apps/cloud/src/project/dto/update-project.dto.ts
+++ b/backend/apps/cloud/src/project/dto/update-project.dto.ts
@@ -56,4 +56,15 @@ export class UpdateProjectDto extends IntersectionType(
@IsIn(['manual', 'auto'])
@IsOptional()
captchaDifficultyMode?: 'manual' | 'auto'
+
+ @ApiProperty({
+ required: false,
+ description: 'Session replay retention in days.',
+ enum: [30, 90, 365, 1825],
+ default: 30,
+ })
+ @IsInt()
+ @IsIn([30, 90, 365, 1825])
+ @IsOptional()
+ sessionReplayRetentionDays?: number
}
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index 5acc2adf0..3f8d92803 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -193,6 +193,9 @@ export class Project {
@Column('boolean', { default: false })
revenueApiEnabled: boolean
+ @Column('int', { unsigned: true, default: 30 })
+ sessionReplayRetentionDays: number
+
@ApiProperty()
@Column('varchar', { nullable: true, default: null, length: 512 })
websiteUrl: string | null
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index d732edb75..ce5bec9f2 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -114,7 +114,10 @@ import { ProjectOrganisationDto } from './dto/project-organisation.dto'
import { trackCustom } from '../common/analytics'
import { PendingInvitationService } from '../pending-invitation/pending-invitation.service'
import { PendingInvitationType } from '../pending-invitation/pending-invitation.entity'
-import { PlanCode } from '../user/entities/user.entity'
+import {
+ PlanCode,
+ getSessionReplayRetentionEntitlement,
+} from '../user/entities/user.entity'
const PROJECTS_MAXIMUM = 50
const ORIGINS_ITEMS_MAXIMUM = 1000
@@ -1826,6 +1829,17 @@ export class ProjectController {
projectDTO.captchaDifficultyMode as Project['captchaDifficultyMode']
}
+ if (projectDTO.sessionReplayRetentionDays !== undefined) {
+ const maxRetention = getSessionReplayRetentionEntitlement(project.admin)
+ if (projectDTO.sessionReplayRetentionDays > maxRetention) {
+ throw new ForbiddenException(
+ 'Your plan does not include this session replay retention period',
+ )
+ }
+
+ project.sessionReplayRetentionDays = projectDTO.sessionReplayRetentionDays
+ }
+
if (projectDTO.name) {
project.name = _trim(projectDTO.name)
}
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index 7ae04cb80..e967284d5 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -191,6 +191,7 @@ export class ProjectService {
)
.leftJoinAndSelect('organisationMembers.user', 'organisationUser')
.select([
+ 'project.id',
'project.origins',
'project.active',
'project.public',
@@ -200,6 +201,7 @@ export class ProjectService {
'project.captchaSecretKey',
'project.captchaDifficulty',
'project.captchaDifficultyMode',
+ 'project.sessionReplayRetentionDays',
'project.passwordHash',
'project.isPasswordProtected',
'admin.id',
@@ -207,6 +209,7 @@ export class ProjectService {
'admin.isAccountBillingSuspended',
'admin.planCode',
'admin.planType',
+ 'admin.entitlementOverrides',
'organisation.id',
'organisationMembers.role',
'organisationMembers.confirmed',
@@ -278,6 +281,7 @@ export class ProjectService {
isAccountBillingSuspended: true,
planCode: true,
planType: true,
+ entitlementOverrides: true,
},
organisation: {
id: true,
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index 4c71c8497..16d10f5f9 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -2098,6 +2098,27 @@ export class TaskManagerService {
await this.userService.deleteRefreshTokensWhere(where)
}
+ @Cron(CronExpression.EVERY_DAY_AT_1AM)
+ async cleanupExpiredSessionReplays() {
+ if (!isPrimaryNode()) {
+ return
+ }
+
+ try {
+ const deleted = await this.analyticsService.cleanupExpiredSessionReplays()
+
+ if (deleted > 0) {
+ this.logger.log(
+ `[CRON WORKER](cleanupExpiredSessionReplays) Deleted ${deleted} expired replay chunks`,
+ )
+ }
+ } catch (reason) {
+ this.logger.error(
+ `[CRON WORKER](cleanupExpiredSessionReplays) Error occured: ${reason}`,
+ )
+ }
+ }
+
// Verify managed reverse proxy domains: resolve CNAME -> probe TLS to advance
// the row's status (waiting -> issuing -> live).
@Cron(CronExpression.EVERY_MINUTE)
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.ts
index 18925cbba..0c4df5307 100644
--- a/backend/apps/cloud/src/user/entities/user.entity.ts
+++ b/backend/apps/cloud/src/user/entities/user.entity.ts
@@ -81,7 +81,7 @@ const PLAN_TYPE_ENTITLEMENTS = {
teamMembers: 25,
organisations: 10,
apiRateLimitPerHour: 6000,
- sessionReplaysIncluded: 50000,
+ sessionReplaysIncluded: 'byEventTier',
},
[PlanType.enterprise]: {
websites: 'custom',
@@ -92,6 +92,21 @@ const PLAN_TYPE_ENTITLEMENTS = {
},
} as const
+const PLUS_SESSION_REPLAY_QUOTA: Partial<Record<PlanCode, number>> = {
+ [PlanCode['100k']]: 5000,
+ [PlanCode['200k']]: 10000,
+ [PlanCode['500k']]: 25000,
+ [PlanCode['1m']]: 50000,
+ [PlanCode['2m']]: 100000,
+ [PlanCode['5m']]: 250000,
+ [PlanCode['10m']]: 500000,
+ [PlanCode['15m']]: 750000,
+ [PlanCode['20m']]: 1000000,
+ [PlanCode['30m']]: 1500000,
+ [PlanCode['40m']]: 2000000,
+ [PlanCode['50m']]: 2500000,
+}
+
const PLAN_TYPE_RANK = {
[PlanType.standard]: 1,
[PlanType.plus]: 2,
@@ -170,6 +185,54 @@ export const getPlanTypeAccountLimitUpdates = (
return updates
}
+export const getSessionReplayQuota = (
+ user?: {
+ planCode?: PlanCode | null
+ planType?: PlanType | null
+ entitlementOverrides?: Record<string, unknown> | null
+ } | null,
+): number | 'custom' => {
+ const replayOverride = getNumericLimitOverride(
+ user?.entitlementOverrides,
+ 'sessionReplaysIncluded',
+ )
+
+ if (typeof replayOverride === 'number') {
+ return replayOverride
+ }
+
+ const effectivePlanType = getEffectivePlanType(user)
+ const entitlements = getPlanTypeEntitlements(effectivePlanType)
+
+ if (entitlements.sessionReplaysIncluded === 'custom') {
+ return 'custom'
+ }
+
+ if (entitlements.sessionReplaysIncluded === 'byEventTier') {
+ return PLUS_SESSION_REPLAY_QUOTA[user?.planCode || PlanCode.none] || 0
+ }
+
+ return entitlements.sessionReplaysIncluded
+}
+
+export const getSessionReplayRetentionEntitlement = (
+ user?: {
+ planType?: PlanType | null
+ entitlementOverrides?: Record<string, unknown> | null
+ } | null,
+): number => {
+ const override = getNumericLimitOverride(
+ user?.entitlementOverrides,
+ 'sessionReplayRetentionDays',
+ )
+
+ if (typeof override === 'number') {
+ return override
+ }
+
+ return getEffectivePlanType(user) === PlanType.enterprise ? 1825 : 30
+}
+
const planTypeHasFeature = (
planType: PlanType | null | undefined,
feature: PlanFeatureCode,
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 1947c91dc..fc298f65c 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -37,6 +37,7 @@ import {
getEffectivePlanType,
getPlanTypeEntitlements,
getPlanTypeAccountLimitUpdates,
+ getSessionReplayQuota,
DEFAULT_MAX_PROJECTS,
} from './entities/user.entity'
import { UserProfileDTO } from './dto/user.dto'
@@ -1316,10 +1317,6 @@ export class UserService {
entitlementOverrides,
'apiRateLimitPerHour',
)
- const replayOverride = numberOverride(
- entitlementOverrides,
- 'sessionReplaysIncluded',
- )
const includedWebsites =
websiteOverride ??
(typeof entitlements.websites === 'number'
@@ -1330,8 +1327,7 @@ export class UserService {
(typeof entitlements.apiRateLimitPerHour === 'number'
? entitlements.apiRateLimitPerHour
: user?.maxApiKeyRequestsPerHour)
- const sessionReplaysIncluded =
- replayOverride ?? entitlements.sessionReplaysIncluded
+ const sessionReplaysIncluded = getSessionReplayQuota(user)
const enhancedUser = {
...user,
diff --git a/backend/migrations/clickhouse/2026_06_03_session_replays.js b/backend/migrations/clickhouse/2026_06_03_session_replays.js
new file mode 100644
index 000000000..709aecd2b
--- /dev/null
+++ b/backend/migrations/clickhouse/2026_06_03_session_replays.js
@@ -0,0 +1,26 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `CREATE TABLE IF NOT EXISTS ${dbName}.session_replay_chunks
+ (
+ pid FixedString(12),
+ psid UInt64,
+ replayId String CODEC(ZSTD(3)),
+ chunkIndex UInt32,
+ objectKey String CODEC(ZSTD(3)),
+ privacyMode LowCardinality(String),
+ eventCount UInt32,
+ uncompressedBytes UInt32,
+ compressedBytes UInt32,
+ firstEventTimestamp Nullable(UInt64),
+ lastEventTimestamp Nullable(UInt64),
+ created DateTime('UTC') CODEC(Delta(4), LZ4),
+ expiresAt DateTime('UTC') CODEC(Delta(4), LZ4)
+ )
+ ENGINE = ReplacingMergeTree(created)
+ PARTITION BY toYYYYMM(created)
+ ORDER BY (pid, psid, replayId, chunkIndex)
+ TTL expiresAt;`,
+]
+
+queriesRunner(queries)
diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.js
index beb10a635..49c44b4d2 100644
--- a/backend/migrations/clickhouse/initialise_database.js
+++ b/backend/migrations/clickhouse/initialise_database.js
@@ -148,6 +148,27 @@ const CLICKHOUSE_INIT_QUERIES = [
ENGINE = ReplacingMergeTree(synced_at)
PARTITION BY toYYYYMM(created)
ORDER BY (pid, transaction_id);`,
+
+ `CREATE TABLE IF NOT EXISTS ${dbName}.session_replay_chunks
+ (
+ pid FixedString(12),
+ psid UInt64,
+ replayId String CODEC(ZSTD(3)),
+ chunkIndex UInt32,
+ objectKey String CODEC(ZSTD(3)),
+ privacyMode LowCardinality(String),
+ eventCount UInt32,
+ uncompressedBytes UInt32,
+ compressedBytes UInt32,
+ firstEventTimestamp Nullable(UInt64),
+ lastEventTimestamp Nullable(UInt64),
+ created DateTime('UTC') CODEC(Delta(4), LZ4),
+ expiresAt DateTime('UTC') CODEC(Delta(4), LZ4)
+ )
+ ENGINE = ReplacingMergeTree(created)
+ PARTITION BY toYYYYMM(created)
+ ORDER BY (pid, psid, replayId, chunkIndex)
+ TTL expiresAt;`,
]
const initialiseDatabase = async () => {
diff --git a/backend/migrations/mysql/2026_06_03_session_replays.sql b/backend/migrations/mysql/2026_06_03_session_replays.sql
new file mode 100644
index 000000000..2d2020855
--- /dev/null
+++ b/backend/migrations/mysql/2026_06_03_session_replays.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `project`
+ ADD COLUMN `sessionReplayRetentionDays` int unsigned NOT NULL DEFAULT 30;
diff --git a/packages/tracker-js/package-lock.json b/packages/tracker-js/package-lock.json
index 0806e8f3c..e69b0dfea 100644
--- a/packages/tracker-js/package-lock.json
+++ b/packages/tracker-js/package-lock.json
@@ -8,6 +8,9 @@
"name": "swetrix",
"version": "4.2.0",
"license": "MIT",
+ "dependencies": {
+ "rrweb": "2.0.0"
+ },
"devDependencies": {
"@rollup/plugin-commonjs": "^29.0.2",
"@rollup/plugin-node-resolve": "^16.0.3",
@@ -1722,6 +1725,18 @@
"win32"
]
},
+ "node_modules/@rrweb/types": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.0.tgz",
+ "integrity": "sha512-p76i3Bdm/cjb/6NGqmFj0LkGXqC2dXs70AwirgVAsE1ndIa00TJo48La5yobHLsBOk5bfRHy6Yd+9O9VFKhAwQ==",
+ "license": "MIT"
+ },
+ "node_modules/@rrweb/utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.0.tgz",
+ "integrity": "sha512-0Q9djyxlwG1fs1TxT7VnKtt33tHku6PENlUAKSXZg8QSSI6aUXdCNZkkBt3JAgbBYVrGhQsYrz+DkCdAXqxs1w==",
+ "license": "MIT"
+ },
"node_modules/@sinclair/typebox": {
"version": "0.34.49",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.49.tgz",
@@ -1805,6 +1820,12 @@
"@babel/types": "^7.28.2"
}
},
+ "node_modules/@types/css-font-loading-module": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/@types/css-font-loading-module/-/css-font-loading-module-0.0.7.tgz",
+ "integrity": "sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==",
+ "license": "MIT"
+ },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -2174,6 +2195,12 @@
"win32"
]
},
+ "node_modules/@xstate/fsm": {
+ "version": "1.6.5",
+ "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.6.5.tgz",
+ "integrity": "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==",
+ "license": "MIT"
+ },
"node_modules/acorn": {
"version": "8.14.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz",
@@ -2369,6 +2396,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/base64-arraybuffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
+ "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
"node_modules/baseline-browser-mapping": {
"version": "2.10.20",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.20.tgz",
@@ -4333,12 +4369,36 @@
"node": ">=16 || 14 >=14.17"
}
},
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true
},
+ "node_modules/nanoid": {
+ "version": "3.3.12",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
+ "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
"node_modules/napi-postinstall": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz",
@@ -4592,7 +4652,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
- "dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
@@ -4630,6 +4689,34 @@
"node": ">=8"
}
},
+ "node_modules/postcss": {
+ "version": "8.5.15",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
+ "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.12",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
"node_modules/pretty-format": {
"version": "30.3.0",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.3.0.tgz",
@@ -4891,6 +4978,31 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/rrdom": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.0.tgz",
+ "integrity": "sha512-Yv+T/IBngNEjhbRv6yJzKdbhgMOiRCV+UA3R0HOpx4yySc8vl4I11Xr5BxCYrnt00l7CGjHbFB9VULEvcg1u6w==",
+ "license": "MIT",
+ "dependencies": {
+ "rrweb-snapshot": "^2.0.0"
+ }
+ },
+ "node_modules/rrweb": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.0.tgz",
+ "integrity": "sha512-ID7NE8OdfAbxZKlTPc/EdL/8sLhTOVB1aZKoQ/M0peKGYB7dIDj0hsdJo+OVXfpiYMTtGzXnKfnMVUj4LnsrhQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@rrweb/types": "^2.0.0",
+ "@rrweb/utils": "^2.0.0",
+ "@types/css-font-loading-module": "0.0.7",
+ "@xstate/fsm": "^1.4.0",
+ "base64-arraybuffer": "^1.0.1",
+ "mitt": "^3.0.0",
+ "rrdom": "^2.0.0",
+ "rrweb-snapshot": "^2.0.0"
+ }
+ },
"node_modules/rrweb-cssom": {
"version": "0.8.0",
"resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
@@ -4898,6 +5010,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/rrweb-snapshot": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.0.tgz",
+ "integrity": "sha512-mDYvvHVXYUD6wZj2AGz5UuupnYnhrWUmF+Hm+haZtVPx8bK3hpAMpu7YjPAoHVluv6KZJNJvVb/6HeBKwXTAvA==",
+ "license": "MIT",
+ "dependencies": {
+ "postcss": "^8.4.38"
+ }
+ },
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -4997,6 +5118,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/source-map-support": {
"version": "0.5.21",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
diff --git a/packages/tracker-js/package.json b/packages/tracker-js/package.json
index 1d6d40f63..18a66052d 100644
--- a/packages/tracker-js/package.json
+++ b/packages/tracker-js/package.json
@@ -44,6 +44,9 @@
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
},
+ "dependencies": {
+ "rrweb": "2.0.0"
+ },
"devDependencies": {
"@rollup/plugin-commonjs": "^29.0.2",
"@rollup/plugin-node-resolve": "^16.0.3",
diff --git a/packages/tracker-js/rollup.config.mjs b/packages/tracker-js/rollup.config.mjs
index 59090f8d3..b0f37730b 100644
--- a/packages/tracker-js/rollup.config.mjs
+++ b/packages/tracker-js/rollup.config.mjs
@@ -3,9 +3,25 @@ import commonjs from '@rollup/plugin-commonjs'
import typescript from '@rollup/plugin-typescript'
import terser from '@rollup/plugin-terser'
import pkg from './package.json' with { type: 'json' }
+import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
+import { dirname, join } from 'node:path'
const require = createRequire(import.meta.url)
+const rrwebDistFile = 'rrweb.min.js'
+const rrwebPackageFile = 'rrweb.umd.min.cjs'
+const rrwebDistPath = join(dirname(require.resolve('rrweb')), rrwebPackageFile)
+
+const copyRrweb = () => ({
+ name: 'copy-rrweb',
+ generateBundle() {
+ this.emitFile({
+ type: 'asset',
+ fileName: rrwebDistFile,
+ source: readFileSync(rrwebDistPath),
+ })
+ },
+})
export default [
{
@@ -35,6 +51,7 @@ export default [
}),
nodeResolve(),
commonjs(),
+ copyRrweb(),
terser(),
],
},
diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.ts
index 253a0d968..a6a7b2175 100644
--- a/packages/tracker-js/src/Lib.ts
+++ b/packages/tracker-js/src/Lib.ts
@@ -14,6 +14,27 @@ import {
getPath,
} from './utils.js'
+type RrwebEvent = Record<string, unknown>
+
+type RrwebEmit = (event: RrwebEvent) => void
+
+interface RrwebRecordOptions {
+ emit?: RrwebEmit
+ [key: string]: unknown
+}
+
+interface RrwebGlobal {
+ record?: (options: RrwebRecordOptions) => (() => void) | undefined
+ Replayer?: unknown
+}
+
+declare global {
+ interface Window {
+ rrweb?: RrwebGlobal
+ __SWETRIX_RRWEB_LOADING__?: Promise<void>
+ }
+}
+
export interface LibOptions {
/**
* When set to `true`, localhost events will be sent to server.
@@ -39,6 +60,11 @@ export interface LibOptions {
* If set, it will be used for all pageviews and events unless overridden per-call.
*/
profileId?: string
+
+ /**
+ * Preload session replay recorder code. Recording only starts after calling startSessionReplay().
+ */
+ sessionReplay?: boolean | { rrwebUrl?: string }
}
export interface TrackEventOptions {
@@ -166,6 +192,20 @@ export interface ErrorActions {
stop: () => void
}
+export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+
+export interface SessionReplayOptions {
+ privacy?: SessionReplayPrivacy
+ rrweb?: RrwebRecordOptions
+ flushIntervalMs?: number
+ maxEventsPerChunk?: number
+}
+
+export interface SessionReplayActions {
+ stop: () => Promise<void>
+ flush: () => Promise<void>
+}
+
export interface PageData {
/** Current URL path. */
path: string
@@ -228,8 +268,17 @@ export const defaultActions = {
stop() {},
}
+export const defaultSessionReplayActions: SessionReplayActions = {
+ async stop() {},
+ async flush() {},
+}
+
const DEFAULT_API_HOST = 'https://api.swetrix.com/log'
const DEFAULT_API_BASE = 'https://api.swetrix.com'
+const DEFAULT_RRWEB_FILE = 'rrweb.min.js'
+const DEFAULT_RRWEB_URL = `https://swetrix.org/${DEFAULT_RRWEB_FILE}`
+const DEFAULT_SESSION_REPLAY_FLUSH_INTERVAL = 5000
+const DEFAULT_SESSION_REPLAY_MAX_EVENTS = 100
// Default cache duration: 5 minutes
const DEFAULT_CACHE_DURATION = 5 * 60 * 1000
@@ -242,11 +291,17 @@ export class Lib {
private activePage: string | null = null
private errorListenerExists = false
private cachedData: CachedData | null = null
+ private rrwebLoader: Promise<void> | null = null
+ private sessionReplayActions: SessionReplayActions | null = null
constructor(private projectID: string, private options?: LibOptions) {
this.trackPathChange = this.trackPathChange.bind(this)
this.heartbeat = this.heartbeat.bind(this)
this.captureError = this.captureError.bind(this)
+
+ if (options?.sessionReplay) {
+ void this.preloadSessionReplay().catch(() => undefined)
+ }
}
captureError(event: ErrorEvent): void {
@@ -370,7 +425,7 @@ export class Lib {
}
this.pageViewsOptions = options
- let interval: NodeJS.Timeout
+ let interval: ReturnType<typeof setInterval>
if (!options?.unique) {
interval = setInterval(this.trackPathChange, 2000)
@@ -707,6 +762,120 @@ export class Lib {
}
}
+ async startSessionReplay(
+ options: SessionReplayOptions = {},
+ ): Promise<SessionReplayActions> {
+ if (this.sessionReplayActions) {
+ return this.sessionReplayActions
+ }
+
+ if (!this.canTrack()) {
+ return defaultSessionReplayActions
+ }
+
+ try {
+ await this.preloadSessionReplay()
+ } catch {
+ return defaultSessionReplayActions
+ }
+
+ const rrweb = window.rrweb
+ if (!rrweb?.record) {
+ return defaultSessionReplayActions
+ }
+
+ const privacy = options.privacy || 'normal'
+ const replayId = this.createReplayId()
+ const started = await this.sendSessionReplayStart(replayId, privacy)
+
+ if (!started) {
+ return defaultSessionReplayActions
+ }
+
+ const flushIntervalMs =
+ typeof options.flushIntervalMs === 'number' && options.flushIntervalMs > 0
+ ? options.flushIntervalMs
+ : DEFAULT_SESSION_REPLAY_FLUSH_INTERVAL
+ const maxEventsPerChunk =
+ typeof options.maxEventsPerChunk === 'number' &&
+ options.maxEventsPerChunk > 0
+ ? Math.floor(options.maxEventsPerChunk)
+ : DEFAULT_SESSION_REPLAY_MAX_EVENTS
+
+ let chunkIndex = 0
+ let stopped = false
+ let events: RrwebEvent[] = []
+ let flushing = Promise.resolve()
+
+ const flush = async (useBeacon = false) => {
+ if (!events.length) return
+
+ const chunk = events
+ events = []
+ const currentChunkIndex = chunkIndex++
+
+ flushing = flushing
+ .catch(() => undefined)
+ .then(() =>
+ this.sendSessionReplayChunk(
+ replayId,
+ privacy,
+ currentChunkIndex,
+ chunk,
+ useBeacon,
+ ),
+ )
+
+ await flushing
+ }
+
+ const userEmit = options.rrweb?.emit
+ const recordOptions = this.getSessionReplayRecordOptions(
+ privacy,
+ options.rrweb,
+ (event) => {
+ try {
+ userEmit?.(event)
+ } catch {}
+
+ events.push(event)
+ if (events.length >= maxEventsPerChunk) {
+ void flush()
+ }
+ },
+ )
+
+ const stopRecording = rrweb.record(recordOptions)
+ const timer = setInterval(() => void flush(), flushIntervalMs)
+ const flushOnPageExit = () => void flush(true)
+ const flushOnHidden = () => {
+ if (document.visibilityState === 'hidden') {
+ void flush(true)
+ }
+ }
+
+ window.addEventListener('pagehide', flushOnPageExit)
+ document.addEventListener('visibilitychange', flushOnHidden)
+
+ this.sessionReplayActions = {
+ stop: async () => {
+ if (stopped) return
+ stopped = true
+ clearInterval(timer)
+ window.removeEventListener('pagehide', flushOnPageExit)
+ document.removeEventListener('visibilitychange', flushOnHidden)
+ stopRecording?.()
+ await flush()
+ this.sessionReplayActions = null
+ },
+ flush: async () => {
+ await flush()
+ },
+ }
+
+ return this.sessionReplayActions
+ }
+
/**
* Gets the API base URL (without /log suffix).
*/
@@ -815,6 +984,212 @@ export class Lib {
return true
}
+ private getSessionReplayUrl(): string {
+ const replayOption = this.options?.sessionReplay
+ if (
+ replayOption &&
+ typeof replayOption === 'object' &&
+ replayOption.rrwebUrl
+ ) {
+ return replayOption.rrwebUrl
+ }
+
+ return this.getDefaultSessionReplayUrl()
+ }
+
+ private getDefaultSessionReplayUrl(): string {
+ if (!isInBrowser()) {
+ return DEFAULT_RRWEB_URL
+ }
+
+ const trackerScript = Array.from(document.scripts).find((script) => {
+ if (!script.src) {
+ return false
+ }
+
+ try {
+ const { pathname } = new URL(script.src)
+ return /(^|\/)swetrix(\.min)?\.js$/i.test(pathname)
+ } catch {
+ return false
+ }
+ })
+
+ if (trackerScript?.src) {
+ return new URL(DEFAULT_RRWEB_FILE, trackerScript.src).toString()
+ }
+
+ return DEFAULT_RRWEB_URL
+ }
+
+ private preloadSessionReplay(): Promise<void> {
+ if (!isInBrowser()) {
+ return Promise.resolve()
+ }
+
+ if (window.rrweb?.record) {
+ return Promise.resolve()
+ }
+
+ if (this.rrwebLoader) {
+ return this.rrwebLoader
+ }
+
+ if (window.__SWETRIX_RRWEB_LOADING__) {
+ this.rrwebLoader = window.__SWETRIX_RRWEB_LOADING__
+ return this.rrwebLoader
+ }
+
+ this.rrwebLoader = new Promise<void>((resolve, reject) => {
+ const script = document.createElement('script')
+ script.async = true
+ script.src = this.getSessionReplayUrl()
+ script.crossOrigin = 'anonymous'
+ script.onload = () => resolve()
+ script.onerror = () => reject(new Error('Failed to load rrweb'))
+ document.head.appendChild(script)
+ })
+
+ window.__SWETRIX_RRWEB_LOADING__ = this.rrwebLoader
+
+ return this.rrwebLoader
+ }
+
+ private getSessionReplayRecordOptions(
+ privacy: SessionReplayPrivacy,
+ userOptions: RrwebRecordOptions | undefined,
+ emit: RrwebEmit,
+ ): RrwebRecordOptions {
+ const options: RrwebRecordOptions = {
+ ...(userOptions || {}),
+ emit,
+ }
+
+ const maskInputOptions =
+ typeof options.maskInputOptions === 'object' &&
+ options.maskInputOptions !== null
+ ? (options.maskInputOptions as Record<string, unknown>)
+ : {}
+
+ if (privacy === 'total') {
+ return {
+ ...options,
+ maskAllInputs: true,
+ maskTextSelector: '*',
+ blockSelector: this.mergeSelectors(
+ options.blockSelector,
+ 'img, picture, video, audio, canvas, svg',
+ ),
+ recordCanvas: false,
+ inlineImages: false,
+ emit,
+ }
+ }
+
+ if (privacy === 'normal') {
+ return {
+ ...options,
+ maskAllInputs: true,
+ emit,
+ }
+ }
+
+ return {
+ ...options,
+ maskInputOptions: {
+ ...maskInputOptions,
+ password: true,
+ },
+ emit,
+ }
+ }
+
+ private mergeSelectors(existing: unknown, required: string): string {
+ if (typeof existing === 'string' && existing.trim()) {
+ return `${existing}, ${required}`
+ }
+
+ return required
+ }
+
+ private createReplayId(): string {
+ if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
+ return crypto.randomUUID()
+ }
+
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
+ }
+
+ private async sendSessionReplayStart(
+ replayId: string,
+ privacy: SessionReplayPrivacy,
+ ): Promise<boolean> {
+ try {
+ const apiBase = this.getApiBase()
+ const response = await fetch(`${apiBase}/log/session-replay/start`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ pid: this.projectID,
+ replayId,
+ privacy,
+ pg:
+ this.activePage ||
+ getPath({
+ hash: this.pageViewsOptions?.hash,
+ search: this.pageViewsOptions?.search,
+ }),
+ lc: getLocale(),
+ tz: getTimezone(),
+ profileId: this.options?.profileId,
+ }),
+ })
+
+ return response.ok
+ } catch {
+ return false
+ }
+ }
+
+ private async sendSessionReplayChunk(
+ replayId: string,
+ privacy: SessionReplayPrivacy,
+ chunkIndex: number,
+ events: RrwebEvent[],
+ useBeacon: boolean,
+ ): Promise<void> {
+ const apiBase = this.getApiBase()
+ const url = `${apiBase}/log/session-replay/chunk`
+ const payload = JSON.stringify({
+ pid: this.projectID,
+ replayId,
+ privacy,
+ chunkIndex,
+ events,
+ })
+
+ if (useBeacon && typeof navigator.sendBeacon === 'function') {
+ const sent = navigator.sendBeacon(
+ url,
+ new Blob([payload], { type: 'application/json' }),
+ )
+ if (sent) return
+ }
+
+ try {
+ await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ keepalive: useBeacon,
+ body: payload,
+ })
+ } catch {}
+ }
+
private async sendRequest(path: string, body: object): Promise<void> {
const host = this.options?.apiURL || DEFAULT_API_HOST
await fetch(`${host}/${path}`, {
diff --git a/packages/tracker-js/src/index.ts b/packages/tracker-js/src/index.ts
index e6a84964a..1b6ae2527 100644
--- a/packages/tracker-js/src/index.ts
+++ b/packages/tracker-js/src/index.ts
@@ -11,6 +11,9 @@ import {
IPageViewPayload,
FeatureFlagsOptions,
ExperimentOptions,
+ SessionReplayOptions,
+ SessionReplayActions,
+ defaultSessionReplayActions,
} from './Lib.js'
export let LIB_INSTANCE: Lib | null = null
@@ -82,6 +85,16 @@ export function trackErrors(options?: ErrorOptions): ErrorActions {
return LIB_INSTANCE.trackErrors(options)
}
+export function startSessionReplay(
+ options?: SessionReplayOptions,
+): Promise<SessionReplayActions> {
+ if (!LIB_INSTANCE) {
+ return Promise.resolve(defaultSessionReplayActions)
+ }
+
+ return LIB_INSTANCE.startSessionReplay(options)
+}
+
/**
* This function is used to manually track an error event.
* It's useful if you want to track specific errors in your application.
diff --git a/packages/tracker-js/tests/sessionReplay.test.ts b/packages/tracker-js/tests/sessionReplay.test.ts
new file mode 100644
index 000000000..bc569373b
--- /dev/null
+++ b/packages/tracker-js/tests/sessionReplay.test.ts
@@ -0,0 +1,244 @@
+/// <reference types="jest" />
+
+import { Lib } from '../src/Lib'
+import { setLocation } from './testUtils'
+
+const PROJECT_ID = 'test-project-id'
+const RRWEB_URL = 'https://swetrix.org/rrweb.min.js'
+const SIBLING_RRWEB_URL = 'https://cdn.swetrix.test/assets/rrweb.min.js'
+const LOCAL_RRWEB_URL = 'http://localhost:8080/dist/rrweb.min.js'
+
+const loadTracker = async () => {
+ jest.resetModules()
+ return import('../src/index')
+}
+
+const resetReplayGlobals = () => {
+ delete (window as any).rrweb
+ delete (window as any).__SWETRIX_RRWEB_LOADING__
+ document.head.innerHTML = ''
+ document.body.innerHTML = ''
+}
+
+const resolveRrwebScript = (
+ record: jest.Mock,
+): { recordOptions: () => any } => {
+ let options: any
+ ;(window as any).rrweb = {
+ record: jest.fn((recordOptions) => {
+ options = recordOptions
+ return jest.fn()
+ }),
+ }
+
+ const script = document.querySelector<HTMLScriptElement>(
+ `script[src="${RRWEB_URL}"]`,
+ )
+ expect(script).toBeTruthy()
+ ;(window as any).rrweb.record = record
+ script!.dispatchEvent(new Event('load'))
+
+ return { recordOptions: () => options }
+}
+
+describe('Session replay tracking', () => {
+ let fetchMock: jest.Mock
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ jest.useRealTimers()
+ resetReplayGlobals()
+ setLocation({ hostname: 'example.com', pathname: '/checkout' })
+
+ Object.defineProperty(navigator, 'doNotTrack', {
+ value: null,
+ writable: true,
+ configurable: true,
+ })
+
+ fetchMock = jest.fn().mockResolvedValue({ ok: true })
+ Object.defineProperty(globalThis, 'fetch', {
+ value: fetchMock,
+ writable: true,
+ configurable: true,
+ })
+ })
+
+ test('init with sessionReplay preloads rrweb but does not record', async () => {
+ const { init } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true, sessionReplay: true })
+
+ const script = document.querySelector<HTMLScriptElement>(
+ `script[src="${RRWEB_URL}"]`,
+ )
+ expect(script).toBeTruthy()
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ test('session replay script defaults to the loaded tracker script directory', async () => {
+ const script = document.createElement('script')
+ script.src = 'https://cdn.swetrix.test/assets/swetrix.js'
+ document.head.appendChild(script)
+
+ const { init } = await loadTracker()
+ init(PROJECT_ID, { devMode: true, sessionReplay: true })
+
+ expect(
+ document.querySelector<HTMLScriptElement>(
+ `script[src="${SIBLING_RRWEB_URL}"]`,
+ ),
+ ).toBeTruthy()
+ })
+
+ test('session replay script resolves beside a localhost tracker build', async () => {
+ const script = document.createElement('script')
+ script.src = 'http://localhost:8080/dist/swetrix.js'
+ document.head.appendChild(script)
+
+ const { init } = await loadTracker()
+ init(PROJECT_ID, { devMode: true, sessionReplay: true })
+
+ expect(
+ document.querySelector<HTMLScriptElement>(
+ `script[src="${LOCAL_RRWEB_URL}"]`,
+ ),
+ ).toBeTruthy()
+ })
+
+ test('startSessionReplay loads rrweb, records events, and flushes chunks', async () => {
+ const record = jest.fn((options) => {
+ ;(record as any).options = options
+ return jest.fn()
+ })
+ const { init, startSessionReplay } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true })
+ const startPromise = startSessionReplay({
+ flushIntervalMs: 60_000,
+ maxEventsPerChunk: 2,
+ })
+ resolveRrwebScript(record)
+
+ const actions = await startPromise
+ const recordOptions = (record as any).options
+ recordOptions.emit({ type: 2, timestamp: 100 })
+ recordOptions.emit({ type: 3, timestamp: 200 })
+
+ await actions.flush()
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.swetrix.com/log/session-replay/start',
+ expect.objectContaining({ method: 'POST' }),
+ )
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.swetrix.com/log/session-replay/chunk',
+ expect.objectContaining({
+ method: 'POST',
+ body: expect.stringContaining('"chunkIndex":0'),
+ }),
+ )
+
+ await actions.stop()
+ })
+
+ test('privacy modes map to rrweb options and keep internal emit', () => {
+ const lib = new Lib(PROJECT_ID, { devMode: true })
+ const emit = jest.fn()
+
+ const total = (lib as any).getSessionReplayRecordOptions(
+ 'total',
+ { blockSelector: '.secret', emit: jest.fn() },
+ emit,
+ )
+ expect(total.maskAllInputs).toBe(true)
+ expect(total.maskTextSelector).toBe('*')
+ expect(total.blockSelector).toContain('.secret')
+ expect(total.blockSelector).toContain('img')
+ expect(total.recordCanvas).toBe(false)
+ expect(total.inlineImages).toBe(false)
+ expect(total.emit).toBe(emit)
+
+ const normal = (lib as any).getSessionReplayRecordOptions(
+ 'normal',
+ {},
+ emit,
+ )
+ expect(normal.maskAllInputs).toBe(true)
+ expect(normal.emit).toBe(emit)
+
+ const freeLove = (lib as any).getSessionReplayRecordOptions(
+ 'free-love',
+ { maskInputOptions: { email: false } },
+ emit,
+ )
+ expect(freeLove.maskInputOptions).toEqual({
+ email: false,
+ password: true,
+ })
+ expect(freeLove.emit).toBe(emit)
+ })
+
+ test('user rrweb emit is composed with Swetrix uploads', async () => {
+ const record = jest.fn((options) => {
+ ;(record as any).options = options
+ return jest.fn()
+ })
+ const userEmit = jest.fn()
+ const { init, startSessionReplay } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true })
+ const startPromise = startSessionReplay({
+ rrweb: { emit: userEmit, maskAllInputs: true },
+ })
+ resolveRrwebScript(record)
+
+ const actions = await startPromise
+ const event = { type: 2, timestamp: 300 }
+ ;(record as any).options.emit(event)
+ await actions.flush()
+
+ expect(userEmit).toHaveBeenCalledWith(event)
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.swetrix.com/log/session-replay/chunk',
+ expect.objectContaining({
+ body: expect.stringContaining('"timestamp":300'),
+ }),
+ )
+
+ await actions.stop()
+ })
+
+ test('DNT and disabled tracking return no-op controls without uploading', async () => {
+ Object.defineProperty(navigator, 'doNotTrack', {
+ value: '1',
+ writable: true,
+ configurable: true,
+ })
+
+ const { init, startSessionReplay } = await loadTracker()
+ init(PROJECT_ID, { devMode: true, respectDNT: true })
+
+ const actions = await startSessionReplay()
+ await actions.flush()
+ await actions.stop()
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+
+ resetReplayGlobals()
+ Object.defineProperty(navigator, 'doNotTrack', {
+ value: null,
+ writable: true,
+ configurable: true,
+ })
+
+ const disabledModule = await loadTracker()
+ disabledModule.init(PROJECT_ID, { devMode: true, disabled: true })
+ const disabledActions = await disabledModule.startSessionReplay()
+ await disabledActions.flush()
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+ })
+})
diff --git a/packages/tracker-js/tsconfig.esnext.json b/packages/tracker-js/tsconfig.esnext.json
index de1bca9a9..143a535a1 100644
--- a/packages/tracker-js/tsconfig.esnext.json
+++ b/packages/tracker-js/tsconfig.esnext.json
@@ -8,7 +8,7 @@
"sourceMap": true,
"declaration": true,
"outDir": "dist/esnext",
- "typeRoots": ["node_modules/@types"]
+ "types": []
},
"include": ["src"]
}
diff --git a/packages/tracker-js/tsconfig.json b/packages/tracker-js/tsconfig.json
index a7e21f182..8df177773 100644
--- a/packages/tracker-js/tsconfig.json
+++ b/packages/tracker-js/tsconfig.json
@@ -7,7 +7,8 @@
"strict": true,
"sourceMap": true,
"declaration": false,
- "allowSyntheticDefaultImports": true
+ "allowSyntheticDefaultImports": true,
+ "types": []
},
"include": ["src"]
}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 13523244b..4e390a841 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -983,6 +983,9 @@ interface Session {
profileId: string | null
isIdentified: 1 | 0
isFirstSession: 1 | 0
+ hasReplay?: 1 | 0
+ replayDuration?: number | null
+ replayExpiresAt?: string | null
}
export interface SessionsResponse {
@@ -1126,6 +1129,23 @@ interface PageflowItem {
currency?: string
}
+export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+
+export interface SessionReplayMetadata {
+ hasReplay: boolean
+ replayId: string
+ privacyMode: SessionReplayPrivacy
+ chunkCount: number
+ eventCount: number
+ replayDuration: number
+ replayExpiresAt: string
+}
+
+export interface SessionReplayResponse {
+ replay: SessionReplayMetadata | null
+ events: Record<string, unknown>[]
+}
+
export interface SessionDetailsResponse {
details: {
psid: string
@@ -1164,6 +1184,7 @@ export interface SessionDetailsResponse {
}
pages?: PageflowItem[]
timeBucket?: string
+ replay?: SessionReplayMetadata | null
}
export async function getSessionServer(
@@ -1193,6 +1214,37 @@ export async function getSessionServer(
)
}
+export async function getSessionReplayServer(
+ request: Request,
+ pid: string,
+ psid: string,
+ replayId?: string,
+ password?: string,
+): Promise<ServerFetchResult<SessionReplayResponse>> {
+ const queryParams = new URLSearchParams({
+ pid,
+ psid,
+ })
+
+ if (replayId) {
+ queryParams.append('replayId', replayId)
+ }
+
+ const headers: Record<string, string> = {}
+ if (password) {
+ headers['x-password'] = password
+ }
+
+ return serverFetch<SessionReplayResponse>(
+ request,
+ `log/session-replay?${queryParams.toString()}`,
+ {
+ headers,
+ timeoutMs: 30000,
+ },
+ )
+}
+
interface SwetrixError {
eid: string
name: string
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index db8985df8..b25c732e6 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,
+ SessionReplayResponse,
ErrorsResponse,
FeatureFlagStats,
FeatureFlagProfilesResponse,
@@ -102,6 +103,41 @@ export function useSessionsProxy() {
return { fetchSessions, data, error, isLoading }
}
+export function useSessionReplayProxy() {
+ const [data, setData] = useState<SessionReplayResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchSessionReplay = useCallback(
+ async (projectId: string, psid: string, replayId?: string) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<SessionReplayResponse>({
+ action: 'getSessionReplay',
+ projectId,
+ psid,
+ replayId,
+ params: {},
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Unknown error'
+ setError(message)
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
+
+ return { fetchSessionReplay, data, error, isLoading }
+}
+
export function useErrorsProxy() {
const [data, setData] = useState<ErrorsResponse | null>(null)
const [error, setError] = useState<string | null>(null)
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 7ffcefb39..37f97c449 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -85,6 +85,18 @@ export interface SwetrixError {
sessions: number
}
+export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+
+export interface SessionReplayMetadata {
+ hasReplay: boolean
+ replayId: string
+ privacyMode: SessionReplayPrivacy
+ chunkCount: number
+ eventCount: number
+ replayDuration: number
+ replayExpiresAt: string
+}
+
export interface Session {
psid: string
cc: string | null
@@ -105,6 +117,9 @@ export interface Session {
profileId: string | null
isIdentified: 1 | 0
isFirstSession: 1 | 0
+ hasReplay?: 1 | 0
+ replayDuration?: number | null
+ replayExpiresAt?: string | null
}
export interface SessionDetails {
@@ -252,6 +267,7 @@ export interface Project {
isErrorDataExists: boolean
isCaptchaDataExists: boolean
featureAccess?: ProjectFeatureAccess
+ sessionReplayRetentionDays?: number
botsProtectionLevel: 'off' | 'basic' | 'strict'
role?: Role
gscPropertyUri?: string | null
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index e0351873e..54b67dbcc 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -25,6 +25,7 @@ import {
DownloadIcon,
BellRingingIcon,
GlobeIcon,
+ VideoCameraIcon,
} from '@phosphor-icons/react'
import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -69,6 +70,7 @@ import AccessSettings from './tabs/AccessSettings'
import DangerZone from './tabs/DangerZone'
import General from './tabs/General'
import Revenue from './tabs/Revenue'
+import SessionReplays from './tabs/SessionReplays'
import Shields from './tabs/Shields'
import ProjectAlerts from './Alerts/ProjectAlertsView'
import NotificationChannels from '~/components/NotificationChannels/NotificationChannels'
@@ -364,6 +366,7 @@ const getFormFromProject = (project: Project): Form => ({
brandKeywords: project.brandKeywords?.join(', ') || '',
captchaDifficulty: project.captchaDifficulty || 4,
captchaDifficultyMode: project.captchaDifficultyMode || 'manual',
+ sessionReplayRetentionDays: project.sessionReplayRetentionDays || 30,
})
const normaliseProjectAutosaveValue = (value: unknown) =>
@@ -390,7 +393,10 @@ const buildProjectAutosaveFormData = (updates: Partial<Form>) => {
return
}
- if (field === 'captchaDifficulty') {
+ if (
+ field === 'captchaDifficulty' ||
+ field === 'sessionReplayRetentionDays'
+ ) {
formData.set(field, String(value))
return
}
@@ -434,6 +440,7 @@ const ProjectSettings = () => {
websiteUrl?: string
transferEmail?: string
email?: string
+ sessionReplayRetentionDays?: string
}>({})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [showDelete, setShowDelete] = useState(false)
@@ -473,6 +480,7 @@ const ProjectSettings = () => {
| 'alerts'
| 'channels'
| 'revenue'
+ | 'sessionReplays'
| 'emails'
| 'people'
| 'annotations'
@@ -548,6 +556,14 @@ const ProjectSettings = () => {
iconColor: 'text-green-500',
visible: !isSelfhosted,
},
+ {
+ id: 'sessionReplays',
+ label: t('project.settings.tabs.sessionReplays'),
+ description: t('project.settings.tabs.sessionReplaysDesc'),
+ icon: VideoCameraIcon,
+ iconColor: 'text-violet-500',
+ visible: !isSelfhosted,
+ },
{
id: 'emails',
label: t('project.settings.tabs.emails'),
@@ -601,6 +617,17 @@ const ProjectSettings = () => {
[t, project?.role],
)
+ const sessionReplayMaxRetentionDays = useMemo(() => {
+ const override = user?.entitlementOverrides?.sessionReplayRetentionDays
+ if (typeof override === 'number') {
+ return override
+ }
+ if (user?.effectivePlanType === 'enterprise') {
+ return 1825
+ }
+ return 30
+ }, [user?.effectivePlanType, user?.entitlementOverrides])
+
const activeTab = useMemo<SettingsTab>(() => {
const tab = searchParams.get('tab') as SettingsTab
const allowed = new Set(tabs.map((t) => t.id as SettingsTab))
@@ -1453,6 +1480,26 @@ const ProjectSettings = () => {
<ProxyDomainsTab projectId={id} />
</>
) : null}
+ {activeTab === 'sessionReplays' && activeTabConfig ? (
+ <>
+ <TabHeader
+ icon={activeTabConfig.icon}
+ label={activeTabConfig.label}
+ description={activeTabConfig.description}
+ iconColorClass={activeTabConfig.iconColor}
+ />
+ <SessionReplays
+ retentionDays={form.sessionReplayRetentionDays || 30}
+ maxRetentionDays={sessionReplayMaxRetentionDays}
+ onRetentionChange={(days) =>
+ handleFieldAutosave(
+ { sessionReplayRetentionDays: days },
+ 'project.settings.autosave.sessionReplayRetention',
+ )
+ }
+ />
+ </>
+ ) : null}
{activeTab === 'integrations' && activeTabConfig ? (
<div>
diff --git a/web/app/pages/Project/Settings/SettingsSidebar.tsx b/web/app/pages/Project/Settings/SettingsSidebar.tsx
index 2e0e31fc3..48437b276 100644
--- a/web/app/pages/Project/Settings/SettingsSidebar.tsx
+++ b/web/app/pages/Project/Settings/SettingsSidebar.tsx
@@ -213,7 +213,12 @@ const SettingsSidebar = <TabId extends string>({
{
id: 'data',
label: t('project.settings.sidebarGroups.data'),
- tabIds: ['annotations', 'revenue', 'import'] as TabId[],
+ tabIds: [
+ 'annotations',
+ 'revenue',
+ 'sessionReplays',
+ 'import',
+ ] as TabId[],
},
{
id: 'integrations',
diff --git a/web/app/pages/Project/Settings/tabs/SessionReplays.tsx b/web/app/pages/Project/Settings/tabs/SessionReplays.tsx
new file mode 100644
index 000000000..4d69970b0
--- /dev/null
+++ b/web/app/pages/Project/Settings/tabs/SessionReplays.tsx
@@ -0,0 +1,115 @@
+import { LockIcon } from '@phosphor-icons/react'
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+
+import Button from '~/ui/Button'
+import { Text } from '~/ui/Text'
+import Tooltip from '~/ui/Tooltip'
+import { cn } from '~/utils/generic'
+import routes from '~/utils/routes'
+
+const RETENTION_OPTIONS = [30, 90, 365, 1825] as const
+
+interface SessionReplaysProps {
+ retentionDays: number
+ maxRetentionDays: number
+ onRetentionChange: (days: number) => void
+}
+
+const SessionReplays = ({
+ retentionDays,
+ maxRetentionDays,
+ onRetentionChange,
+}: SessionReplaysProps) => {
+ const { t } = useTranslation('common')
+ const selectedRetention = RETENTION_OPTIONS.includes(retentionDays as any)
+ ? retentionDays
+ : 30
+ const hasLockedOptions = useMemo(
+ () => RETENTION_OPTIONS.some((days) => days > maxRetentionDays),
+ [maxRetentionDays],
+ )
+
+ return (
+ <div className='max-w-3xl'>
+ <div>
+ <Text as='h3' size='lg' weight='semibold'>
+ {t('project.settings.sessionReplays.retentionTitle')}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-1 max-w-2xl'>
+ {t('project.settings.sessionReplays.retentionDescription')}
+ </Text>
+ </div>
+
+ <div
+ role='radiogroup'
+ aria-label={t('project.settings.sessionReplays.retentionLabel')}
+ className='mt-5 grid w-full max-w-2xl grid-cols-2 gap-1 rounded-lg border border-gray-200 bg-white p-1 sm:grid-cols-4 dark:border-slate-800 dark:bg-slate-950'
+ >
+ {RETENTION_OPTIONS.map((days) => {
+ const allowed = days <= maxRetentionDays
+ const active = selectedRetention === days
+ const label = t(`project.settings.sessionReplays.retention.${days}`)
+ const className = cn(
+ 'flex min-h-14 items-center justify-center rounded-md px-3 py-2 text-center text-sm font-medium transition-colors',
+ {
+ 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-950':
+ active && allowed,
+ 'text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-900':
+ !active && allowed,
+ 'cursor-not-allowed text-gray-400 dark:text-slate-600': !allowed,
+ },
+ )
+
+ if (!allowed) {
+ return (
+ <Tooltip
+ key={days}
+ text={t('project.settings.sessionReplays.upgradeRequired')}
+ tooltipNode={
+ <span className={className}>
+ <span>{label}</span>
+ <LockIcon className='ml-1.5 size-3.5' />
+ </span>
+ }
+ />
+ )
+ }
+
+ return (
+ <label key={days} className={className}>
+ <input
+ type='radio'
+ className='sr-only'
+ aria-label={label}
+ checked={active}
+ onChange={() => onRetentionChange(days)}
+ />
+ {label}
+ </label>
+ )
+ })}
+ </div>
+
+ <Text as='p' size='xs' colour='secondary' className='mt-3 max-w-2xl'>
+ {t('project.settings.sessionReplays.retentionHint')}
+ </Text>
+
+ {hasLockedOptions ? (
+ <div className='mt-6 rounded-lg border border-gray-200 bg-gray-50 p-4 dark:border-slate-800 dark:bg-slate-900/30'>
+ <Text as='h4' size='base' weight='semibold'>
+ {t('project.settings.sessionReplays.upgradeTitle')}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-1'>
+ {t('project.settings.sessionReplays.upgradeDescription')}
+ </Text>
+ <Button to={routes.billing_choose_plan} className='mt-4'>
+ {t('project.settings.sessionReplays.upgradeCta')}
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+export default SessionReplays
diff --git a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
index f65d5a6e9..023227a2c 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
@@ -7,21 +7,26 @@ import {
GlobeIcon,
ClockIcon,
LinkIcon,
+ PlayIcon,
UserIcon,
SignInIcon,
} from '@phosphor-icons/react'
-import { useMemo, useState } from 'react'
+import { lazy, Suspense, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from '~/ui/Link'
import { BrowserIcon, OSIcon } from '../SharedIcons'
import { InfoRow, PanelSection } from '../components/DetailPanels'
import { PROJECT_TABS } from '~/lib/constants'
-import { SessionDetails as SessionDetailsType } from '~/lib/models/Project'
+import {
+ SessionDetails as SessionDetailsType,
+ SessionReplayMetadata,
+} from '~/lib/models/Project'
import { BackButton } from '~/pages/Project/View/components/BackButton'
import { useViewProjectContext } from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
+import Button from '~/ui/Button'
import PulsatingCircle from '~/ui/icons/PulsatingCircle'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
@@ -41,6 +46,8 @@ import { SessionChart } from './SessionChart'
dayjs.extend(utc)
+const SessionReplayModal = lazy(() => import('./SessionReplayModal'))
+
interface PageflowItem {
type: 'pageview' | 'event' | 'error' | 'sale' | 'refund'
value: string
@@ -63,6 +70,7 @@ interface SessionDetailViewProps {
timeBucket?: string
sessionStart?: string
lastActivity?: string
+ replay?: SessionReplayMetadata | null
} | null
sessionId?: string | null
sessionLoading: boolean
@@ -164,6 +172,7 @@ export const SessionDetailView = ({
const [zoomedTimeRange, setZoomedTimeRange] = useState<[Date, Date] | null>(
null,
)
+ const [isReplayOpen, setIsReplayOpen] = useState(false)
const isTouchDevice = useMemo(() => {
if (typeof window === 'undefined') return false
@@ -603,6 +612,17 @@ export const SessionDetailView = ({
</Text>
</Link>
) : null}
+
+ {activeSession.replay?.hasReplay && sessionId ? (
+ <Button
+ type='button'
+ className='mt-2 w-full justify-center gap-2'
+ onClick={() => setIsReplayOpen(true)}
+ >
+ <PlayIcon className='size-4' />
+ {t('project.watchReplay')}
+ </Button>
+ ) : null}
</div>
<PanelSection title={t('project.sessionInfo')}>
@@ -696,6 +716,18 @@ export const SessionDetailView = ({
) : null}
</div>
</aside>
+
+ {activeSession.replay?.hasReplay && sessionId ? (
+ <Suspense fallback={null}>
+ <SessionReplayModal
+ isOpen={isReplayOpen}
+ onClose={() => setIsReplayOpen(false)}
+ projectId={projectId}
+ psid={sessionId}
+ replay={activeSession.replay}
+ />
+ </Suspense>
+ ) : null}
</div>
)
}
diff --git a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
new file mode 100644
index 000000000..c55ab7dd6
--- /dev/null
+++ b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx
@@ -0,0 +1,826 @@
+import {
+ Dialog,
+ DialogBackdrop,
+ DialogPanel,
+ DialogTitle,
+} from '@headlessui/react'
+import {
+ ArrowsInIcon,
+ ArrowsOutIcon,
+ CameraIcon,
+ CaretRightIcon,
+ CursorClickIcon,
+ FastForwardIcon,
+ ListBulletsIcon,
+ PauseIcon,
+ PlayIcon,
+ RewindIcon,
+ TextTIcon,
+ WarningCircleIcon,
+ XIcon,
+} from '@phosphor-icons/react'
+import type { TFunction } from 'i18next'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Replayer } from 'dom-player'
+import type { eventWithTime } from 'dom-player'
+import './replayPlayer.css'
+import { toast } from 'sonner'
+
+import type {
+ SessionReplayMetadata,
+ SessionReplayResponse,
+} from '~/api/api.server'
+import { useSessionReplayProxy } from '~/hooks/useAnalyticsProxy'
+import Button from '~/ui/Button'
+import Loader from '~/ui/Loader'
+import { Text } from '~/ui/Text'
+import Tooltip from '~/ui/Tooltip'
+import { cn, getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
+
+const SPEEDS = [0.5, 1, 1.5, 2, 4]
+const EVENT_FULL_SNAPSHOT = 2
+const EVENT_INCREMENTAL = 3
+const EVENT_META = 4
+const SOURCE_MUTATION = 0
+const SOURCE_MOUSE_INTERACTION = 2
+const SOURCE_SCROLL = 3
+const SOURCE_VIEWPORT_RESIZE = 4
+const SOURCE_INPUT = 5
+const MUTATION_GROUP_MS = 1500
+
+type ReplayEvent = Omit<eventWithTime, 'data'> & {
+ data?: Record<string, any>
+}
+
+interface TimelineStep {
+ id: string
+ offset: number
+ label: string
+ detail?: string
+ kind:
+ | 'navigation'
+ | 'snapshot'
+ | 'click'
+ | 'scroll'
+ | 'input'
+ | 'resize'
+ | 'mutation'
+}
+
+interface SessionReplayModalProps {
+ isOpen: boolean
+ onClose: () => void
+ projectId: string
+ psid: string
+ replay?: SessionReplayMetadata | null
+}
+
+const getTimestamp = (event?: ReplayEvent) =>
+ typeof event?.timestamp === 'number' ? event.timestamp : 0
+
+const formatReplayTime = (ms: number) => {
+ const seconds = Math.max(0, Math.floor(ms / 1000))
+ const minutes = Math.floor(seconds / 60)
+ const rest = seconds % 60
+ return `${minutes}:${String(rest).padStart(2, '0')}`
+}
+
+const getEventDetail = (event: ReplayEvent) => {
+ const href = event.data?.href
+ if (typeof href === 'string') {
+ try {
+ const url = new URL(href)
+ return `${url.pathname}${url.search}`
+ } catch {
+ return href
+ }
+ }
+
+ const text = event.data?.text || event.data?.value
+ if (typeof text === 'string') {
+ return text.length > 48 ? `${text.slice(0, 48)}...` : text
+ }
+
+ return undefined
+}
+
+const buildTimelineSteps = (
+ events: ReplayEvent[],
+ t: TFunction,
+): TimelineStep[] => {
+ const firstTimestamp = getTimestamp(events[0])
+ const steps: TimelineStep[] = []
+ let mutationGroup: TimelineStep | null = null
+ let mutationCount = 0
+
+ const pushMutationGroup = () => {
+ if (!mutationGroup) return
+ steps.push({
+ ...mutationGroup,
+ detail:
+ mutationCount > 1
+ ? t('project.sessionReplay.timeline.mutationsCount', {
+ count: mutationCount,
+ })
+ : mutationGroup.detail,
+ })
+ mutationGroup = null
+ mutationCount = 0
+ }
+
+ events.forEach((event, index) => {
+ const timestamp = getTimestamp(event)
+ const offset = Math.max(0, timestamp - firstTimestamp)
+ const source = event.data?.source
+
+ if (
+ event.type !== EVENT_INCREMENTAL ||
+ source !== SOURCE_MUTATION ||
+ !mutationGroup ||
+ offset - mutationGroup.offset > MUTATION_GROUP_MS
+ ) {
+ pushMutationGroup()
+ }
+
+ if (event.type === EVENT_META) {
+ steps.push({
+ id: `${index}-navigation`,
+ offset,
+ kind: 'navigation',
+ label: t('project.sessionReplay.timeline.navigation'),
+ detail: getEventDetail(event),
+ })
+ return
+ }
+
+ if (event.type === EVENT_FULL_SNAPSHOT) {
+ steps.push({
+ id: `${index}-snapshot`,
+ offset,
+ kind: 'snapshot',
+ label: t('project.sessionReplay.timeline.fullSnapshot'),
+ })
+ return
+ }
+
+ if (event.type !== EVENT_INCREMENTAL) {
+ return
+ }
+
+ if (source === SOURCE_MUTATION) {
+ mutationGroup = {
+ id: `${index}-mutation`,
+ offset,
+ kind: 'mutation',
+ label: t('project.sessionReplay.timeline.mutations'),
+ }
+ mutationCount += 1
+ return
+ }
+
+ if (source === SOURCE_MOUSE_INTERACTION) {
+ steps.push({
+ id: `${index}-click`,
+ offset,
+ kind: 'click',
+ label: t('project.sessionReplay.timeline.click'),
+ })
+ return
+ }
+
+ if (source === SOURCE_SCROLL) {
+ steps.push({
+ id: `${index}-scroll`,
+ offset,
+ kind: 'scroll',
+ label: t('project.sessionReplay.timeline.scroll'),
+ })
+ return
+ }
+
+ if (source === SOURCE_INPUT) {
+ steps.push({
+ id: `${index}-input`,
+ offset,
+ kind: 'input',
+ label: t('project.sessionReplay.timeline.input'),
+ detail: getEventDetail(event),
+ })
+ return
+ }
+
+ if (source === SOURCE_VIEWPORT_RESIZE) {
+ steps.push({
+ id: `${index}-resize`,
+ offset,
+ kind: 'resize',
+ label: t('project.sessionReplay.timeline.resize'),
+ })
+ }
+ })
+
+ pushMutationGroup()
+ return steps.slice(0, 200)
+}
+
+const timelineIcon = (kind: TimelineStep['kind']) => {
+ if (kind === 'click') return CursorClickIcon
+ if (kind === 'input') return TextTIcon
+ if (kind === 'scroll' || kind === 'resize') return CaretRightIcon
+ if (kind === 'mutation') return ListBulletsIcon
+ if (kind === 'navigation' || kind === 'snapshot') return PlayIcon
+ return ListBulletsIcon
+}
+
+export const SessionReplayModal = ({
+ isOpen,
+ onClose,
+ projectId,
+ psid,
+ replay,
+}: SessionReplayModalProps) => {
+ const { t } = useTranslation('common')
+ const { fetchSessionReplay, isLoading } = useSessionReplayProxy()
+ const [payload, setPayload] = useState<SessionReplayResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isPreparing, setIsPreparing] = useState(false)
+ const [duration, setDuration] = useState(0)
+ const [currentTime, setCurrentTime] = useState(0)
+ const [isPlaying, setIsPlaying] = useState(false)
+ const [speed, setSpeed] = useState(1)
+ const [showTimeline, setShowTimeline] = useState(true)
+ const [isFullscreen, setIsFullscreen] = useState(false)
+ const playerRoot = useRef<HTMLDivElement | null>(null)
+ const fullscreenRoot = useRef<HTMLDivElement | null>(null)
+ const replayer = useRef<Replayer | null>(null)
+ const playStart = useRef({ offset: 0, at: 0, speed: 1 })
+ const currentTimeRef = useRef(0)
+ const speedRef = useRef(1)
+
+ const events = useMemo(
+ () => (payload?.events || []) as ReplayEvent[],
+ [payload?.events],
+ )
+ const activeReplay = payload?.replay || replay || null
+ const timelineSteps = useMemo(
+ () => buildTimelineSteps(events, t),
+ [events, t],
+ )
+ const hasEvents = events.length > 0
+
+ useEffect(() => {
+ currentTimeRef.current = currentTime
+ }, [currentTime])
+
+ useEffect(() => {
+ speedRef.current = speed
+ }, [speed])
+
+ useEffect(() => {
+ if (!isOpen) return
+
+ let cancelled = false
+ setIsPreparing(true)
+ setPayload(null)
+ setError(null)
+ setDuration(0)
+ setCurrentTime(0)
+ setIsPlaying(false)
+
+ fetchSessionReplay(projectId, psid, replay?.replayId)
+ .then((result) => {
+ if (cancelled) return
+ if (!result) {
+ setError(t('project.sessionReplay.loadError'))
+ return
+ }
+ setPayload(result)
+ })
+ .catch((reason) => {
+ if (cancelled) return
+ setError(
+ reason instanceof Error
+ ? reason.message
+ : t('project.sessionReplay.loadError'),
+ )
+ })
+ .finally(() => {
+ if (!cancelled) setIsPreparing(false)
+ })
+
+ return () => {
+ cancelled = true
+ }
+ }, [fetchSessionReplay, isOpen, projectId, psid, replay?.replayId, t])
+
+ useEffect(() => {
+ if (!isOpen || !hasEvents || !playerRoot.current) return
+
+ const root = playerRoot.current
+ root.innerHTML = ''
+ setIsPlaying(false)
+ setCurrentTime(0)
+
+ try {
+ const instance = new Replayer(events as eventWithTime[], {
+ root,
+ speed: speedRef.current,
+ insertStyleRules: ['html, body { background-color: #fff; }'],
+ })
+ replayer.current = instance
+ const metadata = instance.getMetaData()
+ const fallbackDuration =
+ events.length > 1
+ ? getTimestamp(events[events.length - 1]) - getTimestamp(events[0])
+ : 0
+ setDuration(Math.max(0, metadata.totalTime || fallbackDuration))
+ } catch (reason) {
+ setError(
+ reason instanceof Error
+ ? reason.message
+ : t('project.sessionReplay.playerError'),
+ )
+ }
+
+ return () => {
+ replayer.current?.pause()
+ replayer.current = null
+ root.innerHTML = ''
+ }
+ }, [events, hasEvents, isOpen, t])
+
+ useEffect(() => {
+ if (!isOpen || !isPlaying || duration <= 0) return
+
+ const timer = window.setInterval(() => {
+ const elapsed =
+ (performance.now() - playStart.current.at) * playStart.current.speed
+ const next = Math.min(duration, playStart.current.offset + elapsed)
+ setCurrentTime(next)
+
+ if (next >= duration) {
+ replayer.current?.pause(duration)
+ setIsPlaying(false)
+ }
+ }, 250)
+
+ return () => window.clearInterval(timer)
+ }, [duration, isOpen, isPlaying])
+
+ useEffect(() => {
+ const onFullscreenChange = () => {
+ setIsFullscreen(Boolean(document.fullscreenElement))
+ }
+
+ document.addEventListener('fullscreenchange', onFullscreenChange)
+ return () =>
+ document.removeEventListener('fullscreenchange', onFullscreenChange)
+ }, [])
+
+ const syncPlaybackOffset = useCallback(() => {
+ if (!isPlaying) return currentTimeRef.current
+
+ const elapsed =
+ (performance.now() - playStart.current.at) * playStart.current.speed
+ return Math.min(duration, playStart.current.offset + elapsed)
+ }, [duration, isPlaying])
+
+ const play = useCallback(() => {
+ if (!replayer.current || duration <= 0) return
+
+ const offset = Math.min(currentTimeRef.current, Math.max(0, duration - 1))
+ replayer.current.play(offset)
+ playStart.current = { offset, at: performance.now(), speed }
+ setIsPlaying(true)
+ }, [duration, speed])
+
+ const pause = useCallback(() => {
+ if (!replayer.current) return
+
+ const offset = syncPlaybackOffset()
+ replayer.current.pause(offset)
+ setCurrentTime(offset)
+ setIsPlaying(false)
+ }, [syncPlaybackOffset])
+
+ const seekTo = useCallback(
+ (offset: number, shouldPlay = isPlaying) => {
+ if (!replayer.current) return
+
+ const nextOffset = Math.max(0, Math.min(duration, offset))
+ if (shouldPlay) {
+ replayer.current.play(nextOffset)
+ } else {
+ replayer.current.pause(nextOffset)
+ }
+ setCurrentTime(nextOffset)
+ currentTimeRef.current = nextOffset
+
+ if (shouldPlay) {
+ playStart.current = {
+ offset: nextOffset,
+ at: performance.now(),
+ speed,
+ }
+ setIsPlaying(true)
+ } else {
+ setIsPlaying(false)
+ }
+ },
+ [duration, isPlaying, speed],
+ )
+
+ const setPlaybackSpeed = (nextSpeed: number) => {
+ const offset = syncPlaybackOffset()
+ setSpeed(nextSpeed)
+ replayer.current?.setConfig({ speed: nextSpeed })
+ setCurrentTime(offset)
+
+ if (isPlaying) {
+ replayer.current?.play(offset)
+ playStart.current = {
+ offset,
+ at: performance.now(),
+ speed: nextSpeed,
+ }
+ }
+ }
+
+ const toggleFullscreen = async () => {
+ try {
+ if (document.fullscreenElement) {
+ await document.exitFullscreen()
+ } else {
+ await fullscreenRoot.current?.requestFullscreen()
+ }
+ } catch {
+ toast.error(t('project.sessionReplay.fullscreenError'))
+ }
+ }
+
+ const downloadScreenshot = async () => {
+ try {
+ const iframe = playerRoot.current?.querySelector('iframe')
+ const doc = iframe?.contentDocument
+ if (!iframe || !doc) {
+ throw new Error('Replay frame is unavailable')
+ }
+
+ const width = iframe.clientWidth || doc.documentElement.clientWidth
+ const height = iframe.clientHeight || doc.documentElement.clientHeight
+ const serialized = new XMLSerializer().serializeToString(
+ doc.documentElement,
+ )
+ const svg = new Blob(
+ [
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><foreignObject width="100%" height="100%">${serialized}</foreignObject></svg>`,
+ ],
+ { type: 'image/svg+xml;charset=utf-8' },
+ )
+ const url = URL.createObjectURL(svg)
+ const image = new Image()
+
+ await new Promise<void>((resolve, reject) => {
+ image.onload = () => resolve()
+ image.onerror = () => reject(new Error('Screenshot failed'))
+ image.src = url
+ })
+
+ const canvas = document.createElement('canvas')
+ canvas.width = width
+ canvas.height = height
+ const context = canvas.getContext('2d')
+ if (!context) throw new Error('Screenshot failed')
+ context.drawImage(image, 0, 0, width, height)
+ URL.revokeObjectURL(url)
+
+ const blob = await new Promise<Blob | null>((resolve) =>
+ canvas.toBlob(resolve, 'image/png'),
+ )
+ if (!blob) throw new Error('Screenshot failed')
+
+ const link = document.createElement('a')
+ link.href = URL.createObjectURL(blob)
+ link.download = `swetrix-replay-${psid}.png`
+ link.click()
+ URL.revokeObjectURL(link.href)
+ toast.success(t('project.sessionReplay.screenshotDownloaded'))
+ } catch {
+ toast.error(t('project.sessionReplay.screenshotError'))
+ }
+ }
+
+ const close = () => {
+ replayer.current?.pause()
+ setIsPlaying(false)
+ onClose()
+ }
+
+ const replayDuration =
+ activeReplay?.replayDuration && activeReplay.replayDuration > 0
+ ? getStringFromTime(getTimeFromSeconds(activeReplay.replayDuration))
+ : formatReplayTime(duration)
+
+ return (
+ <Dialog className='relative z-50' open={isOpen} onClose={close}>
+ <DialogBackdrop
+ transition
+ className='fixed inset-0 bg-gray-950/60 backdrop-blur-[2px] transition-opacity duration-200 data-closed:opacity-0 dark:bg-black/75'
+ />
+ <div className='fixed inset-0 z-10 flex items-center justify-center p-3 sm:p-6'>
+ <DialogPanel
+ ref={fullscreenRoot}
+ transition
+ className={cn(
+ 'flex h-[min(92dvh,900px)] w-[min(96vw,1280px)] flex-col overflow-hidden rounded-xl bg-white shadow-2xl ring-1 ring-gray-200 transition-all duration-200 data-closed:translate-y-2 data-closed:scale-[0.98] data-closed:opacity-0 dark:bg-slate-950 dark:ring-slate-800',
+ isFullscreen && 'h-screen! w-screen! rounded-none',
+ )}
+ >
+ <div className='flex min-h-14 items-center justify-between gap-3 border-b border-gray-200 px-4 dark:border-slate-800'>
+ <div className='min-w-0'>
+ <DialogTitle
+ as='h2'
+ className='truncate text-base font-semibold text-gray-950 dark:text-gray-50'
+ >
+ {t('project.sessionReplay.title')}
+ </DialogTitle>
+ <Text size='xs' colour='secondary' truncate>
+ {activeReplay
+ ? t('project.sessionReplay.summary', {
+ events: activeReplay.eventCount.toLocaleString(),
+ duration: replayDuration,
+ })
+ : psid}
+ </Text>
+ </div>
+ <Button
+ variant='icon'
+ aria-label={t('common.close')}
+ onClick={close}
+ className='shrink-0'
+ >
+ <XIcon className='size-4' />
+ </Button>
+ </div>
+
+ <div
+ className={cn(
+ 'grid min-h-0 flex-1 gap-0 bg-gray-50 dark:bg-slate-950',
+ showTimeline
+ ? 'lg:grid-cols-[minmax(0,1fr)_280px]'
+ : 'grid-cols-1',
+ )}
+ >
+ <div className='min-h-0 p-3'>
+ <div className='relative flex h-full min-h-[360px] items-center justify-center overflow-hidden rounded-lg bg-slate-950 ring-1 ring-slate-900/70 dark:ring-slate-800'>
+ {isPreparing || isLoading ? <Loader /> : null}
+ {!isPreparing && error ? (
+ <div className='max-w-md px-6 text-center'>
+ <WarningCircleIcon className='mx-auto mb-3 size-8 text-amber-400' />
+ <Text
+ colour='inherit'
+ weight='semibold'
+ className='text-white'
+ >
+ {t('project.sessionReplay.loadError')}
+ </Text>
+ <Text as='p' size='sm' className='mt-1 text-slate-300'>
+ {error}
+ </Text>
+ </div>
+ ) : null}
+ {!isPreparing && !error && payload && !hasEvents ? (
+ <div className='max-w-md px-6 text-center'>
+ <Text
+ colour='inherit'
+ weight='semibold'
+ className='text-white'
+ >
+ {t('project.sessionReplay.empty')}
+ </Text>
+ </div>
+ ) : null}
+ <div
+ ref={playerRoot}
+ className={cn(
+ 'rrweb-player-root h-full w-full',
+ (!hasEvents || error) && 'hidden',
+ )}
+ />
+ </div>
+ </div>
+
+ {showTimeline ? (
+ <aside className='min-h-0 border-t border-gray-200 bg-white lg:border-t-0 lg:border-l dark:border-slate-800 dark:bg-slate-950'>
+ <div className='flex h-11 items-center justify-between border-b border-gray-200 px-3 dark:border-slate-800'>
+ <Text size='sm' weight='semibold'>
+ {t('project.sessionReplay.timeline.title')}
+ </Text>
+ <Text size='xs' colour='secondary'>
+ {timelineSteps.length}
+ </Text>
+ </div>
+ <div className='max-h-48 overflow-y-auto px-2 py-2 lg:max-h-[calc(100%-2.75rem)]'>
+ {timelineSteps.length ? (
+ timelineSteps.map((step) => {
+ const Icon = timelineIcon(step.kind)
+ return (
+ <button
+ key={step.id}
+ type='button'
+ onClick={() => seekTo(step.offset, false)}
+ className='flex w-full items-start gap-2 rounded-md px-2 py-2 text-left transition-colors hover:bg-gray-100 dark:hover:bg-slate-900'
+ >
+ <Icon className='mt-0.5 size-4 shrink-0 text-gray-500 dark:text-slate-400' />
+ <span className='min-w-0 flex-1'>
+ <Text size='xs' weight='medium' truncate>
+ {step.label}
+ </Text>
+ {step.detail ? (
+ <Text size='xs' colour='secondary' truncate>
+ {step.detail}
+ </Text>
+ ) : null}
+ </span>
+ <Text
+ size='xs'
+ colour='secondary'
+ className='shrink-0'
+ >
+ {formatReplayTime(step.offset)}
+ </Text>
+ </button>
+ )
+ })
+ ) : (
+ <Text size='sm' colour='secondary' className='px-2 py-3'>
+ {t('project.sessionReplay.timeline.empty')}
+ </Text>
+ )}
+ </div>
+ </aside>
+ ) : null}
+ </div>
+
+ <div className='border-t border-gray-200 bg-white px-3 py-3 dark:border-slate-800 dark:bg-slate-950'>
+ <div className='flex flex-col gap-3 lg:flex-row lg:items-center'>
+ <div className='flex items-center gap-1.5'>
+ <Tooltip
+ asChild
+ text={isPlaying ? t('common.pause') : t('common.play')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={
+ isPlaying ? t('common.pause') : t('common.play')
+ }
+ onClick={isPlaying ? pause : play}
+ disabled={!hasEvents || Boolean(error)}
+ >
+ {isPlaying ? (
+ <PauseIcon className='size-4' />
+ ) : (
+ <PlayIcon className='size-4' />
+ )}
+ </Button>
+ }
+ />
+ <Tooltip
+ asChild
+ text={t('project.sessionReplay.back10')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={t('project.sessionReplay.back10')}
+ onClick={() => seekTo(currentTime - 10000)}
+ disabled={!hasEvents || Boolean(error)}
+ >
+ <RewindIcon className='size-4' />
+ </Button>
+ }
+ />
+ <Tooltip
+ asChild
+ text={t('project.sessionReplay.forward10')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={t('project.sessionReplay.forward10')}
+ onClick={() => seekTo(currentTime + 10000)}
+ disabled={!hasEvents || Boolean(error)}
+ >
+ <FastForwardIcon className='size-4' />
+ </Button>
+ }
+ />
+ </div>
+
+ <div className='grid min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2'>
+ <Text size='xs' colour='secondary'>
+ {formatReplayTime(currentTime)}
+ </Text>
+ <input
+ type='range'
+ aria-label={t('project.sessionReplay.timeline.title')}
+ min={0}
+ max={Math.max(duration, 1)}
+ step={250}
+ value={Math.min(currentTime, duration)}
+ onChange={(event) =>
+ seekTo(Number(event.currentTarget.value), false)
+ }
+ disabled={!hasEvents || Boolean(error)}
+ className='h-1.5 w-full cursor-pointer appearance-none rounded-full bg-gray-200 accent-slate-900 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-slate-800 dark:accent-slate-100'
+ />
+ <Text size='xs' colour='secondary'>
+ {formatReplayTime(duration)}
+ </Text>
+ </div>
+
+ <div className='flex flex-wrap items-center gap-2'>
+ <select
+ value={speed}
+ onChange={(event) =>
+ setPlaybackSpeed(Number(event.currentTarget.value))
+ }
+ disabled={!hasEvents || Boolean(error)}
+ aria-label={t('project.sessionReplay.speed')}
+ className='h-9 rounded-md border border-gray-300 bg-gray-50 px-2 text-xs font-medium text-gray-900 transition-colors outline-none focus:ring-2 focus:ring-slate-900 disabled:opacity-50 dark:border-slate-700 dark:bg-slate-950 dark:text-gray-100 dark:focus:ring-slate-300'
+ >
+ {SPEEDS.map((item) => (
+ <option key={item} value={item}>
+ {item}x
+ </option>
+ ))}
+ </select>
+ <Tooltip
+ asChild
+ text={
+ showTimeline
+ ? t('project.sessionReplay.hideTimeline')
+ : t('project.sessionReplay.showTimeline')
+ }
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={
+ showTimeline
+ ? t('project.sessionReplay.hideTimeline')
+ : t('project.sessionReplay.showTimeline')
+ }
+ onClick={() => setShowTimeline((value) => !value)}
+ >
+ <ListBulletsIcon className='size-4' />
+ </Button>
+ }
+ />
+ <Tooltip
+ asChild
+ text={t('project.sessionReplay.screenshot')}
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={t('project.sessionReplay.screenshot')}
+ onClick={downloadScreenshot}
+ disabled={!hasEvents || Boolean(error)}
+ >
+ <CameraIcon className='size-4' />
+ </Button>
+ }
+ />
+ <Tooltip
+ asChild
+ text={
+ isFullscreen
+ ? t('project.sessionReplay.exitFullscreen')
+ : t('project.sessionReplay.fullscreen')
+ }
+ tooltipNode={
+ <Button
+ variant='icon'
+ aria-label={
+ isFullscreen
+ ? t('project.sessionReplay.exitFullscreen')
+ : t('project.sessionReplay.fullscreen')
+ }
+ onClick={toggleFullscreen}
+ >
+ {isFullscreen ? (
+ <ArrowsInIcon className='size-4' />
+ ) : (
+ <ArrowsOutIcon className='size-4' />
+ )}
+ </Button>
+ }
+ />
+ </div>
+ </div>
+ </div>
+ </DialogPanel>
+ </div>
+ </Dialog>
+ )
+}
+
+export default SessionReplayModal
diff --git a/web/app/pages/Project/tabs/Sessions/Sessions.tsx b/web/app/pages/Project/tabs/Sessions/Sessions.tsx
index 89367d478..e760f9679 100644
--- a/web/app/pages/Project/tabs/Sessions/Sessions.tsx
+++ b/web/app/pages/Project/tabs/Sessions/Sessions.tsx
@@ -9,6 +9,7 @@ import {
WarningIcon,
CursorClickIcon,
CaretRightIcon,
+ VideoCameraIcon,
} from '@phosphor-icons/react'
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -178,6 +179,24 @@ export const Session = ({
() => dayjs.utc(session.lastActivity).fromNow(true),
[session.lastActivity],
)
+ const replayDurationString = useMemo(() => {
+ if (!session.replayDuration || session.replayDuration <= 0) return null
+ return getStringFromTime(getTimeFromSeconds(session.replayDuration))
+ }, [session.replayDuration])
+ const replayExpiresAt = useMemo(() => {
+ if (!session.replayExpiresAt) return null
+ const date = dayjs.utc(session.replayExpiresAt)
+ 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,
+ })
+ }, [language, session.replayExpiresAt, timeFormat, timezone])
const params = new URLSearchParams(location.search)
params.set('psid', session.psid)
@@ -324,6 +343,43 @@ export const Session = ({
}
/>
+ {Boolean(session.hasReplay) && (
+ <Tooltip
+ text={
+ <div className='grid gap-1'>
+ <Text size='xs' colour='inherit'>
+ {t('project.sessionReplay.available')}
+ </Text>
+ {replayDurationString ? (
+ <Text size='xs' colour='inherit'>
+ {t('project.sessionReplay.duration', {
+ duration: replayDurationString,
+ })}
+ </Text>
+ ) : null}
+ {replayExpiresAt ? (
+ <Text size='xs' colour='inherit'>
+ {t('project.sessionReplay.expiresAt', {
+ date: replayExpiresAt,
+ })}
+ </Text>
+ ) : null}
+ </div>
+ }
+ tooltipNode={
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ weight='medium'
+ className='flex items-center gap-1'
+ >
+ <VideoCameraIcon className='size-3.5' />
+ </Text>
+ }
+ />
+ )}
+
{session.customEvents > 0 && (
<Tooltip
text={t('dashboard.events')}
diff --git a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
index 384f332b5..9d0fbfc17 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
@@ -17,6 +17,7 @@ import { useSessionsProxy } from '~/hooks/useAnalyticsProxy'
import {
Session,
SessionDetails as SessionDetailsType,
+ SessionReplayMetadata,
} from '~/lib/models/Project'
import NoSessions from '~/pages/Project/tabs/Sessions/components/NoSessions'
import { SessionDetailView } from '~/pages/Project/tabs/Sessions/SessionDetailView'
@@ -104,6 +105,7 @@ interface ActiveSession {
timeBucket?: string
sessionStart?: string
lastActivity?: string
+ replay?: SessionReplayMetadata | null
}
interface SessionsViewProps {
@@ -221,6 +223,7 @@ const SessionsViewInner = ({
matchingSession?.lastActivity ||
lastPage?.created ||
apiDetails.created,
+ replay: deferredData.sessionDetails.replay,
}
}
return null
diff --git a/web/app/pages/Project/tabs/Sessions/replayPlayer.css b/web/app/pages/Project/tabs/Sessions/replayPlayer.css
new file mode 100644
index 000000000..f9215aed1
--- /dev/null
+++ b/web/app/pages/Project/tabs/Sessions/replayPlayer.css
@@ -0,0 +1,84 @@
+/*
+ * Vendored from rrweb/dist/style.css.
+ * Inlined locally so the stylesheet URL doesn't contain "rrweb", which privacy
+ * adblock lists block. Keep in sync with the installed rrweb version.
+ */
+.replayer-wrapper {
+ position: relative;
+}
+.replayer-mouse {
+ position: absolute;
+ width: 20px;
+ height: 20px;
+ transition: left 0.05s linear, top 0.05s linear;
+ background-size: contain;
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-image: url('data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9JzMwMHB4JyB3aWR0aD0nMzAwcHgnICBmaWxsPSIjMDAwMDAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGRhdGEtbmFtZT0iTGF5ZXIgMSIgdmlld0JveD0iMCAwIDUwIDUwIiB4PSIwcHgiIHk9IjBweCI+PHRpdGxlPkRlc2lnbl90bnA8L3RpdGxlPjxwYXRoIGQ9Ik00OC43MSw0Mi45MUwzNC4wOCwyOC4yOSw0NC4zMywxOEExLDEsMCwwLDAsNDQsMTYuMzlMMi4zNSwxLjA2QTEsMSwwLDAsMCwxLjA2LDIuMzVMMTYuMzksNDRhMSwxLDAsMCwwLDEuNjUuMzZMMjguMjksMzQuMDgsNDIuOTEsNDguNzFhMSwxLDAsMCwwLDEuNDEsMGw0LjM4LTQuMzhBMSwxLDAsMCwwLDQ4LjcxLDQyLjkxWm0tNS4wOSwzLjY3TDI5LDMyYTEsMSwwLDAsMC0xLjQxLDBsLTkuODUsOS44NUwzLjY5LDMuNjlsMzguMTIsMTRMMzIsMjcuNThBMSwxLDAsMCwwLDMyLDI5TDQ2LjU5LDQzLjYyWiI+PC9wYXRoPjwvc3ZnPg==');
+ border-color: transparent; /* otherwise we transition from black when .touch-device class is added */
+}
+.replayer-mouse::after {
+ content: '';
+ display: inline-block;
+ width: 20px;
+ height: 20px;
+ background: rgb(73, 80, 246);
+ border-radius: 100%;
+ transform: translate(-50%, -50%);
+ opacity: 0.3;
+}
+.replayer-mouse.active::after {
+ animation: click 0.2s ease-in-out 1;
+}
+.replayer-mouse.touch-device {
+ background-image: none; /* there's no passive cursor on touch-only screens */
+ width: 70px;
+ height: 70px;
+ border-width: 4px;
+ border-style: solid;
+ border-radius: 100%;
+ margin-left: -37px;
+ margin-top: -37px;
+ border-color: rgba(73, 80, 246, 0);
+ transition: left 0s linear, top 0s linear, border-color 0.2s ease-in-out;
+}
+.replayer-mouse.touch-device.touch-active {
+ border-color: rgba(73, 80, 246, 1);
+ transition: left 0.25s linear, top 0.25s linear, border-color 0.2s ease-in-out;
+}
+.replayer-mouse.touch-device::after {
+ opacity: 0; /* there's no passive cursor on touch-only screens */
+}
+.replayer-mouse.touch-device.active::after {
+ animation: touch-click 0.2s ease-in-out 1;
+}
+.replayer-mouse-tail {
+ position: absolute;
+ pointer-events: none;
+}
+
+@keyframes click {
+ 0% {
+ opacity: 0.3;
+ width: 20px;
+ height: 20px;
+ }
+ 50% {
+ opacity: 0.5;
+ width: 10px;
+ height: 10px;
+ }
+}
+
+@keyframes touch-click {
+ 0% {
+ opacity: 0;
+ width: 20px;
+ height: 20px;
+ }
+ 50% {
+ opacity: 0.5;
+ width: 10px;
+ height: 10px;
+ }
+}
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 0dcd35747..5f770b682 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -354,9 +354,6 @@ const UserSettings = () => {
const currency = CURRENCIES[currencyCode]
const websiteAddonBundle = ADDONS.websiteBundles[0]
const websiteAddonPrice = websiteAddonBundle.monthly[currencyCode]
- // Session replay add-on pricing is hidden until self-serve replay billing ships.
- // const sessionReplayAddon = ADDONS.sessionReplayBundles[0]
- // const sessionReplayAddonPrice = sessionReplayAddon.monthly[currencyCode]
const activeWebsiteAddonQuantity =
websiteAddon?.quantity ?? purchasedWebsiteAddons
const currentWebsiteAddonBillingInterval = (websiteAddon?.billingInterval ||
@@ -2250,29 +2247,30 @@ const UserSettings = () => {
</Button>
</div>
- {/* Additional session replays add-on is temporarily hidden
- until self-serve replay pricing is finalised.
<div className='mt-8 border-t border-gray-200 pt-6 dark:border-slate-800'>
<Text as='h4' size='base' weight='semibold'>
- {t('billing.sessionReplayAddonTitle')}
+ {t('billing.sessionReplayCapacityTitle')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mt-1'>
- {t('billing.sessionReplayAddonDescription', {
- amount: sessionReplayAddon.quantity.toLocaleString(),
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mt-1 max-w-xl'
+ >
+ {t('billing.sessionReplayCapacityDescription', {
+ quota: replayLimitLabel,
})}
</Text>
- <Text as='p' size='lg' weight='bold' className='mt-4'>
- {currency.symbol}
- {formatBillingPrice(sessionReplayAddonPrice)}
- <Text as='span' size='sm' weight='medium' colour='secondary'>
- /{t('pricing.intervals.month')}
- </Text>
- </Text>
- <Text as='p' size='sm' colour='secondary' className='mt-3'>
- {t('billing.sessionReplayAddonComingSoon')}
- </Text>
+ <Button
+ variant='secondary'
+ size='lg'
+ className='mt-5 gap-1'
+ to={routes.billing_choose_plan}
+ >
+ {t('billing.sessionReplayCapacityCta')}
+ <ArrowRightIcon className='size-4' />
+ </Button>
</div>
- */}
</SettingsSection>
</>
)}
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index 4613ce1f8..d7cb34e66 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -6,6 +6,7 @@ import {
import {
getSessionsServer,
+ getSessionReplayServer,
getFunnelSessionsServer,
getGoalSessionsServer,
getErrorsServer,
@@ -43,6 +44,7 @@ import {
type AnalyticsParams,
type AnalyticsFilter,
type SessionsResponse,
+ type SessionReplayResponse,
type FunnelSessionsResponse,
type GoalSessionsResponse,
type ErrorsResponse,
@@ -97,6 +99,7 @@ function formatDateForBackend(dateStr: string | undefined): string | undefined {
interface ProxyRequest {
action:
| 'getSessions'
+ | 'getSessionReplay'
| 'getErrors'
| 'getFeatureFlagStats'
| 'getFeatureFlagProfiles'
@@ -137,6 +140,8 @@ interface ProxyRequest {
goalId?: string
experimentId?: string
profileId?: string
+ psid?: string
+ replayId?: string
errorId?: string
filterType?: string
filterColumn?: 'br' | 'os'
@@ -215,6 +220,31 @@ export async function action({ request }: ActionFunctionArgs) {
})
}
+ case 'getSessionReplay': {
+ if (!body.psid) {
+ return data<ProxyResponse<SessionReplayResponse>>(
+ { data: null, error: 'psid is required' },
+ { status: 400 },
+ )
+ }
+
+ const result = await getSessionReplayServer(
+ request,
+ projectId,
+ body.psid,
+ body.replayId,
+ password || undefined,
+ )
+ return data<ProxyResponse<SessionReplayResponse>>({
+ data: result.data,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
+ })
+ }
+
case 'getFunnelSessions': {
const result = await getFunnelSessionsServer(request, projectId, {
period: analyticsParams.period,
diff --git a/web/app/routes/projects.settings.$id.tsx b/web/app/routes/projects.settings.$id.tsx
index 766570fcc..fbf889816 100644
--- a/web/app/routes/projects.settings.$id.tsx
+++ b/web/app/routes/projects.settings.$id.tsx
@@ -83,6 +83,7 @@ export interface ProjectSettingsActionData {
password?: string
transferEmail?: string
email?: string
+ sessionReplayRetentionDays?: string
}
project?: Project
subscriber?: Subscriber
@@ -130,6 +131,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
const websiteUrl = formData.get('websiteUrl')?.toString()
const brandKeywords = formData.get('brandKeywords')?.toString()
const captchaDifficulty = formData.get('captchaDifficulty')?.toString()
+ const sessionReplayRetentionDays = formData
+ .get('sessionReplayRetentionDays')
+ ?.toString()
const rawCaptchaDifficultyMode = formData
.get('captchaDifficultyMode')
?.toString()
@@ -145,7 +149,15 @@ export async function action({ request, params }: ActionFunctionArgs) {
fieldErrors.name = 'Project name must be 50 characters or less'
}
- if (fieldErrors.name) {
+ if (sessionReplayRetentionDays !== undefined) {
+ const retention = Number(sessionReplayRetentionDays)
+ if (![30, 90, 365, 1825].includes(retention)) {
+ fieldErrors.sessionReplayRetentionDays =
+ 'Choose a valid session replay retention period'
+ }
+ }
+
+ if (Object.keys(fieldErrors).length > 0) {
return data<ProjectSettingsActionData>(
{ intent, fieldErrors },
{ status: 400 },
@@ -184,6 +196,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
updateData.captchaDifficulty = Number(captchaDifficulty)
if (captchaDifficultyMode !== undefined)
updateData.captchaDifficultyMode = captchaDifficultyMode
+ if (sessionReplayRetentionDays !== undefined)
+ updateData.sessionReplayRetentionDays = Number(
+ sessionReplayRetentionDays,
+ )
const result = await serverFetch<Project>(request, `project/${id}`, {
method: 'PUT',
diff --git a/web/app/types/dom-player.d.ts b/web/app/types/dom-player.d.ts
new file mode 100644
index 000000000..44b70a536
--- /dev/null
+++ b/web/app/types/dom-player.d.ts
@@ -0,0 +1,6 @@
+// `dom-player` is a Vite resolve.alias to `rrweb` (see vite.config.ts). The
+// neutral name keeps "rrweb" out of the served asset URLs, which privacy
+// adblock lists block. Re-export rrweb's types under the alias for TS.
+declare module 'dom-player' {
+ export * from 'rrweb'
+}
diff --git a/web/package-lock.json b/web/package-lock.json
index f77aa738f..fec8b34e1 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -47,6 +47,7 @@
"remix-i18next": "^7.5.0",
"remix-sitemap": "^3.2.1",
"remix-utils": "^9.3.1",
+ "rrweb": "^2.0.0",
"sanitize-html": "^2.17.4",
"simple-icons": "^16.21.0",
"sonner": "^2.0.7",
@@ -4209,6 +4210,18 @@
"win32"
]
},
+ "node_modules/@rrweb/types": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.0.tgz",
+ "integrity": "sha512-p76i3Bdm/cjb/6NGqmFj0LkGXqC2dXs70AwirgVAsE1ndIa00TJo48La5yobHLsBOk5bfRHy6Yd+9O9VFKhAwQ==",
+ "license": "MIT"
+ },
+ "node_modules/@rrweb/utils": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.0.tgz",
+ "integrity": "sha512-0Q9djyxlwG1fs1TxT7VnKtt33tHku6PENlUAKSXZg8QSSI6aUXdCNZkkBt3JAgbBYVrGhQsYrz+DkCdAXqxs1w==",
+ "license": "MIT"
+ },
"node_modules/@swc/helpers": {
"version": "0.5.18",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.18.tgz",
@@ -4749,6 +4762,12 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/css-font-loading-module": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/@types/css-font-loading-module/-/css-font-loading-module-0.0.7.tgz",
+ "integrity": "sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==",
+ "license": "MIT"
+ },
"node_modules/@types/d3": {
"version": "7.4.3",
"resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
@@ -5158,6 +5177,12 @@
"node": "*"
}
},
+ "node_modules/@xstate/fsm": {
+ "version": "1.6.5",
+ "resolved": "https://registry.npmjs.org/@xstate/fsm/-/fsm-1.6.5.tgz",
+ "integrity": "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw==",
+ "license": "MIT"
+ },
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -5281,6 +5306,15 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
+ "node_modules/base64-arraybuffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
+ "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6.0"
+ }
+ },
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
@@ -8081,6 +8115,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
"node_modules/morgan": {
"version": "1.10.1",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.1.tgz",
@@ -9290,6 +9330,40 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/rrdom": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.0.tgz",
+ "integrity": "sha512-Yv+T/IBngNEjhbRv6yJzKdbhgMOiRCV+UA3R0HOpx4yySc8vl4I11Xr5BxCYrnt00l7CGjHbFB9VULEvcg1u6w==",
+ "license": "MIT",
+ "dependencies": {
+ "rrweb-snapshot": "^2.0.0"
+ }
+ },
+ "node_modules/rrweb": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.0.tgz",
+ "integrity": "sha512-ID7NE8OdfAbxZKlTPc/EdL/8sLhTOVB1aZKoQ/M0peKGYB7dIDj0hsdJo+OVXfpiYMTtGzXnKfnMVUj4LnsrhQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@rrweb/types": "^2.0.0",
+ "@rrweb/utils": "^2.0.0",
+ "@types/css-font-loading-module": "0.0.7",
+ "@xstate/fsm": "^1.4.0",
+ "base64-arraybuffer": "^1.0.1",
+ "mitt": "^3.0.0",
+ "rrdom": "^2.0.0",
+ "rrweb-snapshot": "^2.0.0"
+ }
+ },
+ "node_modules/rrweb-snapshot": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.0.tgz",
+ "integrity": "sha512-mDYvvHVXYUD6wZj2AGz5UuupnYnhrWUmF+Hm+haZtVPx8bK3hpAMpu7YjPAoHVluv6KZJNJvVb/6HeBKwXTAvA==",
+ "license": "MIT",
+ "dependencies": {
+ "postcss": "^8.4.38"
+ }
+ },
"node_modules/rw": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
diff --git a/web/package.json b/web/package.json
index 96ed90af9..8dcd5194e 100644
--- a/web/package.json
+++ b/web/package.json
@@ -60,6 +60,7 @@
"remix-i18next": "^7.5.0",
"remix-sitemap": "^3.2.1",
"remix-utils": "^9.3.1",
+ "rrweb": "^2.0.0",
"sanitize-html": "^2.17.4",
"simple-icons": "^16.21.0",
"sonner": "^2.0.7",
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 3fb75a9bc..ba713d3e7 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1541,6 +1541,7 @@
"duplicateKeys": "Variant keys must be unique",
"variantFieldsRequired": "Variant name and key are required",
"start": "Start",
+ "play": "Play",
"resume": "Resume",
"pause": "Pause",
"complete": "Complete",
@@ -1958,7 +1959,41 @@
"sessionStartedAt": "Started",
"sessionEndedAt": "Ended",
"goToProfile": "Go to profile",
+ "watchReplay": "Watch replay",
"sessionActivity": "Session activity",
+ "sessionReplay": {
+ "available": "Replay available",
+ "duration": "Replay duration: {{duration}}",
+ "expiresAt": "Expires {{date}}",
+ "title": "Session replay",
+ "summary": "{{events}} events · {{duration}}",
+ "loadError": "Could not load replay",
+ "playerError": "Could not initialise replay player",
+ "empty": "No replay events were found.",
+ "back10": "Back 10 seconds",
+ "forward10": "Forward 10 seconds",
+ "speed": "Playback speed",
+ "screenshot": "Download screenshot",
+ "screenshotError": "Could not capture this replay frame. Cross-origin media can block screenshots.",
+ "screenshotDownloaded": "Replay screenshot downloaded",
+ "fullscreen": "Fullscreen",
+ "exitFullscreen": "Exit fullscreen",
+ "fullscreenError": "Could not enter fullscreen",
+ "showTimeline": "Show timeline",
+ "hideTimeline": "Hide timeline",
+ "timeline": {
+ "title": "Timeline",
+ "empty": "No notable replay steps yet.",
+ "navigation": "Navigation",
+ "fullSnapshot": "Page snapshot",
+ "click": "Click",
+ "scroll": "Scroll",
+ "input": "Input",
+ "resize": "Viewport resize",
+ "mutations": "Page changes",
+ "mutationsCount": "{{count}} grouped changes"
+ }
+ },
"pageflow": "Page flow",
"userSessions": "Sessions",
"noSessions": "No sessions found for this user.",
@@ -2271,6 +2306,8 @@
"channelsDesc": "Project-scoped channels for sending alerts.",
"revenue": "Revenue",
"revenueDesc": "Track revenue and attribute sales to campaigns.",
+ "sessionReplays": "Session replays",
+ "sessionReplaysDesc": "Configure replay retention and project replay settings.",
"import": "Import data",
"importDesc": "Import analytics data from other platforms",
"proxy": "Managed proxy",
@@ -2310,6 +2347,22 @@
"paddleExample": "Paddle Checkout Integration:"
}
},
+ "sessionReplays": {
+ "retentionTitle": "Replay retention",
+ "retentionLabel": "Replay retention period",
+ "retentionDescription": "Choose how long newly recorded session replay chunks are kept for this project.",
+ "retentionHint": "Retention changes apply only to newly recorded replay chunks. Existing chunks keep the expiry date they were recorded with.",
+ "retention": {
+ "30": "30 days",
+ "90": "90 days",
+ "365": "1 year",
+ "1825": "5 years"
+ },
+ "upgradeRequired": "Upgrade to unlock longer replay retention.",
+ "upgradeTitle": "Need more replay capacity?",
+ "upgradeDescription": "Longer retention and higher replay capacity are available through upgraded replay entitlements.",
+ "upgradeCta": "View plans"
+ },
"dataImport": {
"importFrom": "Import from",
"importFromDesc": "Select an analytics provider to import historical data from.",
@@ -2503,6 +2556,7 @@
"passwordProtection": "Password protection updated",
"status": "Project status updated",
"captchaDifficulty": "CAPTCHA difficulty updated",
+ "sessionReplayRetention": "Session replay retention updated",
"organisation": "Project organisation updated",
"updated": "Project setting updated"
},
@@ -2903,6 +2957,9 @@
"websiteAddonDescription": "Add websites in chunks of {{amount}} at {{unitPrice}} per website per month.",
"sessionReplayAddonTitle": "Additional session replays",
"sessionReplayAddonDescription": "Add {{amount}} recorded sessions per month. Session replay pricing is temporary while the feature is finalised.",
+ "sessionReplayCapacityTitle": "Session replay capacity",
+ "sessionReplayCapacityDescription": "Your current plan includes {{quota}} recorded sessions per month. For higher capacity or longer retention, choose a larger Plus plan or contact us for a custom entitlement.",
+ "sessionReplayCapacityCta": "Review replay plans",
"activeAddonAmount": "{{amount}} active",
"requestAddon": "Request add-on",
"comingSoon": "Coming soon",
diff --git a/web/vite.config.ts b/web/vite.config.ts
index c04c2dca2..3c8656a60 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -8,6 +8,20 @@ export default defineConfig({
},
resolve: {
tsconfigPaths: true,
+ alias: {
+ // Serve rrweb under a neutral specifier so the dev dep URL becomes
+ // /.vite/deps/dom-player.js (and the prod chunk is named accordingly)
+ // instead of containing "rrweb", which privacy adblock lists block.
+ 'dom-player': 'rrweb',
+ },
+ },
+ optimizeDeps: {
+ // rrweb is only imported inside the lazily-loaded SessionReplayModal chunk,
+ // so Vite's initial scan never sees it. Without this it gets discovered on
+ // first replay open, triggering a mid-session re-optimization that changes
+ // the dep hash and breaks the in-flight dynamic import ("error loading
+ // dynamically imported module"). Pre-bundling it on startup avoids that.
+ include: ['dom-player'],
},
ssr: {
noExternal: [