Skip to main content

Install the Keploy capture SDK in your web app​

View as Markdown
FreeTeamsScaleEnterpriseSelf-HostedDedicated

The Keploy capture SDK, @keploy/capture-sdk, records what people do in your web app and the requests the page makes, masks personal data in the browser, and posts the recording to Keploy in batches. This page adds it to your own app: install the package, call init once and early, keep the ingest key in your configuration, and check that recordings arrive. It describes SDK 3.1.0.

The code on this page comes from the three UI capture sample shops: one small shop built with React and Vite (ui-capture-react-shop), with the Next.js App Router (ui-capture-next-shop), and as plain HTML pages with no bundler (ui-capture-html-shop). Each sample's CI visits it in Chromium and checks what its SDK sent.

Before you begin​

You need an ingest key for the Keploy app you want to record into, and the ingest endpoint the SDK sends to.

  • In the dashboard, open UI Testing → UI Flows and click Create ingest key: see Create an ingest key.
  • With the REST API, POST /client/v1/apps/<appId>/ui/ingest-keys returns the key as apiKey and the endpoint to use; an AI agent calls the same thing as the MCP tool uiCaptureSetup. See Create an ingest key.

The endpoint is https://api.keploy.io/ui/v1/ingest on Keploy Cloud. When you self-host Keploy, it is your API server's URL followed by /ui/v1/ingest.

Install​

npm install @keploy/capture-sdk

Install it as a runtime dependency, not a dev one: it runs in production, in your visitors' browsers. Its only dependency is rrweb, the library it records the page with, which your bundler resolves, and it has no peer dependencies. The package ships ES module and CommonJS builds with TypeScript types. The samples pin the exact version they are tested with, "@keploy/capture-sdk": "3.1.0".

There is no script-tag build: the only way in is an import. A page with no bundler imports it from the package's dist/ directory, as the Plain HTML tab below shows.

Call init once, as early as you can​

KeployCapture.init starts the capture. It has two required options: endpoint, the ingest endpoint, and apiKey, your ingest key, which the SDK sends in the X-API-Key header of every batch. Every other option has a default. Each sample calls it once, from a module of its own; this is the React shop's:

src/keploy.ts (excerpt)
import {KeployCapture} from "@keploy/capture-sdk";

const endpoint = import.meta.env.VITE_KEPLOY_INGEST_ENDPOINT;
const apiKey = import.meta.env.VITE_KEPLOY_INGEST_KEY;

async function startCapture(): Promise<void> {
if (!endpoint || !apiKey) {
console.info(
"[shop] Keploy UI capture is off: set VITE_KEPLOY_INGEST_ENDPOINT and VITE_KEPLOY_INGEST_KEY in .env"
);
return;
}
await KeployCapture.init({
endpoint,
apiKey,
// The default, written out: every typed value is masked, and the page's
// visible text is kept. "strict" also masks all visible text and records
// no request or response body.
privacyMode: "balanced",
privacy: {
// Text that repeats what the shopper typed: the order confirmation
// shows their email, so its text is masked.
maskSelectors: ["[data-testid=order-confirmation]"],
// Never recorded: the reviews (people's names) are replaced by an
// empty box of the same size.
blockSelectors: ["[data-testid=reviews]"],
// A route whose path holds a credential, such as an invite link, is
// declared so its value is kept out of every event. The shop has none:
// secretRoutes: ["/invites/:key"],
},
onError(err) {
// The visitor's browser sends Do Not Track or Global Privacy Control:
// nothing is recorded, and nothing needs fixing.
if (err.code === "KUI_E_CAPTURE_DECLINED") return;
console.error(
`[shop] Keploy UI capture stopped: ${err.code}`,
err.message
);
},
});
const sessionId = KeployCapture.getSessionId();
if (sessionId)
console.info(`[shop] Keploy UI capture is recording session ${sessionId}`);
}

/** Settles once capture has started, or once it is off, declined or refused. */
export const captureStarted: Promise<void> = startCapture().catch(
(err: unknown) => {
console.error("[shop] Keploy UI capture did not start:", err);
}
);

The Next.js and plain HTML shops make the same call; only where they read the endpoint and key differs (see the tabs below).

  • As early as you can. init() loads rrweb, which your bundler puts in a chunk of its own, before it starts recording the page's fetch and XMLHttpRequest calls. A request the page makes before then is not recorded at all. Starting init() before your app's own code runs narrows that window, but nothing closes it, so the first request of a page load may be missing from its recording. Each sample's npm test prints whether its first page's request was recorded. See Start capture before your first call.
  • Without holding your app back. Start init() and let your app go on: don't make rendering or routing wait for it. Online, an awaited init() resolves only once rrweb has loaded, and a refused one can resolve about 30 seconds after the call, longer in a hidden tab (see Handle SDK errors and warnings). The samples start it first and never wait for it.
  • Once per page load, not per route. A second init() returns the capture that is already running, and KeployCapture.stop() ends it, so that a later init() starts a new session. In a single-page app a session holds the page load's route changes too, up to maxSessionDuration (10 minutes by default): see Single-page apps and navigation and Sessions and sampling. On a site whose links load pages, every page load runs init() again and starts a session of its own.
  • In the browser. Call it from code that runs in the browser, not during server-side rendering. The Next.js shop's module does nothing on the server.

Add it to your app​

