diff --git a/packages/replay/README.md b/packages/replay/README.md index 80d568cff52e..8c0ea81e5cba 100644 --- a/packages/replay/README.md +++ b/packages/replay/README.md @@ -138,6 +138,11 @@ A session starts when the Session Replay SDK is first loaded and initialized. Th [^1]: An 'interaction' refers to either a mouse click or a browser navigation event. +### Accessing the Replay Session ID + +You can get the ID of the currently running session via `replay.getReplayId()`. +This will return `undefined` if no session is ongoing. + ### Replay Captures Only on Errors Alternatively, rather than recording an entire session, you can capture a replay only when an error occurs. In this case, the integration will buffer up to one minute worth of events prior to the error being thrown. It will continue to record the session following the rules above regarding session life and activity. Read the [sampling](#Sampling) section for configuration options. diff --git a/packages/replay/src/integration.ts b/packages/replay/src/integration.ts index c08eb0431cac..f426a9051f97 100644 --- a/packages/replay/src/integration.ts +++ b/packages/replay/src/integration.ts @@ -226,6 +226,17 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`, return this._replay.flushImmediate(); } + /** + * Get the current session ID. + */ + public getReplayId(): string | undefined { + if (!this._replay || !this._replay.isEnabled()) { + return; + } + + return this._replay.getSessionId(); + } + /** Setup the integration. */ private _setup(): void { // Client is not available in constructor, so we need to wait until setupOnce diff --git a/packages/replay/test/integration/getReplayId.test.ts b/packages/replay/test/integration/getReplayId.test.ts new file mode 100644 index 000000000000..1080186974fc --- /dev/null +++ b/packages/replay/test/integration/getReplayId.test.ts @@ -0,0 +1,26 @@ +import { mockSdk } from '../mocks/mockSdk'; +import { useFakeTimers } from '../utils/use-fake-timers'; + +useFakeTimers(); + +describe('Integration | getReplayId', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('works', async () => { + const { integration, replay } = await mockSdk({ + replayOptions: { + stickySession: true, + }, + }); + + expect(integration.getReplayId()).toBeDefined(); + expect(integration.getReplayId()).toEqual(replay.session?.id); + + // When stopped, it is undefined + integration.stop(); + + expect(integration.getReplayId()).toBeUndefined(); + }); +});