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!

Pre-launch improvements

Blue Mouse35ae30356b5e
diff --git a/admin/src/billing/pricing.ts b/admin/src/billing/pricing.ts
index 091b818a2..67785fb8c 100644
--- a/admin/src/billing/pricing.ts
+++ b/admin/src/billing/pricing.ts
@@ -52,7 +52,7 @@ export const planEntitlements = {
teamMembers: 25,
organisations: 10,
apiRateLimitPerHour: 5000,
- sessionReplaysIncluded: 50000,
+ sessionReplaysIncluded: 'byEventTier',
},
[PlanType.enterprise]: {
websites: 'custom',
@@ -63,6 +63,21 @@ export const planEntitlements = {
},
} as const
+const sessionReplayQuotas: 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 numberValue = (source: Record<string, unknown> | null, key: string) =>
source && typeof source[key] === 'number' ? (source[key] as number) : null
@@ -88,6 +103,11 @@ export const getEffectiveLimits = (user: User) => {
user.entitlementOverrides,
'sessionReplaysIncluded',
)
+ const replayQuota =
+ replayOverride ??
+ (entitlements.sessionReplaysIncluded === 'byEventTier'
+ ? sessionReplayQuotas[user.planCode] || 0
+ : entitlements.sessionReplaysIncluded)
const websites =
websiteOverride ??
(typeof entitlements.websites === 'number'
@@ -105,7 +125,7 @@ export const getEffectiveLimits = (user: User) => {
websitesIncluded:
typeof websites === 'number' ? websites + addonWebsites : websites,
purchasedWebsiteAddons: addonWebsites,
- replayQuota: replayOverride ?? entitlements.sessionReplaysIncluded,
+ replayQuota,
apiRateLimitPerHour,
}
}
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 6c34c6382..d597e014a 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -143,6 +143,7 @@ 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 SESSION_REPLAY_CHUNK_FETCH_CONCURRENCY = 6
const SOFTWARE_WITH_PATCH_VERSION = ['GameVault']
@@ -151,6 +152,29 @@ type FunnelStepDetails = Record<
Record<number, Record<string, number>>
>
+const mapLimit = async <T, R>(
+ items: T[],
+ limit: number,
+ fn: (item: T, index: number) => Promise<R>,
+): Promise<R[]> => {
+ const results: R[] = new Array(items.length)
+ const concurrency = Math.max(1, Math.min(limit, items.length))
+ let nextIndex = 0
+
+ const workers = Array.from({ length: concurrency }).map(async () => {
+ while (true) {
+ const current = nextIndex++
+ if (current >= items.length) {
+ break
+ }
+ results[current] = await fn(items[current], current)
+ }
+ })
+
+ await Promise.all(workers)
+ return results
+}
+
const GMT_0_TIMEZONES = [
'Atlantic/Azores',
'Etc/GMT',
@@ -1738,15 +1762,37 @@ export class AnalyticsService {
].join('/')
}
- private getReplayUsageKey(pid: string, psid: string, replayId: string) {
- return `session-replay:usage:${dayjs.utc().format('YYYY-MM')}:${pid}:${psid}:${replayId}`
+ private getReplayUsageKey(
+ accountId: string,
+ pid: string,
+ psid: string,
+ replayId: string,
+ ) {
+ return `session-replay:usage:${dayjs.utc().format('YYYY-MM')}:${accountId}:${pid}:${psid}:${replayId}`
}
private getReplayUsageTtlSeconds() {
return Math.max(60, dayjs.utc().endOf('month').diff(dayjs.utc(), 'second'))
}
- private async getMonthlyReplayUsage(pid: string): Promise<number> {
+ private async getReplayAccountProjectIds(
+ project: Project,
+ pid: string,
+ ): Promise<string[]> {
+ const adminId = project.admin?.id
+ if (!adminId) {
+ return [pid]
+ }
+
+ const projectIds = await this.projectService.getProjectIdsByAdminId(adminId)
+ return Array.from(new Set([pid, ...projectIds])).filter(Boolean)
+ }
+
+ private async getMonthlyReplayUsage(pids: string[]): Promise<number> {
+ if (_isEmpty(pids)) {
+ return 0
+ }
+
const monthStart = dayjs
.utc()
.startOf('month')
@@ -1757,10 +1803,10 @@ export class AnalyticsService {
query: `
SELECT uniqExact(concat(toString(psid), ':', replayId)) AS usage
FROM session_replay_chunks
- WHERE pid = {pid:FixedString(12)}
+ WHERE pid IN {pids:Array(FixedString(12))}
AND created >= {monthStart:DateTime}
`,
- query_params: { pid, monthStart },
+ query_params: { pids, monthStart },
})
.then((resultSet) => resultSet.json<{ usage: number }>())
@@ -1773,7 +1819,8 @@ export class AnalyticsService {
psid: string,
replayId: string,
): Promise<{ reserved: boolean; key?: string }> {
- const key = this.getReplayUsageKey(pid, psid, replayId)
+ const accountId = project.admin?.id || pid
+ const key = this.getReplayUsageKey(accountId, pid, psid, replayId)
const result = await redis.set(
key,
'1',
@@ -1788,7 +1835,8 @@ export class AnalyticsService {
const quota = getSessionReplayQuota(project.admin)
if (quota !== 'custom') {
- const usage = await this.getMonthlyReplayUsage(pid)
+ const pids = await this.getReplayAccountProjectIds(project, pid)
+ const usage = await this.getMonthlyReplayUsage(pids)
if (usage >= quota) {
await redis.del(key)
throw new HttpException(
@@ -1973,7 +2021,7 @@ export class AnalyticsService {
const { data: chunks } = await clickhouse
.query({
query: `
- SELECT objectKey
+ SELECT chunkIndex, objectKey
FROM session_replay_chunks
WHERE pid = {pid:FixedString(12)}
AND psid = toUInt64OrNull({psid:String})
@@ -1983,26 +2031,28 @@ export class AnalyticsService {
`,
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,
+ .then((resultSet) =>
+ resultSet.json<{ chunkIndex: number; objectKey: string }>(),
)
- if (!compressed) continue
- const parsed = JSON.parse(gunzipSync(compressed).toString('utf8')) as {
- events?: Record<string, unknown>[]
- }
+ const chunkEvents = await mapLimit(
+ chunks,
+ SESSION_REPLAY_CHUNK_FETCH_CONCURRENCY,
+ async (chunk) => {
+ const compressed = await this.sessionReplayStorage.getObject(
+ chunk.objectKey,
+ )
+ if (!compressed) return []
- if (Array.isArray(parsed.events)) {
- events.push(...parsed.events)
- }
- }
+ const parsed = JSON.parse(gunzipSync(compressed).toString('utf8')) as {
+ events?: Record<string, unknown>[]
+ }
+
+ return Array.isArray(parsed.events) ? parsed.events : []
+ },
+ )
- events.sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0))
+ const events = chunkEvents.flat()
return {
replay: await this.getSessionReplaySummary(pid, psid, selectedReplayId),
@@ -2035,21 +2085,28 @@ export class AnalyticsService {
const objectKeys = data.map((row) => row.objectKey)
- await Promise.allSettled(
+ const deleteResults = await Promise.allSettled(
objectKeys.map((objectKey) =>
this.sessionReplayStorage.deleteObject(objectKey),
),
)
+ const deletedObjectKeys = objectKeys.filter(
+ (_, index) => deleteResults[index].status === 'fulfilled',
+ )
+
+ if (_isEmpty(deletedObjectKeys)) {
+ return 0
+ }
await clickhouse.command({
query: `
ALTER TABLE session_replay_chunks
DELETE WHERE objectKey IN ({objectKeys:Array(String)})
`,
- query_params: { objectKeys },
+ query_params: { objectKeys: deletedObjectKeys },
})
- return objectKeys.length
+ return deletedObjectKeys.length
}
formatFunnel(data: IFunnelCHResponse[], pages: string[]): IFunnel[] {
diff --git a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
index 3a8989731..19a4d6736 100644
--- a/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/session-replay.dto.ts
@@ -18,7 +18,7 @@ import { Type } from 'class-transformer'
import { PID_REGEX } from '../../common/constants'
import { GetDataDto } from './getData.dto'
-const SESSION_REPLAY_PRIVACY_MODES = ['total', 'normal', 'free-love'] as const
+const SESSION_REPLAY_PRIVACY_MODES = ['total', 'normal', 'none'] as const
export type SessionReplayPrivacyMode =
(typeof SESSION_REPLAY_PRIVACY_MODES)[number]
@@ -34,7 +34,7 @@ export class SessionReplayStartDto {
@MaxLength(80)
replayId: string
- @ApiProperty({ enum: SESSION_REPLAY_PRIVACY_MODES, default: 'normal' })
+ @ApiProperty({ enum: SESSION_REPLAY_PRIVACY_MODES, default: 'total' })
@IsIn(SESSION_REPLAY_PRIVACY_MODES)
privacy: SessionReplayPrivacyMode
diff --git a/backend/migrations/clickhouse/2026_06_03_session_replays.js b/backend/migrations/clickhouse/2026_06_03_session_replays.js
index 709aecd2b..81280424c 100644
--- a/backend/migrations/clickhouse/2026_06_03_session_replays.js
+++ b/backend/migrations/clickhouse/2026_06_03_session_replays.js
@@ -19,8 +19,7 @@ const queries = [
)
ENGINE = ReplacingMergeTree(created)
PARTITION BY toYYYYMM(created)
- ORDER BY (pid, psid, replayId, chunkIndex)
- TTL expiresAt;`,
+ ORDER BY (pid, psid, replayId, chunkIndex);`,
]
queriesRunner(queries)
diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.js
index 49c44b4d2..cc079eae6 100644
--- a/backend/migrations/clickhouse/initialise_database.js
+++ b/backend/migrations/clickhouse/initialise_database.js
@@ -167,8 +167,7 @@ const CLICKHOUSE_INIT_QUERIES = [
)
ENGINE = ReplacingMergeTree(created)
PARTITION BY toYYYYMM(created)
- ORDER BY (pid, psid, replayId, chunkIndex)
- TTL expiresAt;`,
+ ORDER BY (pid, psid, replayId, chunkIndex);`,
]
const initialiseDatabase = async () => {
diff --git a/docs/content/docs/analytics-dashboard/session-replays.mdx b/docs/content/docs/analytics-dashboard/session-replays.mdx
index d4794a9fa..e6a21fdc7 100644
--- a/docs/content/docs/analytics-dashboard/session-replays.mdx
+++ b/docs/content/docs/analytics-dashboard/session-replays.mdx
@@ -82,7 +82,7 @@ Choose the privacy mode in code when you start the replay:
- `total`: masks all text and inputs, and blocks media/canvas content.
- `normal`: masks all inputs. This is the default.
-- `free-love`: only forces password inputs to stay masked unless you add your own recorder masking options.
+- `none`: only forces password inputs to stay masked unless you add your own recorder masking options.
Configure replay retention in **Project Settings > Session replays**. Retention changes apply only to newly recorded replay chunks; existing replay chunks keep the expiry date they were recorded with.
diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdx
index fda3a9bf3..8e41c41fb 100644
--- a/docs/content/docs/script-reference.mdx
+++ b/docs/content/docs/script-reference.mdx
@@ -275,7 +275,7 @@ const replay = await startSessionReplay({
| 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 `free-love` 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. | `normal` |
| 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/README.md b/packages/tracker-js/README.md
index 51c28452d..afa66f8f0 100644
--- a/packages/tracker-js/README.md
+++ b/packages/tracker-js/README.md
@@ -194,6 +194,33 @@ const variantWithFallback = await getExperiment('checkout-redesign-experiment-id
clearExperimentsCache()
```
+### `startSessionReplay(options?)`
+
+Start recording a session replay. Session replays use `total` privacy by default, which masks text and inputs and blocks media/canvas capture unless you explicitly choose another mode.
+
+```javascript
+const replay = await startSessionReplay({
+ privacy: 'total',
+ sampleRate: 0.25,
+ maxDurationMs: 10 * 60 * 1000,
+ idleTimeoutMs: 2 * 60 * 1000,
+})
+
+// Stop or flush manually when needed
+await replay.flush()
+await replay.stop()
+```
+
+| Option | Description | Default |
+|---|---|---|
+| `privacy` | Privacy mode: `total`, `normal`, or `none`. | `'total'` |
+| `sampleRate` | Fraction of sessions to record (`0` to `1`). | `1` |
+| `maxDurationMs` | Stop recording after this duration. | `undefined` |
+| `idleTimeoutMs` | Stop recording after this much visitor inactivity. | `undefined` |
+| `flushIntervalMs` | Upload buffered replay events at this interval. | `5000` |
+| `maxEventsPerChunk` | Upload once this many events are buffered. | `100` |
+| `rrweb` | Additional rrweb record options. | `undefined` |
+
### Session & Profile IDs
```javascript
diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.ts
index a6a7b2175..b185fd326 100644
--- a/packages/tracker-js/src/Lib.ts
+++ b/packages/tracker-js/src/Lib.ts
@@ -192,13 +192,16 @@ export interface ErrorActions {
stop: () => void
}
-export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+export type SessionReplayPrivacy = 'total' | 'normal' | 'none'
export interface SessionReplayOptions {
privacy?: SessionReplayPrivacy
rrweb?: RrwebRecordOptions
flushIntervalMs?: number
maxEventsPerChunk?: number
+ sampleRate?: number
+ maxDurationMs?: number
+ idleTimeoutMs?: number
}
export interface SessionReplayActions {
@@ -279,6 +282,15 @@ 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
+const DEFAULT_SESSION_REPLAY_PRIVACY: SessionReplayPrivacy = 'total'
+const SESSION_REPLAY_ACTIVITY_EVENTS = [
+ 'click',
+ 'keydown',
+ 'mousedown',
+ 'mousemove',
+ 'scroll',
+ 'touchstart',
+] as const
// Default cache duration: 5 minutes
const DEFAULT_CACHE_DURATION = 5 * 60 * 1000
@@ -773,6 +785,10 @@ export class Lib {
return defaultSessionReplayActions
}
+ if (!this.shouldSampleSessionReplay(options.sampleRate)) {
+ return defaultSessionReplayActions
+ }
+
try {
await this.preloadSessionReplay()
} catch {
@@ -784,7 +800,7 @@ export class Lib {
return defaultSessionReplayActions
}
- const privacy = options.privacy || 'normal'
+ const privacy = options.privacy || DEFAULT_SESSION_REPLAY_PRIVACY
const replayId = this.createReplayId()
const started = await this.sendSessionReplayStart(replayId, privacy)
@@ -801,11 +817,21 @@ export class Lib {
options.maxEventsPerChunk > 0
? Math.floor(options.maxEventsPerChunk)
: DEFAULT_SESSION_REPLAY_MAX_EVENTS
+ const maxDurationMs =
+ typeof options.maxDurationMs === 'number' && options.maxDurationMs > 0
+ ? options.maxDurationMs
+ : null
+ const idleTimeoutMs =
+ typeof options.idleTimeoutMs === 'number' && options.idleTimeoutMs > 0
+ ? options.idleTimeoutMs
+ : null
let chunkIndex = 0
let stopped = false
let events: RrwebEvent[] = []
let flushing = Promise.resolve()
+ let maxDurationTimer: ReturnType<typeof setTimeout> | undefined
+ let idleTimer: ReturnType<typeof setTimeout> | undefined
const flush = async (useBeacon = false) => {
if (!events.length) return
@@ -853,21 +879,54 @@ export class Lib {
void flush(true)
}
}
+ const clearIdleTimer = () => {
+ if (idleTimer) {
+ clearTimeout(idleTimer)
+ idleTimer = undefined
+ }
+ }
+ const stopSessionReplay = async () => {
+ if (stopped) return
+ stopped = true
+ clearInterval(timer)
+ if (maxDurationTimer) {
+ clearTimeout(maxDurationTimer)
+ }
+ clearIdleTimer()
+ window.removeEventListener('pagehide', flushOnPageExit)
+ document.removeEventListener('visibilitychange', flushOnHidden)
+ SESSION_REPLAY_ACTIVITY_EVENTS.forEach((eventName) => {
+ window.removeEventListener(eventName, resetIdleTimer)
+ })
+ stopRecording?.()
+ await flush()
+ this.sessionReplayActions = null
+ }
+ const resetIdleTimer = () => {
+ if (!idleTimeoutMs || stopped) return
+ clearIdleTimer()
+ idleTimer = setTimeout(() => void stopSessionReplay(), idleTimeoutMs)
+ }
window.addEventListener('pagehide', flushOnPageExit)
document.addEventListener('visibilitychange', flushOnHidden)
+ if (maxDurationMs) {
+ maxDurationTimer = setTimeout(
+ () => void stopSessionReplay(),
+ maxDurationMs,
+ )
+ }
+
+ if (idleTimeoutMs) {
+ SESSION_REPLAY_ACTIVITY_EVENTS.forEach((eventName) => {
+ window.addEventListener(eventName, resetIdleTimer, { passive: true })
+ })
+ resetIdleTimer()
+ }
+
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
- },
+ stop: stopSessionReplay,
flush: async () => {
await flush()
},
@@ -876,6 +935,22 @@ export class Lib {
return this.sessionReplayActions
}
+ private shouldSampleSessionReplay(sampleRate?: number): boolean {
+ if (typeof sampleRate !== 'number') {
+ return true
+ }
+
+ if (sampleRate <= 0) {
+ return false
+ }
+
+ if (sampleRate >= 1) {
+ return true
+ }
+
+ return Math.random() < sampleRate
+ }
+
/**
* Gets the API base URL (without /log suffix).
*/
@@ -1061,7 +1136,7 @@ export class Lib {
emit: RrwebEmit,
): RrwebRecordOptions {
const options: RrwebRecordOptions = {
- ...(userOptions || {}),
+ ...userOptions,
emit,
}
diff --git a/packages/tracker-js/tests/sessionReplay.test.ts b/packages/tracker-js/tests/sessionReplay.test.ts
index bc569373b..72d708126 100644
--- a/packages/tracker-js/tests/sessionReplay.test.ts
+++ b/packages/tracker-js/tests/sessionReplay.test.ts
@@ -122,6 +122,16 @@ describe('Session replay tracking', () => {
const actions = await startPromise
const recordOptions = (record as any).options
+ expect(recordOptions.maskTextSelector).toBe('*')
+
+ 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' }),
+ )
+
recordOptions.emit({ type: 2, timestamp: 100 })
recordOptions.emit({ type: 3, timestamp: 200 })
@@ -142,6 +152,86 @@ describe('Session replay tracking', () => {
await actions.stop()
})
+ test('sampleRate can skip recording before loading rrweb', async () => {
+ const { init, startSessionReplay } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true })
+ const actions = await startSessionReplay({ sampleRate: 0 })
+ await actions.flush()
+ await actions.stop()
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(document.querySelector(`script[src="${RRWEB_URL}"]`)).toBeNull()
+ })
+
+ test('maxDurationMs stops recording and flushes buffered events', async () => {
+ jest.useFakeTimers()
+ const stopRecording = jest.fn()
+ const record = jest.fn((options) => {
+ ;(record as any).options = options
+ return stopRecording
+ })
+ const { init, startSessionReplay } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true })
+ const startPromise = startSessionReplay({
+ flushIntervalMs: 60_000,
+ maxDurationMs: 1000,
+ })
+ resolveRrwebScript(record)
+
+ await startPromise
+ ;(record as any).options.emit({ type: 2, timestamp: 100 })
+
+ await jest.advanceTimersByTimeAsync(1000)
+ await Promise.resolve()
+
+ expect(stopRecording).toHaveBeenCalledTimes(1)
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.swetrix.com/log/session-replay/chunk',
+ expect.objectContaining({
+ body: expect.stringContaining('"timestamp":100'),
+ }),
+ )
+ })
+
+ test('idleTimeoutMs stops after inactivity and resets on activity', async () => {
+ jest.useFakeTimers()
+ const stopRecording = jest.fn()
+ const record = jest.fn((options) => {
+ ;(record as any).options = options
+ return stopRecording
+ })
+ const { init, startSessionReplay } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true })
+ const startPromise = startSessionReplay({
+ flushIntervalMs: 60_000,
+ idleTimeoutMs: 1000,
+ })
+ resolveRrwebScript(record)
+
+ await startPromise
+ ;(record as any).options.emit({ type: 2, timestamp: 200 })
+
+ await jest.advanceTimersByTimeAsync(900)
+ window.dispatchEvent(new Event('mousemove'))
+ await jest.advanceTimersByTimeAsync(900)
+
+ expect(stopRecording).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(100)
+ await Promise.resolve()
+
+ expect(stopRecording).toHaveBeenCalledTimes(1)
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.swetrix.com/log/session-replay/chunk',
+ expect.objectContaining({
+ body: expect.stringContaining('"timestamp":200'),
+ }),
+ )
+ })
+
test('privacy modes map to rrweb options and keep internal emit', () => {
const lib = new Lib(PROJECT_ID, { devMode: true })
const emit = jest.fn()
@@ -168,7 +258,7 @@ describe('Session replay tracking', () => {
expect(normal.emit).toBe(emit)
const freeLove = (lib as any).getSessionReplayRecordOptions(
- 'free-love',
+ 'none',
{ maskInputOptions: { email: false } },
emit,
)
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 924769694..f504e87fd 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -995,7 +995,7 @@ export interface SessionsResponse {
appliedFilters: AnalyticsFilter[]
}
-export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+export type SessionReplayPrivacy = 'total' | 'normal' | 'none'
export interface SessionReplayListItem extends Session {
replayId: string
diff --git a/web/app/components/marketing/FeaturesGrid.tsx b/web/app/components/marketing/FeaturesGrid.tsx
index d3e18c472..1f0c8740e 100644
--- a/web/app/components/marketing/FeaturesGrid.tsx
+++ b/web/app/components/marketing/FeaturesGrid.tsx
@@ -296,10 +296,7 @@ const ProductAnalyticsMockup = () => (
<div className='absolute top-0 left-0 w-[245px] -rotate-2 rounded-2xl bg-white p-4 ring-1 ring-gray-200 dark:bg-slate-900 dark:ring-slate-800'>
<div className='flex items-center gap-2'>
- <WarningOctagonIcon
- weight='duotone'
- className='size-5 text-red-500'
- />
+ <WarningOctagonIcon weight='duotone' className='size-5 text-red-500' />
<Text as='h3' size='sm' weight='semibold'>
Error tracking
</Text>
diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsx
index 036710d6a..2379f0833 100644
--- a/web/app/components/pricing/MarketingPricing.tsx
+++ b/web/app/components/pricing/MarketingPricing.tsx
@@ -28,6 +28,8 @@ import Tooltip from '~/ui/Tooltip'
import { cn } from '~/utils/generic'
import routes from '~/utils/routes'
+import SessionReplayPricingTooltip from './SessionReplayPricingTooltip'
+
interface MarketingPricingProps {
metainfo?: Metainfo
onSelectPlan?: (selection: MarketingPricingSelection) => void
@@ -53,6 +55,7 @@ interface BenefitTooltip {
interface Benefit {
label: string
tooltip?: BenefitTooltip
+ tooltipType?: 'sessionReplays'
}
const planCards: PlanTypeCode[] = ['standard', 'plus', 'enterprise']
@@ -177,7 +180,10 @@ const getBenefits = (planType: PlanTypeCode, t: TFunction): Benefit[] => {
})}`,
},
},
- { label: t('pricing.benefits.sessionReplays') },
+ {
+ label: t('pricing.benefits.sessionReplays'),
+ tooltipType: 'sessionReplays',
+ },
{ label: t('pricing.benefits.featureFlags') },
{ label: t('pricing.benefits.abTesting') },
{ label: t('pricing.benefits.twentyXHigherApiRateLimits') },
@@ -235,13 +241,17 @@ const PlanInheritanceRow = ({
return (
<div className='flex items-start gap-2.5'>
<ArrowLeftIcon
- className='mt-0.5 size-4 shrink-0 text-emerald-600'
+ className={cn('mt-0.5 size-4 shrink-0', {
+ 'text-gray-700 dark:text-gray-200': !isEnterprise,
+ 'text-gray-200': isEnterprise,
+ })}
weight='bold'
/>
<Text
as='p'
size='sm'
colour='primary'
+ weight='medium'
className={cn('italic', isEnterprise ? 'dark' : '')}
>
{label}
@@ -272,6 +282,9 @@ const BenefitRow = ({
>
{benefit.label}
</Text>
+ {benefit.tooltipType === 'sessionReplays' ? (
+ <SessionReplayPricingTooltip className={isEnterprise ? 'dark' : ''} />
+ ) : null}
{benefit.tooltip ? (
<Tooltip
ariaLabel={benefit.tooltip.ariaLabel}
diff --git a/web/app/components/pricing/SessionReplayPricingTooltip.tsx b/web/app/components/pricing/SessionReplayPricingTooltip.tsx
new file mode 100644
index 000000000..e454e6fc4
--- /dev/null
+++ b/web/app/components/pricing/SessionReplayPricingTooltip.tsx
@@ -0,0 +1,59 @@
+import { useTranslation } from 'react-i18next'
+
+import { DOCS_URL } from '~/lib/constants'
+import Tooltip from '~/ui/Tooltip'
+
+const sessionReplaysDocsUrl = `${DOCS_URL}/analytics-dashboard/session-replays`
+
+interface SessionReplayPricingTooltipProps {
+ className?: string
+ ariaLabel?: string
+}
+
+const SessionReplayPricingTooltipContent = () => {
+ const { t } = useTranslation('common')
+
+ return (
+ <span className='block space-y-2 text-pretty'>
+ <span className='block'>
+ {t('pricing.benefits.tooltips.sessionReplays.description')}
+ </span>
+ <span className='block'>
+ {t('pricing.benefits.tooltips.sessionReplays.recording')}
+ </span>
+ <span className='block'>
+ {t('pricing.benefits.tooltips.sessionReplays.quota')}
+ </span>
+ <span className='block'>
+ {t('pricing.benefits.tooltips.sessionReplays.plans')}
+ </span>
+ <a
+ href={sessionReplaysDocsUrl}
+ className='inline-flex font-semibold underline decoration-dashed hover:decoration-solid'
+ target='_blank'
+ rel='noreferrer noopener'
+ >
+ {t('common.learnMore')}
+ </a>
+ </span>
+ )
+}
+
+const SessionReplayPricingTooltip = ({
+ className,
+ ariaLabel,
+}: SessionReplayPricingTooltipProps) => {
+ const { t } = useTranslation('common')
+ const label = t('pricing.benefits.sessionReplays')
+
+ return (
+ <Tooltip
+ ariaLabel={ariaLabel || `${t('common.learnMore')}: ${label}`}
+ text={<SessionReplayPricingTooltipContent />}
+ className={className}
+ contentClassName='max-w-[calc(100vw-2rem)] sm:max-w-80'
+ />
+ )
+}
+
+export default SessionReplayPricingTooltip
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 37f97c449..99df1ba58 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -85,7 +85,7 @@ export interface SwetrixError {
sessions: number
}
-export type SessionReplayPrivacy = 'total' | 'normal' | 'free-love'
+export type SessionReplayPrivacy = 'total' | 'normal' | 'none'
export interface SessionReplayMetadata {
hasReplay: boolean
diff --git a/web/app/pages/Project/tabs/Replays/Replays.tsx b/web/app/pages/Project/tabs/Replays/Replays.tsx
index dbcb4e0ea..e7ccfe205 100644
--- a/web/app/pages/Project/tabs/Replays/Replays.tsx
+++ b/web/app/pages/Project/tabs/Replays/Replays.tsx
@@ -98,10 +98,7 @@ export const ReplayRow = ({
return t('project.unknownUser')
}
- return getProfileDisplayName(
- replay.profileId,
- Boolean(replay.isIdentified),
- )
+ return getProfileDisplayName(replay.profileId, Boolean(replay.isIdentified))
}, [replay.profileId, replay.isIdentified, t])
const replayStartedAt = useMemo(
@@ -112,11 +109,16 @@ export const ReplayRow = ({
timeFormat,
timezone,
),
- [language, replay.replayCreatedAt, replay.replayStart, timeFormat, timezone],
+ [
+ language,
+ replay.replayCreatedAt,
+ replay.replayStart,
+ timeFormat,
+ timezone,
+ ],
)
const replayExpiresAt = useMemo(
- () =>
- formatDate(replay.replayExpiresAt, language, timeFormat, timezone),
+ () => formatDate(replay.replayExpiresAt, language, timeFormat, timezone),
[language, replay.replayExpiresAt, timeFormat, timezone],
)
const durationString = useMemo(() => {
@@ -215,10 +217,7 @@ export const ReplayRow = ({
text={replay.br || t('project.unknown')}
tooltipNode={
<div className='flex h-[22px] w-[22px] items-center justify-center rounded bg-gray-100/80 ring-1 ring-gray-200/50 dark:bg-slate-800/80 dark:ring-slate-700/50'>
- <BrowserIcon
- browser={replay.br}
- className='size-3.5'
- />
+ <BrowserIcon browser={replay.br} className='size-3.5' />
</div>
}
/>
diff --git a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
index 811ff3308..154754ec9 100644
--- a/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
+++ b/web/app/pages/Project/tabs/Replays/ReplaysView.tsx
@@ -1,5 +1,14 @@
import _isEmpty from 'lodash/isEmpty'
-import { Component, lazy, Suspense, use, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ Component,
+ lazy,
+ Suspense,
+ use,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { useLoaderData, useRevalidator, useSearchParams } from 'react-router'
@@ -89,8 +98,7 @@ function ReplaysDataResolver({
}: {
children: (data: DeferredReplaysData) => React.ReactNode
}) {
- const { replaysData: replaysDataPromise } =
- useLoaderData<ProjectLoaderData>()
+ const { replaysData: replaysDataPromise } = useLoaderData<ProjectLoaderData>()
const replaysData = replaysDataPromise ? use(replaysDataPromise) : null
diff --git a/web/app/pages/Subscribe/Subscribe.tsx b/web/app/pages/Subscribe/Subscribe.tsx
index 541ce371e..79108f710 100644
--- a/web/app/pages/Subscribe/Subscribe.tsx
+++ b/web/app/pages/Subscribe/Subscribe.tsx
@@ -12,6 +12,7 @@ import { Trans, useTranslation } from 'react-i18next'
import { useFetcher, useLoaderData, useNavigate } from 'react-router'
import { toast } from 'sonner'
+import SessionReplayPricingTooltip from '~/components/pricing/SessionReplayPricingTooltip'
import { usePaddle } from '~/hooks/usePaddle'
import { CURRENCIES, paddleLanguageMapping, TRIAL_DAYS } from '~/lib/constants'
import {
@@ -447,23 +448,26 @@ const Subscribe = () => {
<div className='rounded-lg bg-white p-4 ring-1 ring-gray-200 ring-inset dark:bg-slate-950 dark:ring-slate-800'>
<div className='flex flex-wrap items-center justify-between gap-3'>
- <div>
+ <div className='min-w-0'>
<Text as='p' size='base' weight='semibold'>
{getPlanName(selectedPlanType, t)}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mt-1'>
- {formatEventsLong(
- EVENT_TIERS[selectedEventTier].monthlyEvents,
- i18n.language,
- )}{' '}
- {t('pricing.eventsWithReplay', {
- replayQuota: formatReplayQuota(
- replayQuota,
- t,
+ <div className='mt-1 flex min-w-0 items-start gap-1.5'>
+ <Text as='p' size='sm' colour='secondary'>
+ {formatEventsLong(
+ EVENT_TIERS[selectedEventTier].monthlyEvents,
i18n.language,
- ),
- })}
- </Text>
+ )}{' '}
+ {t('pricing.eventsWithReplay', {
+ replayQuota: formatReplayQuota(
+ replayQuota,
+ t,
+ i18n.language,
+ ),
+ })}
+ </Text>
+ <SessionReplayPricingTooltip className='mt-0.5 shrink-0' />
+ </div>
</div>
<Text as='p' size='2xl' weight='bold'>
{monthlyPrice === null ? (
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index ec074ce9b..75c93a3aa 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -220,7 +220,7 @@ export async function action({ request }: ActionFunctionArgs) {
? result.error.join(', ')
: result.error
: null,
- })
+ })
}
case 'getSessionReplays': {
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index fe9c3a71f..b116fc46d 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -3135,7 +3135,7 @@
},
"benefits": {
"funnels": "Funnels",
- "everythingFrom": "everything from {{plan}}",
+ "everythingFrom": "Everything from {{plan}}",
"unlimitedMembers": "Unlimited members",
"eventsAndGoals": "Events & Goals",
"sessionUserProfileAnalysis": "Session & User profile analysis",
@@ -3164,6 +3164,12 @@
"tooltips": {
"advancedBotDetection": "Swetrix filters automated traffic before it is stored, from known bot user agents and headless browsers to stricter checks for suspicious headers, probe paths, referrer spam, and datacenter IPs. Blocked bot requests never count toward your event quota.",
"adBlockerBypass": "Route the tracker script and analytics traffic through a managed reverse proxy on your own subdomain, so requests are served first-party from your domain.",
+ "sessionReplays": {
+ "description": "A session replay is a recorded browser session that you can play back to debug user journeys, errors, and drop-offs.",
+ "recording": "Replays are recorded only after you explicitly start recording through the tracker. Regular analytics events and pageviews do not create replays automatically.",
+ "quota": "Quota is based on recorded replays, also shown as recorded sessions, per month. It is not based on replay minutes, storage size, or how many times a replay is watched.",
+ "plans": "Standard includes 0 replays, Plus includes a monthly quota proportional to the selected event tier, and Enterprise is custom."
+ },
"plusWebsites": "Swetrix has no limit on the number of websites you can add. You can purchase more websites via add-ons. Bulk discounts are available if you contact support.",
"customEventLimits": "Enterprise plans are flexible for event limits, API rate limits, and project quantity.",
"manualInvoicing": "We accept all major credit & debit cards. Enterprise customers can also pay by ACH, SEPA, wire transfer, or invoice."