Next.js

Next.js

Use route wrappers for App Router and Pages Router APIs. Server Actions have no global HTTP wrapper—log manually with the same client you use elsewhere.

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 doesIf you omit it
apiKeyRequiredProject key from the ReplayStack dashboard. Keep server-side only.
endpointOptionalAPI 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
serviceNameOptionalLogical service name in the UI (filters, grouping).REPLAYSTACK_SERVICE_NAME env, or set per event
environmentOptionalLabel for where this process runs (production, staging, …).NODE_ENV, else development
appVersionOptionalRelease or build version shown on events.REPLAYSTACK_APP_VERSION / APP_VERSION env when not set on the client
commitHashOptionalGit/deploy SHA for tying events to a revision.REPLAYSTACK_COMMIT_HASH / COMMIT_HASH env when not set on the client
enabledOptionalTurns all SDK sends off without removing code.true unless REPLAYSTACK_ENABLED=false
timeoutMsOptionalHow long to wait on each ingest HTTP request.2500 (overridable via REPLAYSTACK_TIMEOUT_MS)
retriesOptionalRetries if the ingest request fails transiently.1 (REPLAYSTACK_RETRIES)
sampleRateOptionalRandom sample of events, 0–1. Use to reduce volume on success paths.1 (capture all)
captureSuccessOptionalWhether 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)
captureLogsOptionalAttach application log lines to events (e.g. error log on exceptions).true — set false or REPLAYSTACK_CAPTURE_LOGS=false to disable
logLevelOptionalMinimum log level stored when captureLogs is on.error (REPLAYSTACK_LOG_LEVEL)
maxLogsOptionalMax log lines kept per request context.50
batchFlushIntervalMsOptionalWhen > 0, buffer events and POST to /api/v1/ingest/bulk-events on an interval.0 (disabled; REPLAYSTACK_BATCH_FLUSH_INTERVAL_MS)
batchMaxEventsOptionalMax events per bulk flush batch.20 (REPLAYSTACK_BATCH_MAX_EVENTS)
maxPayloadSizeBytesOptionalTruncates very large JSON bodies/headers before send.512 KiB
maskFieldsOptionalExtra 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, …)
ignoredPathsOptionalURL paths to skip for client-level capture. Express middleware also merges its own defaults (/health, /metrics, /favicon.ico).none
maxBreadcrumbsOptionalMax breadcrumbs kept per request/client context.50
fetchImplOptionalInject fetch for tests or runtimes without global fetch.globalThis.fetch
onErrorOptionalCalled if the SDK fails internally (network, parsing). Does not replace your app error handling.none
offlineQueueMaxOptionalMax 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
flushIntervalMsOptionalIf > 0, periodically calls flush() to drain the offline queue when the API recovers.0 / disabled (REPLAYSTACK_FLUSH_INTERVAL_MS)
onQueueDropOptionalCallback 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.

ReplayStackClient constructor

Every example below uses the same client shape: only apiKey is required; other fields are optional and often come from REPLAYSTACK_* env vars. The table above is the full reference; inline comments match the snippet only.

What to use where

  • App RouterwithReplayStackNext on each exported method.
  • Pages RouterwithReplayStackNextApi around the handler.
  • Server ActionscaptureEvent / captureException.
  • Edge Middleware — not a replacement for body capture; keep using handlers or manual calls.

App Router — route handler

File such as app/api/orders/route.ts. Wrap each HTTP verb you export.

POST example
import { NextRequest, NextResponse } from "next/server";
import { ReplayStackClient } from "@replaystack/sdk";
import { withReplayStackNext } from "@replaystack/sdk/nextjs";

const replayStack = new ReplayStackClient({
  // Required — project key from the dashboard.
  apiKey: process.env.REPLAYSTACK_API_KEY!,
  // Optional — API base; env REPLAYSTACK_ENDPOINT works if you omit this property.
  endpoint: process.env.REPLAYSTACK_ENDPOINT!,
  // Optional — service name in the UI.
  serviceName: process.env.REPLAYSTACK_SERVICE_NAME || "nextjs-api",
  // Optional — defaults to NODE_ENV.
  environment: process.env.NODE_ENV || "development",
  // Optional — release metadata.
  appVersion: process.env.APP_VERSION,
  commitHash: process.env.COMMIT_HASH,
});

export const POST = withReplayStackNext(
  async function POST(req: NextRequest) {
    const body = await req.json();
    return NextResponse.json({ success: true, order: { id: "ord_123", ...body } });
  },
  { client: replayStack, endpoint: "/api/orders" }
);

Pages Router — API route

File such as pages/api/orders.ts.

default export
import type { NextApiRequest, NextApiResponse } from "next";
import { ReplayStackClient } from "@replaystack/sdk";
import { withReplayStackNextApi } from "@replaystack/sdk/nextjs";

const replayStack = new ReplayStackClient({
  // Required — project key from the dashboard.
  apiKey: process.env.REPLAYSTACK_API_KEY!,
  // Optional — API base; env REPLAYSTACK_ENDPOINT works if you omit this property.
  endpoint: process.env.REPLAYSTACK_ENDPOINT!,
  // Optional — service name in the UI.
  serviceName: process.env.REPLAYSTACK_SERVICE_NAME || "nextjs-api",
  // Optional — defaults to NODE_ENV.
  environment: process.env.NODE_ENV || "development",
  // Optional — release metadata.
  appVersion: process.env.APP_VERSION,
  commitHash: process.env.COMMIT_HASH,
});

async function handler(_req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ success: true });
}

export default withReplayStackNextApi(handler, { client: replayStack });

Server Actions

One shared server-only module (here @/lib/replaystack) avoids creating many clients.

lib/replaystack.ts
import { ReplayStackClient } from "@replaystack/sdk";

export const replayStack = new ReplayStackClient({
  // Required — project key from the dashboard.
  apiKey: process.env.REPLAYSTACK_API_KEY!,
  // Optional — API base; env REPLAYSTACK_ENDPOINT works if you omit this property.
  endpoint: process.env.REPLAYSTACK_ENDPOINT!,
  // Optional — service name in the UI.
  serviceName: process.env.REPLAYSTACK_SERVICE_NAME || "nextjs-app",
  // Optional — defaults to NODE_ENV.
  environment: process.env.NODE_ENV || "development",
  // Optional — release metadata.
  appVersion: process.env.APP_VERSION,
  commitHash: process.env.COMMIT_HASH,
});
action.ts
"use server";

import { replayStack } from "@/lib/replaystack";

export async function createOrderAction(formData: FormData) {
  const start = Date.now();
  try {
    replayStack.addBreadcrumb("Action started");
    const order = { id: "ord_123" };
    await replayStack.captureEvent({
      eventType: "custom",
      endpoint: "createOrderAction",
      status: "success",
      statusCode: 200,
      executionTimeMs: Date.now() - start,
      requestPayload: Object.fromEntries(formData),
      responsePayload: order,
    });
    return order;
  } catch (error) {
    await replayStack.captureException(error, {
      eventType: "custom",
      endpoint: "createOrderAction",
      executionTimeMs: Date.now() - start,
    });
    throw error;
  }
}
Pass a stable endpoint string into the wrapper so the dashboard groups traffic the way you expect.