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!

Optimise session replay capture and privacy controls

Blue Mouse93d130a6a700
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 6d20a4368..b92ac28b1 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -142,6 +142,7 @@ 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_EVENT_BYTES = 5 * 1024 * 1024
const MAX_SESSION_REPLAY_CHUNK_BYTES = 15 * 1024 * 1024
const MAX_SESSION_REPLAY_CHUNKS_PER_REPLAY = 1200
const MAX_SESSION_REPLAY_EVENTS_PER_REPLAY = 100000
@@ -2156,6 +2157,23 @@ export class AnalyticsService {
}
}
+ private validateSessionReplayEventSizes(events: Record<string, unknown>[]) {
+ const hasOversizedEvent = events.some((event) => {
+ try {
+ return (
+ Buffer.byteLength(JSON.stringify(event)) >
+ MAX_SESSION_REPLAY_EVENT_BYTES
+ )
+ } catch {
+ return true
+ }
+ })
+
+ if (hasOversizedEvent) {
+ throw new PayloadTooLargeException('Session replay event is too large')
+ }
+ }
+
async storeSessionReplayChunk(
project: Project,
pid: string,
@@ -2176,6 +2194,8 @@ export class AnalyticsService {
throw new BadRequestException('Session replay chunk has too many events')
}
+ this.validateSessionReplayEventSizes(events)
+
const psid = await this.resolveReplaySession(pid, userAgent, ip)
const retention = this.getSessionReplayRetention(project)
const payload = JSON.stringify({ events })
diff --git a/docs/content/docs/analytics-dashboard/session-replays.mdx b/docs/content/docs/analytics-dashboard/session-replays.mdx
index d8331dd54..137c1fcf4 100644
--- a/docs/content/docs/analytics-dashboard/session-replays.mdx
+++ b/docs/content/docs/analytics-dashboard/session-replays.mdx
@@ -27,6 +27,8 @@ swetrix.init("YOUR_PROJECT_ID", {
await swetrix.startSessionReplay({
privacy: "total",
+ maskAllText: true,
+ maxBytesPerChunk: 512 * 1024,
});
```
@@ -34,6 +36,61 @@ The optional `preloadSessionReplay: true` setting preloads the replay recorder.
See the [tracking script reference](/swetrix-js-reference#startsessionreplay) for all privacy modes, recorder options, and code examples.
+To mask all text while using the less restrictive `normal` privacy mode, set `maskAllText: true`:
+
+```javascript
+await swetrix.startSessionReplay({
+ privacy: "normal",
+ maskAllText: true,
+});
+```
+
+## Replay size controls
+
+Swetrix keeps replay recordings lighter by default:
+
+- Mousemove and scroll events are sampled before upload.
+- Script tags, comments, and noisy metadata are removed from DOM snapshots where possible.
+- Media, canvas, SVG, inline images, fonts, and iframe content are not recorded unless you opt into more capture.
+- Replay chunks are uploaded when they reach 100 events or roughly 512 KiB, whichever happens first.
+- A single replay event larger than 5 MiB is dropped before upload.
+
+You can tune the client-side chunk limits:
+
+```javascript
+await swetrix.startSessionReplay({
+ maxEventsPerChunk: 100,
+ maxBytesPerChunk: 512 * 1024,
+ maxBytesPerEvent: 5 * 1024 * 1024,
+});
+```
+
+## Recording iframes
+
+Iframe capture is disabled by default because embedded pages can be large, sensitive, or controlled by another vendor. This keeps replay storage predictable and avoids recording third-party content unintentionally.
+
+If the iframe is part of your own product and you need it in the replay, enable it explicitly:
+
+```javascript
+await swetrix.startSessionReplay({
+ privacy: "normal",
+ recordIframes: true,
+});
+```
+
+Cross-origin iframe recording also requires rrweb's cross-origin iframe support and should only be enabled for domains you control:
+
+```javascript
+await swetrix.startSessionReplay({
+ recordIframes: true,
+ rrweb: {
+ recordCrossOriginIframes: true,
+ },
+});
+```
+
+Third-party iframes that you do not control cannot be captured reliably because browsers restrict access to their contents.
+
## Replays list
Open the **Replays** tab in your project dashboard to see recorded sessions for the selected date range.
@@ -90,6 +147,8 @@ Choose the privacy mode in code when you start the replay:
- `normal`: masks all inputs.
- `none`: only forces password inputs to stay masked unless you add your own recorder masking options.
+Set `maskAllText: true` to mask all non-input text with asterisks in any privacy mode. If you do not set it explicitly, Swetrix enables it for `total` privacy and leaves it disabled for `normal` and `none`.
+
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.
<Callout type="warn">
diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdx
index a092d1084..28bb1929f 100644
--- a/docs/content/docs/script-reference.mdx
+++ b/docs/content/docs/script-reference.mdx
@@ -255,6 +255,8 @@ swetrix.init("YOUR_PROJECT_ID", {
const replay = await swetrix.startSessionReplay({
privacy: "total",
+ maskAllText: true,
+ maxBytesPerChunk: 512 * 1024,
});
await replay.stop();
@@ -271,6 +273,8 @@ init("YOUR_PROJECT_ID", {
const replay = await startSessionReplay({
privacy: "total",
+ maskAllText: true,
+ maxBytesPerChunk: 512 * 1024,
});
```
@@ -279,9 +283,42 @@ For npm installs, Swetrix dynamically imports the installed `rrweb` package only
| 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. | `total` |
+| maskAllText | Masks all non-input text with asterisks. Defaults to `true` when `privacy` is `total`, and `false` for `normal` or `none`. | privacy-based |
| 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` |
+| maxBytesPerChunk | The approximate maximum byte size to buffer before Swetrix uploads a chunk immediately. | `524288` |
+| maxBytesPerEvent | Drops a single replay event if it is larger than this many bytes. This protects the visitor's browser and your replay storage from unusually large snapshots. | `5242880` |
+| recordIframes | Allows iframe elements to be captured. Iframes are blocked by default to reduce replay size and avoid recording embedded third-party content. | `false` |
+
+To mask text while keeping media less restricted than `total` privacy, combine `normal` privacy with `maskAllText`:
+
+```javascript
+await swetrix.startSessionReplay({
+ privacy: "normal",
+ maskAllText: true,
+});
+```
+
+By default, iframe elements are blocked from replay snapshots. If you own the iframe content and need it in the replay, opt in explicitly:
+
+```javascript
+await swetrix.startSessionReplay({
+ privacy: "normal",
+ recordIframes: true,
+});
+```
+
+Cross-origin iframe recording also requires rrweb's cross-origin iframe support and should only be enabled for domains you control:
+
+```javascript
+await swetrix.startSessionReplay({
+ recordIframes: true,
+ rrweb: {
+ recordCrossOriginIframes: true,
+ },
+});
+```
The function returns a `Promise` with controls for the active replay:
diff --git a/packages/tracker-js/README.md b/packages/tracker-js/README.md
index 2f2415c37..e34620fa0 100644
--- a/packages/tracker-js/README.md
+++ b/packages/tracker-js/README.md
@@ -205,9 +205,11 @@ If you use the npm package, rrweb is dynamically imported from your installed de
```javascript
const replay = await startSessionReplay({
privacy: 'total',
+ maskAllText: true,
sampleRate: 0.25,
maxDurationMs: 10 * 60 * 1000,
idleTimeoutMs: 2 * 60 * 1000,
+ maxBytesPerChunk: 512 * 1024,
})
// Stop or flush manually when needed
@@ -218,13 +220,46 @@ await replay.stop()
| Option | Description | Default |
|---|---|---|
| `privacy` | Privacy mode: `total`, `normal`, or `none`. | `'total'` |
+| `maskAllText` | Mask all non-input text with asterisks. Defaults to `true` when `privacy` is `total`, otherwise `false`. | privacy-based |
| `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` |
+| `maxBytesPerChunk` | Upload once buffered replay events reach this approximate byte size. | `524288` |
+| `maxBytesPerEvent` | Drop a single replay event if it is larger than this many bytes. | `5242880` |
+| `recordIframes` | Allow iframe elements to be captured. Iframes are blocked by default to reduce replay size and avoid recording embedded third-party content. | `false` |
| `rrweb` | Additional rrweb record options. | `undefined` |
+To mask text while keeping media less restricted than `total` privacy, combine `normal` privacy with `maskAllText`:
+
+```javascript
+await startSessionReplay({
+ privacy: 'normal',
+ maskAllText: true,
+})
+```
+
+By default, Swetrix blocks iframe elements from replay snapshots. If you own the iframe content and need it in the replay, opt in explicitly:
+
+```javascript
+await startSessionReplay({
+ privacy: 'normal',
+ recordIframes: true,
+})
+```
+
+Cross-origin iframe recording also requires rrweb's cross-origin iframe support and should only be enabled for domains you control:
+
+```javascript
+await startSessionReplay({
+ recordIframes: true,
+ rrweb: {
+ recordCrossOriginIframes: true,
+ },
+})
+```
+
### Session & Profile IDs
```javascript
diff --git a/packages/tracker-js/src/Lib.ts b/packages/tracker-js/src/Lib.ts
index a42bb85a6..f3319ef75 100644
--- a/packages/tracker-js/src/Lib.ts
+++ b/packages/tracker-js/src/Lib.ts
@@ -208,9 +208,13 @@ export interface SessionReplayOptions {
rrweb?: RrwebRecordOptions
flushIntervalMs?: number
maxEventsPerChunk?: number
+ maxBytesPerChunk?: number
+ maxBytesPerEvent?: number
sampleRate?: number
maxDurationMs?: number
idleTimeoutMs?: number
+ maskAllText?: boolean
+ recordIframes?: boolean
}
export interface SessionReplayActions {
@@ -291,7 +295,26 @@ const DEFAULT_RRWEB_FILE = 'replaylibrary.min.js'
const DEFAULT_RRWEB_URL = `https://cdn.jsdelivr.net/npm/swetrix@latest/dist/${DEFAULT_RRWEB_FILE}`
const DEFAULT_SESSION_REPLAY_FLUSH_INTERVAL = 5000
const DEFAULT_SESSION_REPLAY_MAX_EVENTS = 100
+const DEFAULT_SESSION_REPLAY_MAX_CHUNK_BYTES = 512 * 1024
+const DEFAULT_SESSION_REPLAY_MAX_EVENT_BYTES = 5 * 1024 * 1024
const DEFAULT_SESSION_REPLAY_PRIVACY: SessionReplayPrivacy = 'total'
+const DEFAULT_SESSION_REPLAY_SAMPLING = {
+ mousemove: 50,
+ scroll: 150,
+ input: 'last',
+}
+const DEFAULT_SESSION_REPLAY_SLIM_DOM_OPTIONS = {
+ script: true,
+ comment: true,
+ headFavicon: true,
+ headWhitespace: true,
+ headMetaDescKeywords: true,
+ headMetaSocial: true,
+ headMetaRobots: true,
+ headMetaHttpEquiv: true,
+ headMetaAuthorship: true,
+ headMetaVerification: true,
+}
const SESSION_REPLAY_ACTIVITY_EVENTS = [
'click',
'keydown',
@@ -304,6 +327,18 @@ const SESSION_REPLAY_ACTIVITY_EVENTS = [
// Default cache duration: 5 minutes
const DEFAULT_CACHE_DURATION = 5 * 60 * 1000
+const getStringByteLength = (value: string) => {
+ if (typeof TextEncoder !== 'undefined') {
+ return new TextEncoder().encode(value).length
+ }
+
+ if (typeof Blob !== 'undefined') {
+ return new Blob([value]).size
+ }
+
+ return value.length
+}
+
export class Lib {
private pageData: PageData | null = null
private pageViewsOptions?: PageViewsOptions | null = null
@@ -850,6 +885,16 @@ export class Lib {
options.maxEventsPerChunk > 0
? Math.floor(options.maxEventsPerChunk)
: DEFAULT_SESSION_REPLAY_MAX_EVENTS
+ const maxBytesPerChunk =
+ typeof options.maxBytesPerChunk === 'number' &&
+ options.maxBytesPerChunk > 0
+ ? Math.floor(options.maxBytesPerChunk)
+ : DEFAULT_SESSION_REPLAY_MAX_CHUNK_BYTES
+ const maxBytesPerEvent =
+ typeof options.maxBytesPerEvent === 'number' &&
+ options.maxBytesPerEvent > 0
+ ? Math.floor(options.maxBytesPerEvent)
+ : DEFAULT_SESSION_REPLAY_MAX_EVENT_BYTES
const maxDurationMs =
typeof options.maxDurationMs === 'number' && options.maxDurationMs > 0
? options.maxDurationMs
@@ -862,6 +907,7 @@ export class Lib {
let chunkIndex = 0
let stopped = false
let events: RrwebEvent[] = []
+ let eventsByteLength = 0
let flushing = Promise.resolve()
let maxDurationTimer: ReturnType<typeof setTimeout> | undefined
let idleTimer: ReturnType<typeof setTimeout> | undefined
@@ -871,6 +917,7 @@ export class Lib {
const chunk = events
events = []
+ eventsByteLength = 0
const currentChunkIndex = chunkIndex++
flushing = flushing
@@ -897,11 +944,36 @@ export class Lib {
userEmit?.(event)
} catch {}
+ let eventByteLength = 0
+
+ try {
+ eventByteLength = getStringByteLength(JSON.stringify(event))
+ } catch {
+ return
+ }
+
+ if (eventByteLength > maxBytesPerEvent) {
+ return
+ }
+
+ if (
+ events.length &&
+ eventsByteLength + eventByteLength > maxBytesPerChunk
+ ) {
+ void flush()
+ }
+
events.push(event)
- if (events.length >= maxEventsPerChunk) {
+ eventsByteLength += eventByteLength
+ if (
+ events.length >= maxEventsPerChunk ||
+ eventsByteLength >= maxBytesPerChunk
+ ) {
void flush()
}
},
+ Boolean(options.recordIframes),
+ options.maskAllText,
)
const stopRecording = rrweb.record(recordOptions)
@@ -1246,9 +1318,42 @@ export class Lib {
privacy: unknown,
userOptions: RrwebRecordOptions | undefined,
emit: RrwebEmit,
+ recordIframes: boolean,
+ maskAllText?: boolean,
): RrwebRecordOptions {
+ const hasUserSampling =
+ userOptions &&
+ Object.prototype.hasOwnProperty.call(userOptions, 'sampling')
+ const hasUserSlimDOMOptions =
+ userOptions &&
+ Object.prototype.hasOwnProperty.call(userOptions, 'slimDOMOptions')
+ const sampling =
+ typeof userOptions?.sampling === 'object' && userOptions.sampling !== null
+ ? {
+ ...DEFAULT_SESSION_REPLAY_SAMPLING,
+ ...(userOptions.sampling as Record<string, unknown>),
+ }
+ : hasUserSampling
+ ? userOptions?.sampling
+ : DEFAULT_SESSION_REPLAY_SAMPLING
+ const slimDOMOptions =
+ typeof userOptions?.slimDOMOptions === 'object' &&
+ userOptions.slimDOMOptions !== null
+ ? {
+ ...DEFAULT_SESSION_REPLAY_SLIM_DOM_OPTIONS,
+ ...(userOptions.slimDOMOptions as Record<string, unknown>),
+ }
+ : hasUserSlimDOMOptions
+ ? userOptions?.slimDOMOptions
+ : DEFAULT_SESSION_REPLAY_SLIM_DOM_OPTIONS
const options: RrwebRecordOptions = {
+ recordCanvas: false,
+ recordCrossOriginIframes: false,
+ collectFonts: false,
+ inlineImages: false,
...userOptions,
+ sampling,
+ slimDOMOptions,
emit,
}
@@ -1259,14 +1364,22 @@ export class Lib {
: {}
const resolvedPrivacy = this.getSessionReplayPrivacy(privacy)
+ const defaultBlockSelector = recordIframes ? undefined : 'iframe'
+ const resolvedMaskAllText =
+ typeof maskAllText === 'boolean'
+ ? maskAllText
+ : resolvedPrivacy === 'total'
+ const textMaskingOptions = resolvedMaskAllText
+ ? { maskTextSelector: '*' }
+ : {}
if (resolvedPrivacy === 'total') {
return {
...options,
+ ...textMaskingOptions,
maskAllInputs: true,
- maskTextSelector: '*',
blockSelector: this.mergeSelectors(
- options.blockSelector,
+ this.mergeSelectors(options.blockSelector, defaultBlockSelector),
'img, picture, video, audio, canvas, svg',
),
recordCanvas: false,
@@ -1278,13 +1391,23 @@ export class Lib {
if (resolvedPrivacy === 'normal') {
return {
...options,
+ ...textMaskingOptions,
maskAllInputs: true,
+ blockSelector: this.mergeSelectors(
+ options.blockSelector,
+ defaultBlockSelector,
+ ),
emit,
}
}
return {
...options,
+ ...textMaskingOptions,
+ blockSelector: this.mergeSelectors(
+ options.blockSelector,
+ defaultBlockSelector,
+ ),
maskInputOptions: {
...maskInputOptions,
password: true,
@@ -1293,7 +1416,14 @@ export class Lib {
}
}
- private mergeSelectors(existing: unknown, required: string): string {
+ private mergeSelectors(
+ existing: unknown,
+ required?: string,
+ ): string | undefined {
+ if (!required) {
+ return typeof existing === 'string' ? existing : undefined
+ }
+
if (typeof existing === 'string' && existing.trim()) {
return `${existing}, ${required}`
}
diff --git a/packages/tracker-js/tests/sessionReplay.test.ts b/packages/tracker-js/tests/sessionReplay.test.ts
index 124b052dc..03236b39a 100644
--- a/packages/tracker-js/tests/sessionReplay.test.ts
+++ b/packages/tracker-js/tests/sessionReplay.test.ts
@@ -242,28 +242,48 @@ describe('Session replay tracking', () => {
'total',
{ blockSelector: '.secret', emit: jest.fn() },
emit,
+ false,
)
expect(total.maskAllInputs).toBe(true)
expect(total.maskTextSelector).toBe('*')
expect(total.blockSelector).toContain('.secret')
+ expect(total.blockSelector).toContain('iframe')
expect(total.blockSelector).toContain('img')
expect(total.recordCanvas).toBe(false)
+ expect(total.recordCrossOriginIframes).toBe(false)
+ expect(total.collectFonts).toBe(false)
expect(total.inlineImages).toBe(false)
+ expect(total.sampling).toEqual({
+ mousemove: 50,
+ scroll: 150,
+ input: 'last',
+ })
+ expect(total.slimDOMOptions).toEqual(
+ expect.objectContaining({
+ script: true,
+ comment: true,
+ headMetaSocial: true,
+ }),
+ )
expect(total.emit).toBe(emit)
const normal = (lib as any).getSessionReplayRecordOptions(
'normal',
{},
emit,
+ false,
)
expect(normal.maskAllInputs).toBe(true)
+ expect(normal.blockSelector).toBe('iframe')
expect(normal.emit).toBe(emit)
const freeLove = (lib as any).getSessionReplayRecordOptions(
'none',
{ maskInputOptions: { email: false } },
emit,
+ false,
)
+ expect(freeLove.blockSelector).toBe('iframe')
expect(freeLove.maskInputOptions).toEqual({
email: false,
password: true,
@@ -271,6 +291,66 @@ describe('Session replay tracking', () => {
expect(freeLove.emit).toBe(emit)
})
+ test('recordIframes opt-in keeps iframe capture available', () => {
+ const lib = new Lib(PROJECT_ID, { devMode: true })
+ const emit = jest.fn()
+
+ const options = (lib as any).getSessionReplayRecordOptions(
+ 'normal',
+ {
+ blockSelector: '.secret',
+ recordCrossOriginIframes: true,
+ sampling: { scroll: 500 },
+ },
+ emit,
+ true,
+ )
+
+ expect(options.blockSelector).toBe('.secret')
+ expect(options.recordCrossOriginIframes).toBe(true)
+ expect(options.sampling).toEqual({
+ mousemove: 50,
+ scroll: 500,
+ input: 'last',
+ })
+ expect(options.emit).toBe(emit)
+ })
+
+ test('maskAllText can be enabled outside total privacy', () => {
+ const lib = new Lib(PROJECT_ID, { devMode: true })
+ const emit = jest.fn()
+
+ const options = (lib as any).getSessionReplayRecordOptions(
+ 'normal',
+ {},
+ emit,
+ false,
+ true,
+ )
+
+ expect(options.maskAllInputs).toBe(true)
+ expect(options.maskTextSelector).toBe('*')
+ expect(options.emit).toBe(emit)
+ })
+
+ test('maskAllText can be disabled for total privacy', () => {
+ const lib = new Lib(PROJECT_ID, { devMode: true })
+ const emit = jest.fn()
+
+ const options = (lib as any).getSessionReplayRecordOptions(
+ 'total',
+ { maskTextSelector: '.masked' },
+ emit,
+ false,
+ false,
+ )
+
+ expect(options.maskAllInputs).toBe(true)
+ expect(options.maskTextSelector).toBe('.masked')
+ expect(options.blockSelector).toContain('img')
+ expect(options.emit).toBe(emit)
+ })
+
test('invalid privacy values fall back to total privacy', async () => {
const { recordOptions } = usePackageRrweb()
const { init, startSessionReplay } = await loadTracker()
@@ -292,6 +372,32 @@ describe('Session replay tracking', () => {
await actions.stop()
})
+ test('oversized replay events are dropped before upload', async () => {
+ const { recordOptions } = usePackageRrweb()
+ const { init, startSessionReplay } = await loadTracker()
+
+ init(PROJECT_ID, { devMode: true })
+ const actions = await startSessionReplay({
+ flushIntervalMs: 60_000,
+ maxBytesPerEvent: 30,
+ })
+
+ recordOptions().emit({
+ type: 3,
+ timestamp: 400,
+ data: { text: 'x'.repeat(200) },
+ })
+ await actions.flush()
+
+ expect(
+ fetchMock.mock.calls.filter(([url]) =>
+ String(url).includes('/session-replay/chunk'),
+ ),
+ ).toHaveLength(0)
+
+ await actions.stop()
+ })
+
test('script rrweb loader clears failed loads so startSessionReplay can retry', async () => {
const record = jest.fn(() => jest.fn())
const trackerScript = document.createElement('script')