Install the Keploy capture SDK in your web app
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-keysreturns the key asapiKeyand theendpointto use; an AI agent calls the same thing as the MCP tooluiCaptureSetup. 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:
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'sfetchandXMLHttpRequestcalls. A request the page makes before then is not recorded at all. Startinginit()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'snpm testprints 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 awaitedinit()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, andKeployCapture.stop()ends it, so that a laterinit()starts a new session. In a single-page app a session holds the page load's route changes too, up tomaxSessionDuration(10 minutes by default): see Single-page apps and navigation and Sessions and sampling. On a site whose links load pages, every page load runsinit()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
- React + Vite
- Next.js (App Router)
- Plain HTML (no bundler)
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:
// 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:
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.
The Next.js shop (Next.js 16 App Router) starts the capture from instrumentation-client.ts, at the shop's root: Next.js runs that file in the browser before the app hydrates.
// Next.js runs this file in the browser before the app hydrates, so Keploy
// UI capture starts from here. lib/keploy.ts does the work.
import "./lib/keploy";
lib/keploy.ts makes the React shop's init call. It reads the endpoint and key from NEXT_PUBLIC_ variables:
const endpoint = process.env.NEXT_PUBLIC_KEPLOY_INGEST_ENDPOINT;
const apiKey = process.env.NEXT_PUBLIC_KEPLOY_INGEST_KEY;
And it starts nothing on the server, where Next.js renders the pages too:
/** Settles once capture has started, or once it is off, declined or refused. */
export const captureStarted: Promise<void> =
typeof window === "undefined"
? Promise.resolve()
: startCapture().catch((err: unknown) => {
console.error("[shop] Keploy UI capture did not start:", err);
});
NEXT_PUBLIC_KEPLOY_INGEST_ENDPOINT=https://api.keploy.io/ui/v1/ingest
NEXT_PUBLIC_KEPLOY_INGEST_KEY=kep_YOUR_INGEST_KEY
Next.js writes NEXT_PUBLIC_ variables into the page when it builds it, so build again after you change them.
The SDK records the requests the browser makes. A fetch in a server component runs on the server and is not part of the recording; the shop's pages are client components that fetch their data in the browser. Next.js's own requests from the browser are recorded too: a <Link> fetches its page's server component payload (GET /products?_rsc=…) as it prefetches or when it is followed.
Without a bundler, serve the package's dist/ directory as it is and import dist/index.mjs from it. The SDK imports rrweb by name, so map that name with an import map before the SDK loads. The plain HTML shop's server, server.mjs, serves node_modules/@keploy/capture-sdk/dist/ at /vendor/capture-sdk/ and rrweb's dist/ at /vendor/rrweb/, and every page has these lines in its <head>:
<!-- The SDK imports rrweb by name; with no bundler, an import map says where it is. -->
<script type="importmap">
{ "imports": { "rrweb": "/vendor/rrweb/rrweb.js" } }
</script>
<!-- Keploy UI capture, on its own and async, so the page's script never waits for it: see app/keploy.js. -->
<script type="module" async src="/app/keploy.js"></script>
app/keploy.js is the React shop's src/keploy.ts in plain JavaScript, with the SDK imported by its path:
import {KeployCapture} from "/vendor/capture-sdk/index.mjs";
import {apiKey, endpoint} from "/keploy-config.js";
- Serve the whole
dist/directory, notindex.mjsalone. The SDK loads its other files from besidedist/index.mjs: its body redaction code, its GraphQL code, its body worker and, underprivacyMode: "strict", its attribute list. A page that servesindex.mjsalone records each request and response body as not captured, and refuses every strict capture. - Install rrweb yourself, at a version inside the SDK's own
rrwebrange, so that npm installs one copy, atnode_modules/rrweb. The shop'spackage.jsonlists"rrweb": "2.2.2". - The endpoint and key come from the shop's
.env, which its server hands toapp/keploy.jsas/keploy-config.js. On your own static site, write them into yourkeploy.js: an ingest key is safe to ship in a page.
KEPLOY_INGEST_ENDPOINT=https://api.keploy.io/ui/v1/ingest
KEPLOY_INGEST_KEY=kep_YOUR_INGEST_KEY
Every link on this site loads a page, so each page load starts its own capture and is a session of its own, and a page's flows never span two pages. If the import map is missing or rrweb cannot load, the capture ends before anything is sent, with KUI_E_DOM_RECORDER_UNAVAILABLE. A Content-Security-Policy must allow the import map, an inline script: see Content-Security-Policy and workers.
Choose a privacy mode
Masking happens in the browser, before anything is sent. privacyMode sets how much the SDK records:
privacyMode | Typed values | Visible text | Request and response bodies |
|---|---|---|---|
"balanced" (the default) | Masked in every input, textarea and select | Recorded, except inside maskSelectors | Recorded, redacted |
"strict", for public sites | Masked | Masked, and every attribute value that can hold text is blanked | Not recorded |
"off" | Masked only in password and hidden fields | Recorded, except inside maskSelectors | Recorded, 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
onErrorwithKUI_E_CAPTURE_DECLINED, in a task of its own after theinit()call, for every declinedinit()except one made while 16 already wait for their hand-over; - writes one
console.infoline per page, not aconsole.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 reachesonErrorin a task of its own, andinit()resolves once the handler has run. - Warnings don't call
onError. The capture goes on, and the SDK writes oneconsole.warnline with the code, such asKUI_E_BODY_WORKER_UNAVAILABLE. - A
429, a5xxor a network failure is not an error. The SDK retries with backoff and never callsonErrorfor it.
UI Capture errors and warnings explains every code: what happened, why, and how to fix it.
Check that it works
- 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>. - Watch the Network tab. While you click around, the SDK posts a batch to
/ui/v1/ingestevery few seconds (every 5 seconds by default), and each is answered200. - 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-statusreports 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.