← Back to Cookbook

Control Session Replay sampling per page with a React hook

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.

Features
SDKs
Category Debugging
Time
20-30 minutes
Complexity
Intermediate
Steps
9 steps

Before you start

SDKs & packages
Accounts & access
  • Sentry account with a React or Next.js project
  • Any Sentry plan (each includes Session Replay)
Knowledge
  • Basic React / Next.js App Router experience
  • A sense of which parts of your app are worth watching, and which are high-traffic noise

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.

Session Replay sampling docs
instrumentation-client.ts
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,
});

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.

Session Replay configuration
lib/replay/policies.ts
"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));
  });
}

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.

Next.js Session Replay guide
components/session-replay-provider.tsx
"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>;
}

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.
TypeScript
// Docs pages: plenty of traffic, so a small sample is enough.
<SessionReplayProvider name="docs" mode="session" sampleRate={0.05}>
  {children}
</SessionReplayProvider>

Record a share of visits in full.

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.

app/layout.tsx
// 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.

How buffer mode works
app/(browse)/layout.tsx + app/(event)/layout.tsx
// 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>
  );
}

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.

Submit funnel: provider, success screen, and layout
// 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.

components/checkout-form.tsx
"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 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

That's it.

Record only what you care about.

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

  • 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

Pro tips

  • 💡 Filter the Replays view 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 of the recorded page, change apply() to call replay.stop({ flush: false }) when switching to off.

Frequently asked questions

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.

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.

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.

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.

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.

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.

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

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.

Fix it, don't observe it.

Get started with the only application monitoring platform that empowers developers to fix application problems without compromising on velocity.