📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Fix review comments
Blue Mouse68aeb0ee3962
diff --git a/admin/src/billing/pricing.ts b/admin/src/billing/pricing.tsindex 67785fb8c..a9d2acf18 100644--- a/admin/src/billing/pricing.ts+++ b/admin/src/billing/pricing.ts@@ -44,14 +44,14 @@ export const planEntitlements = {websites: 50,teamMembers: 10,organisations: 3,- apiRateLimitPerHour: 600,+ apiRateLimitPerHour: 300,sessionReplaysIncluded: 0,},[PlanType.plus]: {websites: 100,teamMembers: 25,organisations: 10,- apiRateLimitPerHour: 5000,+ apiRateLimitPerHour: 6000,sessionReplaysIncluded: 'byEventTier',},[PlanType.enterprise]: {diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 67d7eb4e9..72f6a47af 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -144,6 +144,41 @@ const MAX_SESSION_REPLAY_EVENTS_PER_CHUNK = 1000const MAX_SESSION_REPLAY_CHUNK_BYTES = 900 * 1024const SESSION_REPLAY_CLEANUP_BATCH_SIZE = 500const SESSION_REPLAY_CHUNK_FETCH_CONCURRENCY = 6+const RESERVE_REPLAY_USAGE_LUA = `+local reservationKey = KEYS[1]+local counterKey = KEYS[2]+local quota = tonumber(ARGV[1])+local monthlyUsage = tonumber(ARGV[2]) or 0+local ttl = tonumber(ARGV[3])++if redis.call("EXISTS", reservationKey) == 1 then+ return 0+end++local reservedUsage = tonumber(redis.call("GET", counterKey) or "0")+local currentUsage = reservedUsage+if monthlyUsage > currentUsage then+ currentUsage = monthlyUsage+end++if currentUsage >= quota then+ return -1+end++redis.call("SET", reservationKey, "1", "EX", ttl)+redis.call("SET", counterKey, currentUsage + 1, "EX", ttl)+return 1+`+const RELEASE_REPLAY_USAGE_LUA = `+if redis.call("DEL", KEYS[1]) == 1 then+ local current = tonumber(redis.call("GET", KEYS[2]) or "0")+ if current > 0 then+ redis.call("DECR", KEYS[2])+ end+ return 1+end+return 0+`const SOFTWARE_WITH_PATCH_VERSION = ['GameVault']@@ -1771,6 +1806,10 @@ export class AnalyticsService {return `session-replay:usage:${dayjs.utc().format('YYYY-MM')}:${accountId}:${pid}:${psid}:${replayId}`}+ private getReplayUsageCounterKey(accountId: string) {+ return `session-replay:usage-count:${dayjs.utc().format('YYYY-MM')}:${accountId}`+ }+private getReplayUsageTtlSeconds() {return Math.max(60, dayjs.utc().endOf('month').diff(dayjs.utc(), 'second'))}@@ -1818,35 +1857,68 @@ export class AnalyticsService {pid: string,psid: string,replayId: string,- ): Promise<{ reserved: boolean; key?: string }> {+ ): Promise<{ reserved: boolean; key?: string; counterKey?: string }> {const accountId = project.admin?.id || pidconst key = this.getReplayUsageKey(accountId, pid, psid, replayId)- const result = await redis.set(+ const quota = getSessionReplayQuota(project.admin)++ if (quota === 'custom') {+ const result = await redis.set(+ key,+ '1',+ 'EX',+ this.getReplayUsageTtlSeconds(),+ 'NX',+ )++ return result === 'OK' ? { reserved: true, key } : { reserved: false }+ }++ const counterKey = this.getReplayUsageCounterKey(accountId)+ const pids = await this.getReplayAccountProjectIds(project, pid)+ const usage = await this.getMonthlyReplayUsage(pids)+ const result = await redis.eval(+ RESERVE_REPLAY_USAGE_LUA,+ 2,key,- '1',- 'EX',+ counterKey,+ quota,+ usage,this.getReplayUsageTtlSeconds(),- 'NX',)- if (result !== 'OK') {+ if (Number(result) === -1) {+ throw new HttpException(+ 'Monthly session replay quota exceeded',+ HttpStatus.PAYMENT_REQUIRED,+ )+ }++ if (Number(result) !== 1) {return { reserved: false }}- const quota = getSessionReplayQuota(project.admin)- if (quota !== 'custom') {- const pids = await this.getReplayAccountProjectIds(project, pid)- const usage = await this.getMonthlyReplayUsage(pids)- if (usage >= quota) {- await redis.del(key)- throw new HttpException(- 'Monthly session replay quota exceeded',- HttpStatus.PAYMENT_REQUIRED,- )- }+ return { reserved: true, key, counterKey }+ }++ private async releaseReplayUsageReservation(+ reservation: { key?: string; counterKey?: string },+ ) {+ if (!reservation.key) {+ return}- return { reserved: true, key }+ if (!reservation.counterKey) {+ await redis.del(reservation.key)+ return+ }++ await redis.eval(+ RELEASE_REPLAY_USAGE_LUA,+ 2,+ reservation.key,+ reservation.counterKey,+ )}async storeSessionReplayChunk(@@ -1928,7 +2000,7 @@ export class AnalyticsService {})} catch (reason) {await Promise.allSettled([- usageReservation.key ? redis.del(usageReservation.key) : undefined,+ this.releaseReplayUsageReservation(usageReservation),this.sessionReplayStorage.deleteObject(objectKey),])throw reasondiff --git a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts b/backend/apps/cloud/src/analytics/dto/session-replay.dto.tsindex 19a4d6736..c02584dbf 100644--- a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts+++ b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts@@ -31,6 +31,7 @@ export class SessionReplayStartDto {@ApiProperty({ required: true })@IsString()+ @IsNotEmpty()@MaxLength(80)replayId: string@@ -85,6 +86,7 @@ export class GetSessionReplayDto {@ApiProperty({ required: false })@IsOptional()@IsString()+ @IsNotEmpty()@MaxLength(80)replayId?: string}@@ -98,15 +100,17 @@ export class GetSessionReplaysDto extends PickType(GetDataDto, ['timezone',] as const) {@Type(() => Number)+ @IsOptional()@IsInt()@Min(0)@Max(150)- take: number+ take?: number@Type(() => Number)+ @IsOptional()@IsInt()@Min(0)- skip: number+ skip?: number}export class SessionReplayExportStartDto extends GetSessionReplayDto {}diff --git a/backend/apps/cloud/src/analytics/session-replay-export.service.ts b/backend/apps/cloud/src/analytics/session-replay-export.service.tsindex 970abc88f..d1cc40a46 100644--- a/backend/apps/cloud/src/analytics/session-replay-export.service.ts+++ b/backend/apps/cloud/src/analytics/session-replay-export.service.ts@@ -1,5 +1,6 @@import { spawn } from 'child_process'-import { randomUUID } from 'crypto'+import { createHash, randomUUID } from 'crypto'+import { createReadStream } from 'fs'import * as fs from 'fs/promises'import * as os from 'os'import * as path from 'path'@@ -383,8 +384,16 @@ export class SessionReplayExportService {await this.updateState(state, { status: 'processing', progress: 90 })const objectKey = this.getObjectKey(data.pid, data.psid, data.exportId)- const output = await fs.readFile(mp4Path)- await this.sessionReplayStorage.putObject(objectKey, output, 'video/mp4')+ const outputHash = await this.hashFile(mp4Path)+ await this.sessionReplayStorage.putObject(+ objectKey,+ createReadStream(mp4Path),+ 'video/mp4',+ {+ contentLength: outputStat.size,+ payloadHash: outputHash,+ },+ )await this.updateState(state, {status: 'ready',@@ -393,21 +402,29 @@ export class SessionReplayExportService {error: undefined,})- await this.exportQueue.add(- 'cleanup-session-replay-export',- {- type: 'cleanup',- exportId: data.exportId,- expiresAt: state.expiresAt,- },- {- jobId: `${data.exportId}:cleanup:${hash(state.expiresAt)}`,- delay: this.ttlSeconds * 1000,- attempts: 3,- removeOnComplete: true,- removeOnFail: true,- },- )+ try {+ await this.exportQueue.add(+ 'cleanup-session-replay-export',+ {+ type: 'cleanup',+ exportId: data.exportId,+ expiresAt: state.expiresAt,+ },+ {+ jobId: `${data.exportId}:cleanup:${hash(state.expiresAt)}`,+ delay: this.ttlSeconds * 1000,+ attempts: 3,+ removeOnComplete: true,+ removeOnFail: true,+ },+ )+ } catch (reason) {+ this.logger.warn(+ `Failed to schedule session replay export cleanup ${data.exportId}: ${+ reason instanceof Error ? reason.message : String(reason)+ }`,+ )+ }} catch (reason) {await this.markFailed(state, reason)throw reason@@ -427,15 +444,16 @@ export class SessionReplayExportService {if (state.expiresAt !== data.expiresAt) returnif (state.objectKey) {- await this.sessionReplayStorage- .deleteObject(state.objectKey)- .catch((reason) =>- this.logger.warn(- `Failed to delete session replay export ${data.exportId}: ${- reason instanceof Error ? reason.message : String(reason)- }`,- ),+ try {+ await this.sessionReplayStorage.deleteObject(state.objectKey)+ } catch (reason) {+ this.logger.warn(+ `Failed to delete session replay export ${data.exportId}: ${+ reason instanceof Error ? reason.message : String(reason)+ }`,)+ throw reason+ }}await this.expireState(state)@@ -657,6 +675,18 @@ export class SessionReplayExportService {return 'about:blank'}+ private async hashFile(filePath: string) {+ const digest = createHash('sha256')+ await new Promise<void>((resolve, reject) => {+ const stream = createReadStream(filePath)+ stream.on('data', (chunk) => digest.update(chunk))+ stream.on('error', reject)+ stream.on('end', resolve)+ })++ return digest.digest('hex')+ }+private async runCommand(command: string,args: string[],diff --git a/backend/apps/cloud/src/analytics/session-replay-s3.service.ts b/backend/apps/cloud/src/analytics/session-replay-s3.service.tsindex 556e32b9f..7bab0bc95 100644--- a/backend/apps/cloud/src/analytics/session-replay-s3.service.ts+++ b/backend/apps/cloud/src/analytics/session-replay-s3.service.ts@@ -11,6 +11,9 @@ interface S3Config {}type HeaderMap = Record<string, string>+type PutObjectBody = Buffer | Readable++const SESSION_REPLAY_STORAGE_TIMEOUT_MS = 30_000const sha256Hex = (value: Buffer | string) =>crypto.createHash('sha256').update(value).digest('hex')@@ -73,12 +76,25 @@ export class SessionReplayS3Service {async putObject(key: string,- body: Buffer,+ body: PutObjectBody,contentType = 'application/json',+ options: { contentLength?: number; payloadHash?: string } = {},): Promise<void> {- const response = await this.signedFetch('PUT', key, body, {+ const headers: HeaderMap = {'content-type': contentType,- })+ }++ if (typeof options.contentLength === 'number') {+ headers['content-length'] = String(options.contentLength)+ }++ const response = await this.signedFetch(+ 'PUT',+ key,+ body,+ headers,+ options.payloadHash,+ )if (!response.ok) {throw new Error(`Hetzner S3 PUT failed with status ${response.status}`)@@ -136,15 +152,22 @@ export class SessionReplayS3Service {private async signedFetch(method: 'PUT' | 'GET' | 'DELETE',key: string,- body?: Buffer,+ body?: PutObjectBody,extraHeaders: HeaderMap = {},+ payloadHashOverride?: string,): Promise<Response> {const config = this.getConfig()if (!config) {throw new Error('Hetzner S3 session replay storage is not configured')}- const payloadHash = sha256Hex(body || '')+ const hasStreamBody = body instanceof Readable+ if (hasStreamBody && !payloadHashOverride) {+ throw new Error('Stream uploads require a payload hash')+ }++ const payloadHash =+ payloadHashOverride || sha256Hex(body instanceof Readable ? '' : body || '')const now = new Date()const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '')const dateStamp = amzDate.slice(0, 8)@@ -194,12 +217,33 @@ export class SessionReplayS3Service {`SignedHeaders=${signedHeaders}`,`Signature=${signature}`,].join(', ')- const requestBody = body ? new Uint8Array(body) : undefined-- return fetch(endpoint, {+ const requestBody = body+ ? hasStreamBody+ ? (body as any)+ : new Uint8Array(body)+ : undefined+ const controller = new AbortController()+ const timeout = setTimeout(+ () => controller.abort(),+ SESSION_REPLAY_STORAGE_TIMEOUT_MS,+ )+ const request: RequestInit & { duplex?: 'half' } = {method,headers,- body: requestBody,- })+ signal: controller.signal,+ }++ if (requestBody) {+ request.body = requestBody+ if (hasStreamBody) {+ request.duplex = 'half'+ }+ }++ try {+ return await fetch(endpoint, request)+ } finally {+ clearTimeout(timeout)+ }}}diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.tsindex 0c4df5307..a64e60a65 100644--- a/backend/apps/cloud/src/user/entities/user.entity.ts+++ b/backend/apps/cloud/src/user/entities/user.entity.ts@@ -93,6 +93,7 @@ const PLAN_TYPE_ENTITLEMENTS = {} as constconst PLUS_SESSION_REPLAY_QUOTA: Partial<Record<PlanCode, number>> = {+ [PlanCode.freelancer]: 5000,[PlanCode['100k']]: 5000,[PlanCode['200k']]: 10000,[PlanCode['500k']]: 25000,@@ -217,6 +218,7 @@ export const getSessionReplayQuota = (export const getSessionReplayRetentionEntitlement = (user?: {+ planCode?: PlanCode | nullplanType?: PlanType | nullentitlementOverrides?: Record<string, unknown> | null} | null,@@ -230,6 +232,10 @@ export const getSessionReplayRetentionEntitlement = (return override}+ if (user?.planType === PlanType.enterprise) {+ return 1825+ }+return getEffectivePlanType(user) === PlanType.enterprise ? 1825 : 30}diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdxindex 8e3193b65..86444510d 100644--- a/docs/content/docs/script-reference.mdx+++ b/docs/content/docs/script-reference.mdx@@ -254,7 +254,7 @@ swetrix.init("YOUR_PROJECT_ID", {});const replay = await swetrix.startSessionReplay({- privacy: "normal",+ privacy: "total",});await replay.stop();@@ -270,13 +270,13 @@ init("YOUR_PROJECT_ID", {});const replay = await startSessionReplay({- privacy: "normal",+ privacy: "total",});```| Name | Description | Default value || ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |-| privacy | Controls how much page content is masked. Use `total` to mask all text and inputs and block media/canvas content, `normal` to mask all inputs, or `none` to only force password inputs to stay masked unless you add your own `rrweb` masking options. | `normal` |+| privacy | Controls how much page content is masked. Use `total` to mask all text and inputs and block media/canvas content, `normal` to mask all inputs, or `none` to only force password inputs to stay masked unless you add your own `rrweb` masking options. | `total` || rrweb | Advanced recorder options passed to `rrweb.record()`. If you provide an `emit` callback, Swetrix will call it and still upload replay events. | `undefined` || flushIntervalMs | How often replay events are uploaded while recording. | `5000` || maxEventsPerChunk | The maximum number of replay events to batch before Swetrix uploads a chunk immediately. | `100` |diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.tsindex b185fd326..32f543de2 100644--- a/packages/tracker-js/src/Lib.ts+++ b/packages/tracker-js/src/Lib.ts@@ -192,7 +192,10 @@ export interface ErrorActions {stop: () => void}-export type SessionReplayPrivacy = 'total' | 'normal' | 'none'+const SESSION_REPLAY_PRIVACY_VALUES = ['total', 'normal', 'none'] as const++export type SessionReplayPrivacy =+ (typeof SESSION_REPLAY_PRIVACY_VALUES)[number]export interface SessionReplayOptions {privacy?: SessionReplayPrivacy@@ -800,7 +803,7 @@ export class Lib {return defaultSessionReplayActions}- const privacy = options.privacy || DEFAULT_SESSION_REPLAY_PRIVACY+ const privacy = this.getSessionReplayPrivacy(options.privacy)const replayId = this.createReplayId()const started = await this.sendSessionReplayStart(replayId, privacy)@@ -951,6 +954,14 @@ export class Lib {return Math.random() < sampleRate}+ private getSessionReplayPrivacy(privacy: unknown): SessionReplayPrivacy {+ return SESSION_REPLAY_PRIVACY_VALUES.includes(+ privacy as SessionReplayPrivacy,+ )+ ? (privacy as SessionReplayPrivacy)+ : DEFAULT_SESSION_REPLAY_PRIVACY+ }+/*** Gets the API base URL (without /log suffix).*/@@ -1112,6 +1123,12 @@ export class Lib {if (window.__SWETRIX_RRWEB_LOADING__) {this.rrwebLoader = window.__SWETRIX_RRWEB_LOADING__+ void this.rrwebLoader.catch(() => {+ if (window.__SWETRIX_RRWEB_LOADING__ === this.rrwebLoader) {+ delete window.__SWETRIX_RRWEB_LOADING__+ }+ this.rrwebLoader = null+ })return this.rrwebLoader}@@ -1126,12 +1143,21 @@ export class Lib {})window.__SWETRIX_RRWEB_LOADING__ = this.rrwebLoader+ const loader = this.rrwebLoader+ void loader.catch(() => {+ if (window.__SWETRIX_RRWEB_LOADING__ === loader) {+ delete window.__SWETRIX_RRWEB_LOADING__+ }+ if (this.rrwebLoader === loader) {+ this.rrwebLoader = null+ }+ })return this.rrwebLoader}private getSessionReplayRecordOptions(- privacy: SessionReplayPrivacy,+ privacy: unknown,userOptions: RrwebRecordOptions | undefined,emit: RrwebEmit,): RrwebRecordOptions {@@ -1146,7 +1172,9 @@ export class Lib {? (options.maskInputOptions as Record<string, unknown>): {}- if (privacy === 'total') {+ const resolvedPrivacy = this.getSessionReplayPrivacy(privacy)++ if (resolvedPrivacy === 'total') {return {...options,maskAllInputs: true,@@ -1161,7 +1189,7 @@ export class Lib {}}- if (privacy === 'normal') {+ if (resolvedPrivacy === 'normal') {return {...options,maskAllInputs: true,diff --git a/packages/tracker-js/tests/sessionReplay.test.ts b/packages/tracker-js/tests/sessionReplay.test.tsindex 72d708126..e01f54a72 100644--- a/packages/tracker-js/tests/sessionReplay.test.ts+++ b/packages/tracker-js/tests/sessionReplay.test.ts@@ -269,6 +269,62 @@ describe('Session replay tracking', () => {expect(freeLove.emit).toBe(emit)})+ test('invalid privacy values fall back to total privacy', 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({+ privacy: 'totl' as any,+ })+ resolveRrwebScript(record)++ const actions = await startPromise+ const startCall = fetchMock.mock.calls.find(([url]) =>+ String(url).includes('/session-replay/start'),+ )++ expect(startCall).toBeTruthy()+ expect(JSON.parse(startCall![1].body as string)).toEqual(+ expect.objectContaining({ privacy: 'total' }),+ )+ expect((record as any).options.maskTextSelector).toBe('*')++ await actions.stop()+ })++ test('rrweb loader clears failed loads so startSessionReplay can retry', async () => {+ const record = jest.fn(() => jest.fn())+ const { init, startSessionReplay } = await loadTracker()++ init(PROJECT_ID, { devMode: true })+ const failedStart = startSessionReplay()+ const failedScript = document.querySelector<HTMLScriptElement>(+ `script[src="${RRWEB_URL}"]`,+ )+ expect(failedScript).toBeTruthy()+ failedScript!.dispatchEvent(new Event('error'))++ await failedStart+ expect((window as any).__SWETRIX_RRWEB_LOADING__).toBeUndefined()++ const retryStart = startSessionReplay()+ const scripts = document.querySelectorAll<HTMLScriptElement>(+ `script[src="${RRWEB_URL}"]`,+ )+ expect(scripts).toHaveLength(2)+ ;(window as any).rrweb = { record }+ scripts[1].dispatchEvent(new Event('load'))++ const actions = await retryStart+ expect(record).toHaveBeenCalled()++ await actions.stop()+ })+test('user rrweb emit is composed with Swetrix uploads', async () => {const record = jest.fn((options) => {;(record as any).options = optionsdiff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.tsindex 39a294c42..d10de09dc 100644--- a/web/app/hooks/useAnalyticsProxy.ts+++ b/web/app/hooks/useAnalyticsProxy.ts@@ -196,10 +196,16 @@ async function parseExportProxyResponse(export function useSessionReplayExportProxy() {const startSessionReplayExport = useCallback(- async (projectId: string, psid: string, replayId?: string) => {+ async (+ projectId: string,+ psid: string,+ replayId?: string,+ signal?: AbortSignal,+ ) => {const response = await fetch('/api/session-replay-export', {method: 'POST',headers: { 'Content-Type': 'application/json' },+ signal,body: JSON.stringify({ projectId, psid, replayId }),})@@ -209,9 +215,11 @@ export function useSessionReplayExportProxy() {)const getSessionReplayExportStatus = useCallback(- async (projectId: string, exportId: string) => {+ async (projectId: string, exportId: string, signal?: AbortSignal) => {const query = new URLSearchParams({ projectId, exportId })- const response = await fetch(`/api/session-replay-export?${query}`)+ const response = await fetch(`/api/session-replay-export?${query}`, {+ signal,+ })return parseExportProxyResponse(response)},diff --git a/web/app/pages/Project/Settings/tabs/SessionReplays.tsx b/web/app/pages/Project/Settings/tabs/SessionReplays.tsxindex 4d69970b0..36966fa21 100644--- a/web/app/pages/Project/Settings/tabs/SessionReplays.tsx+++ b/web/app/pages/Project/Settings/tabs/SessionReplays.tsx@@ -80,6 +80,7 @@ const SessionReplays = ({<label key={days} className={className}><inputtype='radio'+ name='retention'className='sr-only'aria-label={label}checked={active}diff --git a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsxindex 6522a54fc..c59d96c3f 100644--- a/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx+++ b/web/app/pages/Project/tabs/Sessions/SessionReplayModal.tsx@@ -1061,6 +1061,8 @@ const SessionReplayModal = ({const previewReplayer = useRef<Replayer | null>(null)const previewSeekRaf = useRef<number | null>(null)const exportPollTimeout = useRef<number | null>(null)+ const exportAbortController = useRef<AbortController | null>(null)+ const isModalOpenRef = useRef(isOpen)const playStart = useRef({ offset: 0, at: 0, speed: 1 })const currentTimeRef = useRef(0)const speedRef = useRef(1)@@ -1166,8 +1168,14 @@ const SessionReplayModal = ({window.clearTimeout(exportPollTimeout.current)exportPollTimeout.current = null}+ exportAbortController.current?.abort()+ exportAbortController.current = null}, [])+ useEffect(() => {+ isModalOpenRef.current = isOpen+ }, [isOpen])+useEffect(() => {currentTimeRef.current = currentTime}, [currentTime])@@ -1640,6 +1648,8 @@ const SessionReplayModal = ({const handleExportStatus = useCallback((status: SessionReplayExportResponse) => {+ if (!isModalOpenRef.current) return true+setExportStatus(status)if (status.status === 'ready') {@@ -1680,28 +1690,48 @@ const SessionReplayModal = ({clearExportPoll()const poll = async () => {+ if (!isModalOpenRef.current) return++ const controller = new AbortController()+ exportAbortController.current = controller+try {- const status = await getSessionReplayExportStatus(projectId, exportId)+ const status = await getSessionReplayExportStatus(+ projectId,+ exportId,+ controller.signal,+ )++ if (!isModalOpenRef.current || controller.signal.aborted) returnif (handleExportStatus(status)) return+ if (!isModalOpenRef.current) returnexportPollTimeout.current = window.setTimeout(poll,EXPORT_POLL_INTERVAL_MS,)} catch {+ if (!isModalOpenRef.current || controller.signal.aborted) return+clearExportPoll()setIsExportStarting(false)setExportStatus(null)toast.error(t('project.sessionReplay.exportFailed'), {id: exportToastId,})+ } finally {+ if (exportAbortController.current === controller) {+ exportAbortController.current = null+ }}}- exportPollTimeout.current = window.setTimeout(- poll,- EXPORT_POLL_INTERVAL_MS,- )+ if (isModalOpenRef.current) {+ exportPollTimeout.current = window.setTimeout(+ poll,+ EXPORT_POLL_INTERVAL_MS,+ )+ }},[clearExportPoll,@@ -1717,6 +1747,8 @@ const SessionReplayModal = ({if (!canControlReplay || isReplayExporting) returnclearExportPoll()+ const controller = new AbortController()+ exportAbortController.current = controllersetIsExportStarting(true)setSettingsOpen(false)toast.loading(t('project.sessionReplay.exportPreparing'), {@@ -1728,13 +1760,19 @@ const SessionReplayModal = ({projectId,psid,selectedReplayId,+ controller.signal,)++ if (!isModalOpenRef.current || controller.signal.aborted) return+setIsExportStarting(false)if (!handleExportStatus(status)) {startExportPolling(status.exportId)}} catch (reason) {+ if (!isModalOpenRef.current || controller.signal.aborted) return+setIsExportStarting(false)setExportStatus(null)toast.error(@@ -1743,6 +1781,10 @@ const SessionReplayModal = ({: t('project.sessionReplay.exportFailed'),{ id: exportToastId },)+ } finally {+ if (exportAbortController.current === controller) {+ exportAbortController.current = null+ }}}, [canControlReplay,@@ -1759,6 +1801,7 @@ const SessionReplayModal = ({])const close = () => {+ isModalOpenRef.current = falsereplayer.current?.pause()clearExportPoll()setIsPlaying(false)diff --git a/web/app/routes/api.session-replay-export.ts b/web/app/routes/api.session-replay-export.tsindex 4a0161cf2..9a516f0f9 100644--- a/web/app/routes/api.session-replay-export.ts+++ b/web/app/routes/api.session-replay-export.ts@@ -26,12 +26,21 @@ const getCookieHeaders = (cookies: string[]) => {}export async function action({ request }: ActionFunctionArgs) {- const body = (await request.json()) as {+ let body: {projectId?: stringpsid?: stringreplayId?: string}+ try {+ body = (await request.json()) as typeof body+ } catch {+ return data<ProxyResponse<SessionReplayExportResponse>>(+ { data: null, error: 'Invalid JSON body' },+ { status: 400 },+ )+ }+if (!body.projectId || !body.psid) {return data<ProxyResponse<SessionReplayExportResponse>>({ data: null, error: 'projectId and psid are required' },