# Control Session Replay Sampling per Page with a React Hook

> Set Session Replay sampling per page in Next.js or React with a custom hook: record, buffer until an error, or skip each section of your app.

**URL:** https://sentry.io/cookbook/control-session-replay-sampling-per-page/

---

Give each section of your React or Next.js app its own Session Replay policy (record, buffer until something breaks, or skip) with a nestable provider and hook, so you get only the Session Replays you care about.

**Time:** 20-30 minutes | **Difficulty:** Intermediate

## What You'll Learn

- Turned off global replay sampling so nothing records by default

- Built a policy controller that safely switches Replay between session, buffer, and off

- Chose a mode, sample rate, and name for each policy, and saw how nested policies override each other

- Set an app-wide default with a provider and overrode it per section and per component

- Sent buffered replays on errors, and when users leave a funnel

- Checked each policy in Sentry by filtering replays by the `replay.policy` tag

**Topics:** Session Replay

**SDKs:** React, Next.js

## Before you start

**SDKs & packages**

- [@sentry/nextjs](https://docs.sentry.io/platforms/javascript/guides/nextjs/) (or [@sentry/react](https://docs.sentry.io/platforms/javascript/guides/react/)). This recipe was built and tested on 11.10.0

- The [Session Replay integration](https://docs.sentry.io/platforms/javascript/session-replay/) with `replayIntegration()` in your Sentry init

- React 19 (the provider uses `use()` and `<Context value>`)

**Accounts & access**

- [Sentry account](https://sentry.io/signup/) with a React or Next.js project

- Any Sentry plan (each includes Session Replay)

**Knowledge**

- Basic [React](https://docs.sentry.io/platforms/javascript/guides/react/) / [Next.js](https://docs.sentry.io/platforms/javascript/guides/nextjs/) App Router experience

- A sense of which parts of your app are worth watching, and which are high-traffic noise

## Steps

### 1. Set both replay sample rates to 0

By default, Session Replay has two global sample rates, so a busy static landing page uses your replay quota at the same rate as a critical new feature. It's common to use up your plan's 50 included replays on pages you never wanted to watch. In this cookbook, you'll set sample rates in code, page by page. It's more setup than a global rate, but you get much finer control.

Keep `replayIntegration()` installed, but set `replaysSessionSampleRate` and `replaysOnErrorSampleRate` to `0`. Replay stays loaded but idle, so nothing records unless your code starts it.

If you're using React without Next.js, import from `@sentry/react` instead of `@sentry/nextjs` in every file in this recipe, put this config in your usual `Sentry.init` call, and put providers around your routes instead of in layouts.

```typescript
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,

  integrations: [
    // Installed but idle: with both sample rates at 0, nothing records
    // until a <SessionReplayProvider> starts it (lib/replay/policies.ts).
    Sentry.replayIntegration(),
  ],

  // Both at 0: nothing records until a <SessionReplayProvider> says so.
  replaysSessionSampleRate: 0,
  replaysOnErrorSampleRate: 0,
});
```

[Session Replay sampling docs](https://docs.sentry.io/platforms/javascript/session-replay/understanding-sessions/)

### 2. Add the replay policy controller

Copy this file as is. This replaces the Sentry SDK's built-in sampling with our custom controller using Replay's `start()`, `startBuffering()`, and `stop()` manually.

Each `useSessionReplay` call chooses a policy (`session`, `buffer`, or `off`) and a sample rate. The deepest policy registered in the tree is the one used. So you can supply a "global" sample rate, and override it on specific pages. Each policy's sample rate is rolled once per page load. The currently active policy is set as the `replay.policy` tag so you can filter replays by it in Sentry.

```typescript
"use client";

import * as Sentry from "@sentry/nextjs";

export type ReplayMode = "off" | "buffer" | "session";

export type ReplayPolicy = {
  /** Shown in Sentry as the `replay.policy` tag. */
  name: string;
  /** What to do when this policy is sampled in. */
  mode: ReplayMode;
  /** 0..1. Chance that a user gets `mode` instead of "off". */
  sampleRate: number;
  /** If the user leaves while it's buffering, send the buffer. */
  sendOnLeave?: boolean;
};

type ActivePolicy = ReplayPolicy & { id: string; depth: number };

// Every mounted provider's policy. The deepest one decides, so a layout can
// override the one around it. Providers only say what they want; the
// queued tasks below make Replay match.
const active = new Map<string, ActivePolicy>();
let winner: ActivePolicy | undefined;
let wanted: ReplayMode = "off";
// The winning buffer policy. Nested buffer policies share one buffer,
// and the innermost owns it like every other setting: its sendOnLeave
// decides whether the buffer is sent when it goes away.
let bufferOwner: ActivePolicy | undefined;
// One roll per policy per page load, so leaving and coming back
// isn't a second chance to be sampled.
const rolls = new Map<string, boolean>();

export function addPolicy(id: string, policy: Omit<ActivePolicy, "id">) {
  watch();
  active.set(id, { ...policy, id });
  update();
}

export function removePolicy(id: string) {
  active.delete(id);
  update();
}

function update() {
  winner = undefined;
  for (const p of active.values()) if (!winner || p.depth > winner.depth) winner = p;

  if (winner && !rolls.has(winner.name)) rolls.set(winner.name, Math.random() < winner.sampleRate);
  wanted = winner && rolls.get(winner.name) ? winner.mode : "off";
  Sentry.setTag("replay.policy", winner?.name ?? "none");
  enqueue(apply);
}

// stop() is async, and start() before it finishes records nothing, so
// tasks run one at a time. Each acts on the latest state, which also
// means navigating from one section to the next is a single change.
let queue = Promise.resolve();
function enqueue(task: () => unknown) {
  queue = queue.then(task).then(
    () => {},
    (err) => console.warn("Session Replay:", err),
  );
}

async function apply() {
  const replay = Sentry.getReplay();
  if (!replay) return;

  // The buffer's policy is gone and asked for sendOnLeave: send the buffer
  // under its own name before anything else stops it. Checked here, not on
  // unmount: React remounts providers in development, and one whose props
  // change is removed and re-added.
  const owner = bufferOwner;
  if (owner?.sendOnLeave && !active.has(owner.id) && replay.getRecordingMode() === "buffer") {
    bufferOwner = undefined;
    Sentry.setTag("replay.policy", owner.name);
    // Send without recording on: the next page belongs to the next policy.
    await replay.flush({ continueRecording: false });
    Sentry.setTag("replay.policy", winner?.name ?? "none");
    await replay.stop();
  }

  // Same mode as before, e.g. two session policies in a row: one continuous replay.
  const current = replay.getRecordingMode() ?? "off";
  if (current !== wanted) {
    if (current !== "off") await replay.stop();
    // Read `wanted` again: the user may have moved on while stop() ran.
    if (wanted === "session") replay.start();
    if (wanted === "buffer") replay.startBuffering();
  }
  bufferOwner = wanted === "buffer" ? winner : undefined;
}

let watching = false;
function watch() {
  const client = Sentry.getClient();
  if (watching || !client) return;
  watching = true;

  // A buffered replay is only sent for errors tagged with its ID, and with
  // replaysOnErrorSampleRate at 0 the SDK doesn't add that tag. So we do,
  // and the SDK flushes the buffer once the error has been sent.
  client.on("preprocessEvent", (event) => {
    const replay = Sentry.getReplay();
    if (!event.type && event.exception && replay?.getRecordingMode() === "buffer") {
      event.tags = { ...event.tags, replayId: replay.getReplayId() };
    }
  });

  // Replays end after 15 minutes idle or 60 minutes total. Start the
  // current policy's again (after stop() has finished).
  client.on("replayEnd", ({ reason }) => {
    if (reason === "sessionExpired") setTimeout(() => enqueue(apply));
  });
}
```

[Session Replay configuration](https://docs.sentry.io/platforms/javascript/session-replay/configuration/)

### 3. Create the useSessionReplay hook and SessionReplayProvider

`useSessionReplay` applies a Session Replay policy on mount. `SessionReplayProvider` wraps the hook so you can use it in layouts, which on Next.js are usually Server Components, which cannot call hooks directly. It also tracks how deeply providers are nested, so an inner layout overrides an outer one.

```typescript
"use client";

import { createContext, use, useEffect, useId } from "react";
import { addPolicy, removePolicy, type ReplayMode } from "@/lib/replay/policies";

type SessionReplayOptions = {
  /** Shown in Sentry as the `replay.policy` tag. */
  name: string;
  mode?: ReplayMode;
  /** 0..1. Chance that a user gets `mode` instead of "off". */
  sampleRate?: number;
  /** If the user leaves while it's buffering, send the buffer. */
  sendOnLeave?: boolean;
};

// How deeply providers are nested here. The innermost one wins.
const Depth = createContext(0);

/**
 * Applies a Session Replay policy while the calling component is mounted,
 * overriding the provider around it.
 *
 *   useSessionReplay({ name: "checkout", mode: "session" });
 */
export function useSessionReplay({ name, mode = "session", sampleRate = 1, sendOnLeave = false }: SessionReplayOptions) {
  const id = useId();
  const depth = use(Depth) + 1;

  useEffect(() => {
    addPolicy(id, { name, mode, sampleRate, sendOnLeave, depth });
    return () => removePolicy(id);
  }, [id, name, mode, sampleRate, sendOnLeave, depth]);
}

/**
 * Applies a Session Replay policy to everything inside it, for layouts
 * (which are usually Server Components and can't call hooks). Nest them:
 * the innermost provider wins.
 *
 *   <SessionReplayProvider name="submit" mode="session" sampleRate={0.1}>
 */
export function SessionReplayProvider({
  children,
  ...options
}: SessionReplayOptions & { children: React.ReactNode }) {
  useSessionReplay(options);
  return <Depth value={use(Depth) + 1}>{children}</Depth>;
}
```

[Next.js Session Replay guide](https://docs.sentry.io/platforms/javascript/guides/nextjs/session-replay/)

### 4. Choose a mode, sample rate, and name for each policy

`SessionReplayProvider` and `useSessionReplay` take the same four options, which together make a policy: what Replay does on that part of your app, and for what share of users.

The most deeply nested policy wins, and only its sample rate counts. If a user isn't sampled into it, Replay is `off` there. It doesn't fall back to the policy around it.

- **`name`** (required): a short label like `"checkout"`. The name is added as the `replay.policy` tag so you can easily filter for it in Sentry. Policies with the same name share one sample roll per page load.

- **`mode`** (default `"session"`): `"session"` records the whole visit to the section. `"buffer"` keeps the last ~60 seconds in memory and sends them when an error happens, then keeps recording. With `sendOnLeave`, it also sends them when the user leaves. `"off"` stops Replay and throws away anything buffered.

- **`sampleRate`** (default `1`): a number from `0` to `1`, the chance that a user gets `mode`. Everyone else gets `off` for that policy. It's rolled once per page load, and has no effect when `mode` is `"off"`.

- **`sendOnLeave`** (default `false`): with `mode: "buffer"`, also send the buffer when the user navigates to another part of the app.

**Sample sessions**

Record a share of visits in full.

```typescript
// Docs pages: plenty of traffic, so a small sample is enough.
<SessionReplayProvider name="docs" mode="session" sampleRate={0.05}>
  {children}
</SessionReplayProvider>
```

**Errors only**

Buffer for everyone, send only when something breaks.

```typescript
// Settings: nobody needs to watch a working settings page.
<SessionReplayProvider name="settings" mode="buffer">
  {children}
</SessionReplayProvider>

// Same, for a quarter of users. The rest aren't buffered at all.
<SessionReplayProvider name="settings" mode="buffer" sampleRate={0.25}>
  {children}
</SessionReplayProvider>
```

**Abandonment**

Buffer, and send when the user leaves the section.

```typescript
// Signup: send the last ~60s for errors and for users who leave.
// Turn it off on the success screen so finished signups aren't sent.
<SessionReplayProvider name="signup" mode="buffer" sendOnLeave>
  {children}
</SessionReplayProvider>
```

**Never**

Don't record this section at all.

```typescript
// Billing: high traffic and sensitive, never record.
<SessionReplayProvider name="billing" mode="off">
  {children}
</SessionReplayProvider>
```

**Nesting**

How policies override each other.

```typescript
<SessionReplayProvider name="app" mode="session" sampleRate={0.1}>
  {/* Everywhere: 10% of visits recorded. */}
  <SessionReplayProvider name="settings" mode="buffer">
    {/* Settings: everyone buffered, sent on errors. The 10% roll doesn't apply here. */}
    <ApiKeysPanel />
    {/* Calls useSessionReplay({ name: "api-keys", mode: "off" }):
        off while the panel is mounted, back to "settings" when it unmounts. */}
  </SessionReplayProvider>
</SessionReplayProvider>
```

### 5. Set an app-wide default in your root layout

Wrap your root layout's children with a provider to set the default for every page. Here, 10% of sessions are recorded by default, unless overridden on a specific page.

```typescript
// app/layout.tsx
import { SessionReplayProvider } from "@/components/session-replay-provider";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {/* The app-wide default: 10% of sessions. Sections override it in their own layouts. */}
        <SessionReplayProvider name="app" mode="session" sampleRate={0.1}>
          {children}
        </SessionReplayProvider>
      </body>
    </html>
  );
}
```

### 6. Override the default per section

Give each route group its own policy in its layout. Turn Replay `off` for pages that are static, or that have been stable for a long time. Record new experiences in full, like new features, feature-flagged releases, and experiments, so you can see how users interact with them. Use `buffer` for pages you only need to see when something breaks: Replay keeps the last ~60 seconds and sends them with the error, then records the rest of the visit to that section. Sections without a provider inherit the one above them.

```typescript
// app/(browse)/layout.tsx
// Landing page + event list. High traffic, low insight: never record.
import { SessionReplayProvider } from "@/components/session-replay-provider";

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <SessionReplayProvider name="browse" mode="off">
      {children}
    </SessionReplayProvider>
  );
}

// app/(event)/layout.tsx
// Event detail + RSVP. We only care when something breaks:
// buffer the last ~60s for everyone, send it only if an error happens.
import { SessionReplayProvider } from "@/components/session-replay-provider";

export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <SessionReplayProvider name="event" mode="buffer">
      {children}
    </SessionReplayProvider>
  );
}
```

[How buffer mode works](https://docs.sentry.io/platforms/javascript/session-replay/understanding-sessions/)

### 7. Send the buffer when users navigate away from a funnel

In a funnel, the replays worth watching are usually from users who give up. Use `mode="buffer"` with `sendOnLeave`: when the user leaves the section for another part of the app, the controller sends the last ~60 seconds, tagged with the section's `replay.policy`.

`sendOnLeave` also fires after a successful submission, so turn Replay off on your success screen. Calling `useSessionReplay` with `mode: "off"` there throws the buffer away, so leaving afterwards sends nothing.

This example also records a beta cohort in full. Pass `inBeta` in from your feature flag check, as the layout at the end of the snippet does.

```typescript
// components/submit-replay-provider.tsx
"use client";

import { SessionReplayProvider } from "@/components/session-replay-provider";

/**
 * The submit funnel is mature, so we only want to watch the people who
 * give up: everyone buffers, and the last ~60 seconds are sent if they
 * navigate away. The success screen turns Replay off, which discards
 * the buffer, so completed submissions are never sent. Everyone in the
 * beta cohort is recorded in full: that's the rollout we're nervous about.
 */
export function SubmitReplayProvider({
  inBeta = false,
  children,
}: {
  inBeta?: boolean;
  children: React.ReactNode;
}) {
  return inBeta ? (
    <SessionReplayProvider name="submit-beta" mode="session">
      {children}
    </SessionReplayProvider>
  ) : (
    <SessionReplayProvider name="submit" mode="buffer" sendOnLeave>
      {children}
    </SessionReplayProvider>
  );
}

// components/submitted.tsx
"use client";

import { useSessionReplay } from "@/components/session-replay-provider";

export function Submitted({ id }: { id: string }) {
  // The funnel is done: turn Replay off here so the buffer is discarded
  // instead of sent when the user leaves.
  useSessionReplay({ name: "submit-done", mode: "off" });

  return <p>Submitted! Reference: {id}</p>;
}

// app/(submit)/layout.tsx
import { SubmitReplayProvider } from "@/components/submit-replay-provider";

export default async function Layout({ children }: { children: React.ReactNode }) {
  const inBeta = await isSubmitBetaEnabled(); // your feature flag check
  return <SubmitReplayProvider inBeta={inBeta}>{children}</SubmitReplayProvider>;
}
```

### 8. Use the hook for a single component

When one component matters more than the page it's on, call `useSessionReplay` directly from a Client Component. Its policy applies while it's mounted and the surrounding policy takes over again when it unmounts.

```typescript
"use client";

import { useSessionReplay } from "@/components/session-replay-provider";

export function CheckoutForm() {
  // Record this form in full for everyone who reaches it,
  // overriding whatever the surrounding layout asked for.
  useSessionReplay({ name: "checkout", mode: "session" });

  return <form>{/* ... */}</form>;
}
```

### 9. Check your policies in Sentry

Run your app and check each kind of policy once. New replays can take a moment to appear in Sentry.

- **`session`**: visit a recorded section and click around. While testing, set its `sampleRate` to `1` so you're sure to be sampled. In Sentry, open [Replays](https://sentry.io/orgredirect/organizations/:orgslug/explore/replays/) and search for `replay.policy:app`, using your policy's name, to find your visit.

- **`buffer`**: on a buffered section, trigger an error, for example from a button that throws. Open the new issue in Sentry: it has a replay of the seconds before the error.

- **`off`**: open an `off` section in a fresh tab and click around. No new replay appears.

[How replay sampling works](https://docs.sentry.io/platforms/javascript/session-replay/understanding-sessions/)

## Summary

**Record only what you care about.**

Set which pages of your app to record, buffer, or skip with a custom React hook

## Pro Tips

- Filter the [Replays view](https://sentry.io/orgredirect/organizations/:orgslug/explore/replays/) by the `replay.policy` tag to confirm each section is recording the way you intended.

- Use `buffer` instead of `session` for pages you only need when something breaks. You still get the replay for every error, without paying for sessions where nothing went wrong.

- Put a high `sampleRate` on low-traffic, high-value flows like onboarding and a low one, or `off`, on high-traffic marketing pages.

- Two `session` policies in a row keep one continuous replay, so moving between recorded sections doesn't split the session.

## Common Pitfalls

- Calling `useSessionReplay` from a Server Component won't work. Use `SessionReplayProvider` in layouts, or call the hook from a `"use client"` component.

- Leaving `replaysSessionSampleRate` or `replaysOnErrorSampleRate` above `0` means the SDK starts recording on its own, outside your policies.

- Calling `replay.start()` before `replay.stop()` resolves records nothing. Let the controller's queue handle every change instead of calling Replay directly.

- Closing the tab or reloading the page doesn't trigger `sendOnLeave`, so those buffers are never sent.

- Switching from a `session` page to an `off` page sends the last chunk of the recording, which can include a moment of the `off` page, because React cleans up after the new page renders. To drop that chunk instead, at the cost of the last [~5 seconds](https://github.com/getsentry/sentry-javascript/blob/11.10.0/packages/replay-internal/src/constants.ts#L21-L24) of the recorded page, change `apply()` to call `replay.stop({ flush: false })` when switching to `off`.

## FAQ

**Can I use `useSessionReplay` directly inside a Next.js layout.tsx or page.tsx?**

Not the hook, if that file is a Server Component, which layouts usually are. Wrap the children in `SessionReplayProvider` instead: it's a `"use client"` component, so it works inside Server Component layouts.

**Can I use this without Next.js?**

Yes. The hook and provider are plain React 19. Import from `@sentry/react` instead of `@sentry/nextjs`, and wrap your routes in `SessionReplayProvider` instead of layouts. The `"use client"` lines only matter in Next.js.

**Can I use `useSessionReplay` inside a component that's not a layout?**

Yes, in any client component. Inside a provider, it overrides that provider while it's mounted. With no provider around it, it's the only policy.

**Why set both sample rates to 0?**

Any non-zero rate lets the SDK start recording or buffering on its own, which conflicts with the policies. At `0`, Replay only does what the active provider asks for.

**If replaysOnErrorSampleRate is 0, how do buffered replays get sent on errors?**

The SDK only sends a buffered replay for errors tagged with its replay ID, and it doesn't add that tag when the error sample rate is `0`. The controller's `preprocessEvent` hook adds it while Replay is buffering, and the SDK sends the buffer after the error. This depends on SDK internals rather than a documented option. It was tested with `@sentry/nextjs` 11.10.0, so check it after upgrading.

**What if two policies are mounted at the same depth?**

The one that registered first wins, which depends on React's mount order. Give each section one place that sets its policy, a layout or a single component, so there's never a tie.

**Does navigating back to a page give a user another chance to be sampled?**

No. Each policy is rolled once per page load, so a user who wasn't sampled for a section stays unsampled until they reload.

**Are there privacy or PII considerations?**

Yes. Your `replayIntegration()` options control masking and blocking of text, inputs, and media. These policies only control when Replay records. Setting a section to `off` is a simple way to keep pages full of personal data out of replays entirely.

## Next Steps

- [product/session-replay](https://sentry.io/product/session-replay/)

- [Configure Session Replay privacy](https://docs.sentry.io/platforms/javascript/session-replay/privacy/): Control what gets masked or blocked in your replays with the integration's privacy options. The policies here only decide when to record.

- [Understand replay sampling](https://docs.sentry.io/platforms/javascript/session-replay/understanding-sessions/): Learn how session-based and error-based sampling work so you can tune capture rates for your traffic.

---

*Source: [sentry.io/cookbook/control-session-replay-sampling-per-page/](https://sentry.io/cookbook/control-session-replay-sampling-per-page/)*
