Skip to content
SDKs

Node.js SDK

Capture backend errors with HTTP context, logs, and spans.

Watch the Node.js SDK video

A 2:40 walkthrough of this guide’s documented setup, examples, and SDK options. British male narration and captions are included.

2:40 · English narration · Captions includedOpen video

Jump to a chapter

Read the video transcript
Install and initialize

Install the Node SDK with the guide’s npm command. It requires Node eighteen or newer. Initialize before your server handles traffic, using the Cloud HTTPS endpoint or your Enterprise Agent URL. Pass endpoint, node ID, and ingest key explicitly, as in server dot T S. Release and commit SHA can also come from the Reelay release and commit SHA environment variables.

Express and error capture

Follow the Express middleware order in the documentation. Request Handler goes before routes and seeds the request context. Error Handler goes after routes, before your application’s final error handler. It captures the error and calls next; your handler still sends the response. In Express four, asynchronous route errors must reach the error pipeline through a wrapper or next error. The middleware helper throws if called before init.

For a handled failure, use the guide’s charge Card example. Append Log adds the payment provider failure message, then capture Exception reports the caught error. Capture inside an instrumented request inherits its HTTP context. Outside a request, such as a cron task or queue worker, use run With Context or with Transaction to supply context.

Verify and configure telemetry

Add the documented Reelay test route in staging, hit it with the curl command, and check the event in Errors. Error sampling defaults to one. Before Send can inspect or drop an event by returning null. Scrub Patterns adds extra redaction expressions, and sensitive-key redaction is always on. These options are listed on the SDK page.

To record sampled requests as transactions, set traces Sample Rate above zero. The documentation example uses zero point one and enables profiling for CPU profiles. The API reference lists with Span for timing a child operation, with Transaction for timing a job, and set Transaction Name for a useful route name. With Monitor and check In report scheduled-job check-ins.

Crashes and shutdown

Uncaught exceptions and unhandled rejections are captured automatically. When Reelay is the only uncaught Exception listener, it flushes for up to two seconds and exits with code one. Your own listener takes precedence. For graceful shutdown, stop accepting requests and let in-flight work finish, then await Reelay close. It flushes pending telemetry and tears down the SDK, with a default timeout of two thousand milliseconds. The guide also links a complete example project.

Install

Requires Node.js 18+. Initialize before your server handles traffic. Use https://api.usereelay.com for Cloud, or your Enterprise Agent URL.

The SDK reads REELAY_RELEASE and REELAY_COMMIT_SHA from the environment. Everything else — endpoint, nodeId, ingestKey — must be passed to init explicitly.

Install
npm install @usereelay/node
server.ts · Express
import express from "express";
import * as Reelay from "@usereelay/node";
const reelay = Reelay.init({
endpoint: process.env.REELAY_INGEST_ENDPOINT!,
nodeId: process.env.REELAY_NODE_ID!,
ingestKey: process.env.REELAY_INGEST_KEY!,
});
const app = express();
app.use(Reelay.requestHandler(reelay));
// Your routes here.
app.use(Reelay.errorHandler(reelay));
app.use((error: unknown, _req: express.Request,
res: express.Response, _next: express.NextFunction) => {
console.error(error);
res.status(500).json({ error: "Internal server error" });
});
app.listen(3000);

Middleware order

  1. requestHandler goes before routes. It seeds the request context and adopts incoming trace headers.

  2. Your routes and middleware.

  3. errorHandler goes after routes, before your own error handler. It captures the error and calls next(err) — your handler still sends the response.

Verify it works

Add a test route in staging, hit it, and check the event in Errors.

Test route
app.get("/reelay-test", () => {
throw new Error("Reelay test");
});
Hit it
curl http://localhost:3000/reelay-test

Add context to a caught error

A capture inside an instrumented request inherits its HTTP context. Outside a request (cron, queue worker), use runWithContext or withTransaction to supply one.

Handled failure
try {
await chargeCard();
} catch (error) {
Reelay.appendLog("error", "Payment provider failed");
Reelay.captureException(error);
}

Options

OptionUse
endpointHTTPS ingest URL. Required.
nodeId, ingestKeyNode credentials. Required by the backend.
release, commitShaDeployed version and full Git SHA. Also read from REELAY_RELEASE / REELAY_COMMIT_SHA.
sampleRateFraction of errors to send (0–1). Default: 1.
beforeSendInspect or drop an event. Return null to drop.
scrubPatternsExtra regexes to redact. Sensitive-key redaction is always on.
tracesSampleRatePerformance sampling (0–1). Default: 0 (off).
profilingCPU profiling. Requires tracesSampleRate > 0. Default: false.
debugDiagnostic callback.

Performance monitoring

Set tracesSampleRate above 0 to record a sampled share of requests as transactions. Set profiling: true alongside it for CPU profiles.

Performance options
Reelay.init({
endpoint: process.env.REELAY_INGEST_ENDPOINT!,
nodeId: process.env.REELAY_NODE_ID!,
ingestKey: process.env.REELAY_INGEST_KEY!,
tracesSampleRate: 0.1,
profiling: true,
});

Crashes and shutdown

Uncaught exceptions and unhandled rejections are captured automatically. When the SDK is the only uncaughtException listener, it flushes for up to 2 seconds and exits with code 1 — the same as Node's default. Your own listener takes precedence.

On graceful shutdown, await Reelay.close() to flush and tear down. Default timeout is 2000 ms.

Example project

A complete Node.js integration is available in the example workbench.

SDK API reference

For graceful server shutdown, stop accepting requests, let in-flight work finish, then await Reelay.close(). Flushing the error queue alone does not replace a full telemetry shutdown.

Function or methodPurpose
init(options), getClient()Initialize once, or get the active NodeClient.
requestHandler(client), errorHandler(client)Add request context before routes and error capture afterward.
middleware()Get both middleware handlers bound to the initialized client. Throws if called before init().
captureException(error), captureMessage(message)Report an exception or message with active request context.
appendLog(level, message), appendSpan(span)Add investigation detail to the active request timeline.
currentContext(), runWithContext(context, fn)Inspect the active context or supply context for a background task.
withSpan(op, description, fn), withSpan(op, fn)Time an operation as a child of the active transaction. Description is optional.
withTransaction(name, op, fn)Time a job or other operation as a transaction.
setTransactionName(name)Set a useful transaction name, such as a route pattern.
withMonitor(slug, config, fn), checkIn(payload)Report scheduled-job check-ins.
close(timeoutMs?)Flush pending telemetry and tear down the SDK; the default timeout is 2000 ms.