The React shop (React 19, Vite 8, React Router) calls init in src/keploy.ts, above. src/main.tsx imports that module before anything else, so the capture starts before the app's own code runs:

src/main.tsx (excerpt)
// Keploy UI capture first, so it starts before any of the app's code: see keploy.ts.
import "./keploy";

Vite reads the endpoint and key from .env into import.meta.env, and src/vite-env.d.ts declares the two variables for TypeScript:

.env
VITE_KEPLOY_INGEST_ENDPOINT=https://api.keploy.io/ui/v1/ingest
VITE_KEPLOY_INGEST_KEY=kep_YOUR_INGEST_KEY

Vite builds the SDK's own files as chunks of your build, beside rrweb's, and emits its body worker as a file. Deploy every file the build emits: see Bundlers and frameworks.

Choose a privacy mode​

Masking happens in the browser, before anything is sent. privacyMode sets how much the SDK records:

privacyModeTyped valuesVisible textRequest and response bodies
"balanced" (the default)Masked in every input, textarea and selectRecorded, except inside maskSelectorsRecorded, redacted
"strict", for public sitesMaskedMasked, and every attribute value that can hold text is blankedNot recorded
"off"Masked only in password and hidden fieldsRecorded, except inside maskSelectorsRecorded, redacted

"strict" also replaces every query value in a URL. Under "balanced" and "off", a body's values under a credential's name, such as password or token, are replaced with [REDACTED] before it is sent.

The dashboard's setup card and the REST API's init snippet set only endpoint and apiKey, so they record under "balanced". The samples write privacyMode: "balanced" out, so the choice is visible in the code. Strict still records data-testid values as written, so never build one from user data. Privacy and masking covers every rule, and what each mode still records.

Keep the key in configuration​

  • The key is safe to ship. An ingest key can post recordings into the one app it was made for and do nothing else: no reads and no other API. That is why it can sit in a page every visitor can read. Never put any other kind of Keploy key in its place: the ingest server refuses a personal access token with 403.
  • Read it from the build's configuration, as the samples do: VITE_ variables for Vite, NEXT_PUBLIC_ variables for Next.js. Both are built into the page, so rebuild after you change one.
  • One key records into one app, the one it was made for: the SDK sends no app of its own, so a key made for another app is accepted, and its recordings go into that app with no error. An app's journey shares are shares of every session the app receives, so give an environment whose visits you don't want mixed with production's, such as staging or CI, an app and a key of its own: see One app per environment.

Visitors who send Do Not Track or Global Privacy Control​

The SDK honours both signals by default (honorPrivacySignals: true). When a visitor's browser sends Global Privacy Control (navigator.globalPrivacyControl === true) or Do Not Track (navigator.doNotTrack === "1", or as older browsers spell it), init() records, patches and sends nothing for that page load. The SDK then:

  • calls onError with KUI_E_CAPTURE_DECLINED, in a task of its own after the init() call, for every declined init() except one made while 16 already wait for their hand-over;
  • writes one console.info line per page, not a console.error.

Some browsers send Global Privacy Control by default, Brave and DuckDuckGo among them, so expect this from a share of your real visitors. It is not an error: return early on KUI_E_CAPTURE_DECLINED in onError and keep it out of your error tracking, as the samples' onError does. Calling init() again does not help: every init() is declined while the browser sends the signal.

Set honorPrivacySignals: false only where your site has its own lawful basis to record such visitors and says so in its privacy policy. The SDK then records regardless of the signals.

Handle errors​

onError is called once when a condition that ends the capture happens: the ingest server refused a batch (a revoked key, a wrong endpoint), or the SDK refused to start (rrweb could not load, a conflicting privacy option, the visitor's privacy signal). Branch on err.code, never on the message. The samples' onError, above, returns on KUI_E_CAPTURE_DECLINED and logs every other code.

  • A refusal before anything is sent does not reject init(). It reaches onError in a task of its own, and init() resolves once the handler has run.
  • Warnings don't call onError. The capture goes on, and the SDK writes one console.warn line with the code, such as KUI_E_BODY_WORKER_UNAVAILABLE.
  • A 429, a 5xx or a network failure is not an error. The SDK retries with backoff and never calls onError for it.

UI Capture errors and warnings explains every code: what happened, why, and how to fix it.

Check that it works​

  1. Open your app with your browser's developer tools. KeployCapture.getSessionId() returns the id of the session being recorded, and "" when no session is live; the samples log it as [shop] Keploy UI capture is recording session <id>.
  2. Watch the Network tab. While you click around, the SDK posts a batch to /ui/v1/ingest every few seconds (every 5 seconds by default), and each is answered 200.
  3. Check that sessions arrive in Keploy. The dashboard's setup card counts them under 3. Check that sessions arrive, and GET /client/v1/apps/<appId>/ui/capture-status reports the same: see Watch the sessions arrive and Capture status.

Nothing is posted? Check the console for a KUI_E_ code, and test in a browser that sends neither Do Not Track nor Global Privacy Control: in one that does, nothing is recorded, as above. A 401 or 403 on those posts means the key is missing, unknown, expired, revoked or not an ingest key.

Other bundlers and frameworks​

The SDK's tests build it with webpack 4 and 5, Parcel 2, Next.js (Turbopack and webpack), Vite, esbuild, and with no bundler. Bundlers and frameworks says what each needs. If your site sends a Content-Security-Policy, read Content-Security-Policy and workers.