Express
Capture middleware records requests and responses; error middleware catches thrown failures and forwards them to ReplayStack. Order matters—register the error middleware after your routes (and after you parse JSON bodies).
Runnable reference
See replaystack-express-example for a complete server (/health, /ok, Bearer-protected POST /fail, GET /fail/type, self-tests). Uses @replaystack/sdk@^1.0.7 from npm. NestJS parity lives in replaystack-nestjs-example.
Client options reference
Only apiKey is required. Everything else is optional—the SDK fills many values from environment variables when you do not pass them explicitly. For ReplayStack Cloud, you usually only need the key—omit endpoint to use the default host https://api.replaystack.co.
| Field | What it does | If you omit it | |
|---|---|---|---|
| apiKey | Required | Project key from the ReplayStack dashboard. Keep server-side only. | — |
| endpoint | Optional | API base URL (no /api/v1/... path). The SDK posts to /api/v1/ingest/events under this host. | REPLAYSTACK_ENDPOINT env, else https://api.replaystack.co |
| serviceName | Optional | Logical service name in the UI (filters, grouping). | REPLAYSTACK_SERVICE_NAME env, or set per event |
| environment | Optional | Label for where this process runs (production, staging, …). | NODE_ENV, else development |
| appVersion | Optional | Release or build version shown on events. | REPLAYSTACK_APP_VERSION / APP_VERSION env when not set on the client |
| commitHash | Optional | Git/deploy SHA for tying events to a revision. | REPLAYSTACK_COMMIT_HASH / COMMIT_HASH env when not set on the client |
| enabled | Optional | Turns all SDK sends off without removing code. | true unless REPLAYSTACK_ENABLED=false |
| timeoutMs | Optional | How long to wait on each ingest HTTP request. | 2500 (overridable via REPLAYSTACK_TIMEOUT_MS) |
| retries | Optional | Retries if the ingest request fails transiently. | 1 (REPLAYSTACK_RETRIES) |
| sampleRate | Optional | Random sample of events, 0–1. Use to reduce volume on success paths. | 1 (capture all) |
| captureSuccess | Optional | Whether successful HTTP-style events are sent (failures are still captured). | false — set true or REPLAYSTACK_CAPTURE_SUCCESS=true for 2xx traffic (examples often enable this) |
| captureLogs | Optional | Attach application log lines to events (e.g. error log on exceptions). | true — set false or REPLAYSTACK_CAPTURE_LOGS=false to disable |
| logLevel | Optional | Minimum log level stored when captureLogs is on. | error (REPLAYSTACK_LOG_LEVEL) |
| maxLogs | Optional | Max log lines kept per request context. | 50 |
| batchFlushIntervalMs | Optional | When > 0, buffer events and POST to /api/v1/ingest/bulk-events on an interval. | 0 (disabled; REPLAYSTACK_BATCH_FLUSH_INTERVAL_MS) |
| batchMaxEvents | Optional | Max events per bulk flush batch. | 20 (REPLAYSTACK_BATCH_MAX_EVENTS) |
| maxPayloadSizeBytes | Optional | Truncates very large JSON bodies/headers before send. | 512 KiB |
| maskFields | Optional | Extra field names to redact in payloads and headers (built-in sensitive list always applies). | built-in list always on (authorization, password, passwd, token, access_token, refresh_token, …) |
| ignoredPaths | Optional | URL paths to skip for client-level capture. Express middleware also merges its own defaults (/health, /metrics, /favicon.ico). | none |
| maxBreadcrumbs | Optional | Max breadcrumbs kept per request/client context. | 50 |
| fetchImpl | Optional | Inject fetch for tests or runtimes without global fetch. | globalThis.fetch |
| onError | Optional | Called if the SDK fails internally (network, parsing). Does not replace your app error handling. | none |
| offlineQueueMax | Optional | Max prepared events to keep in memory when ingest is down after retries. Oldest dropped when full. 0 = disable queueing. | 0 — set REPLAYSTACK_OFFLINE_QUEUE_MAX to buffer failed sends in RAM |
| flushIntervalMs | Optional | If > 0, periodically calls flush() to drain the offline queue when the API recovers. | 0 / disabled (REPLAYSTACK_FLUSH_INTERVAL_MS) |
| onQueueDrop | Optional | Callback when the offline queue exceeds offlineQueueMax and drops the oldest event. | none |
maskFields: optional extra JSON/header keys to redact. Passwords, tokens, cookies, and card fields are masked even when you omit this option. See Security & masking for the full built-in name list.
Lifecycle and reliability: call flush() to drain the in-memory queue after failed sends. close() stops new capture, cancels periodic flush, then drains. In Node, installReplayStackProcessGuards(client) from @replaystack/sdk registers optional hooks (unhandled rejection, uncaught exception, beforeExit) to flush best-effort—crash capture is not guaranteed.
Setup checklist
Parse JSON (or your body parser) first
So request bodies are available to the capture middleware.Register replayStackExpressMiddleware
Right after parsers and before your routers. Pass options for ignored paths and body/header capture.Define routes as usual
No per-route SDK calls required for basic capture. Use addBreadcrumb() or captureFailure() when you need business steps or rich error JSON.Register replayStackExpressErrorMiddleware last
It must run after routers so exceptions bubble into it.
Example
Imports
The snippet below imports from @replaystack/sdk (same helpers are re-exported from @replaystack/sdk/express if you prefer a narrower entry point).
createReplayStackClient is the factory used in the Express example repo; new ReplayStackClient is equivalent.
import express from "express";
import {
createReplayStackClient,
getReplayStackErrorCapture,
replayStackExpressErrorMiddleware,
replayStackExpressMiddleware,
} from "@replaystack/sdk";
const app = express();
app.use(express.json());
const replayStack = createReplayStackClient({
apiKey: process.env.REPLAYSTACK_API_KEY!,
endpoint: process.env.REPLAYSTACK_ENDPOINT,
serviceName: process.env.REPLAYSTACK_SERVICE_NAME ?? "api",
environment: process.env.NODE_ENV ?? "development",
appVersion: process.env.APP_VERSION,
commitHash: process.env.COMMIT_HASH,
captureSuccess: true,
});
app.use(
replayStackExpressMiddleware(replayStack, {
captureRequestBody: true,
captureResponseBody: true,
captureHeaders: true,
ignoredPaths: ["/health"],
}),
);
// …your routes…
app.use(replayStackExpressErrorMiddleware(replayStack));
// Return JSON; use captureFailure() in routes for rich error bodies on failed events.
app.use((err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
if (res.headersSent) return;
const capture = getReplayStackErrorCapture(err);
const status =
typeof capture?.statusCode === "number" && capture.statusCode >= 400 ? capture.statusCode : 500;
if (capture?.responsePayload != null && typeof capture.responsePayload === "object") {
return res.status(status).json(capture.responsePayload);
}
const message = err instanceof Error ? err.message : String(err);
res.status(status).json({ error: message });
});ignoredPaths on the middleware merges with SDK defaults (/health, /metrics, /favicon.ico) so probes do not spam your workspace.