Skip to main content

Node

The @chrom-ar/collector-node package reports your Node server's errors. It's made for Express and Next.js (Node runtime) and works with any Node server. It needs Node 24 or newer and has no dependencies. This page describes version 0.2.1.

Installation​

npm install @chrom-ar/collector-node

Give the deployed application the project's DSN in the COLLECTOR_DSN variable and call init() before it starts:

import * as Collector from "@chrom-ar/collector-node";

Collector.init(); // reads COLLECTOR_DSN, COLLECTOR_ENVIRONMENT, COLLECTOR_RELEASE

That's it. From now on, uncaught exceptions and unhandled rejections are reported on their own, with the request they happened in and what happened right before them: console messages and outgoing requests.

Without a DSN nothing is sent, so dev and tests stay quiet when you don't set COLLECTOR_DSN there. Options passed to init() win over the environment variables:

Collector.init({ dsn: process.env.MY_DSN, release: "api@1.4.2" });

The environment is COLLECTOR_ENVIRONMENT, else NODE_ENV as it is. It also sends a signal when it starts and every hour.

Express​

Add the error handler after your routes:

const app = express();
// … your routes …
app.use(Collector.expressErrorHandler());

It reports errors that end in a 5xx (an error without a status counts as 500), then passes the error on, so your own handlers still run. Errors with a 4xx status, like a not found, aren't bugs in your code and aren't reported.

Next.js​

In instrumentation.ts, at the project's root (or in src/):

export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const Collector = await import("@chrom-ar/collector-node");
Collector.init();
}
}

export { onRequestError } from "@chrom-ar/collector-node/next";

That reports errors from pages, route handlers, server actions and middleware on the Node runtime, tagged with the route (next.route) and its kind (next.route_type). redirect(), notFound(), forbidden() and the other errors Next throws on purpose aren't reported. Errors on the Edge runtime aren't reported yet; there the package loads a version that does nothing.

For the browser side, install the browser SDK too.

Checking it works​

const result = await Collector.test();
// { ok: true, id: "…" } or { ok: false, reason: "Collector rejected the key (HTTP 401)…" }

Or from a shell, with the same DSN: COLLECTOR_DSN=https://clt_…@app.clt.chrom.ar collector test.

Reporting by hand​

try {
await charge(order);
} catch (error) {
Collector.captureException(error, { tags: { step: "payment" } });
return res.status(502).send("Payment failed");
}

Collector.captureMessage("Payment gateway slow", "warning");

Users and tags​

Collector.setUser({ id: req.user.id }); // an id, not personal data
Collector.setTag("plan", "pro");

Inside a request, these apply to that request only: every request gets its own user, tags and "what happened before", with no middleware to add. Outside a request (at startup, in a job), they apply to everything after.

Logs, requests and sign-ins​

The SDK can also send what your server logs, every request it serves and its sign-in attempts, to catch attacks. It's off until you create a server key and give it to the server as COLLECTOR_SERVER_KEY, next to COLLECTOR_DSN. The key is only read from that variable.

From then on, with nothing to add:

  • Requests: one per request the application's HTTP servers serve, 404s and 500s included: method, path (no query string), status, time, client IP, user agent, size. Express's route pattern (/users/:id) is read on its own. A segment matched by a route param named token, password or secret is sent as :token, :password or :secret.
  • console lines at info and above.

pino and winston need one line each:

const logger = pino(opts, pino.multistream([{ stream: process.stdout }, { stream: Collector.pinoStream() }]));

const logger = winston.createLogger({
transports: [new winston.transports.Console(), Collector.winstonTransport()],
});

(pino needs its options argument, even {}, before the stream.) Per-request lines from pino-http and morgan aren't sent: the request records already cover them.

Sign-ins are reported by your login code:

Collector.signIn("failed", req.body.email, { req, method: "password", reason: "bad_password" });
Collector.signIn("succeeded", req.body.email, { req, method: "password", user: user.id });

method is password, magic_link, passkey, token or other; reason is unknown_account, bad_password, locked, expired_token or other. Inside a request, req can be left out.

Collector.init({
logs: {
lines: true, // console, pino, winston
requests: true,
signIns: true,
level: "info",
skipPaths: ["/health", "/internal/*"], // exact, or a prefix ending in /*
trustedProxies: ["10.0.0.0/8"],
},
});

logs: false turns all of it off.

An error caught while serving a request carries that request's id, the same one its log records send, so Collector links the error to its logs.

  • Client IPs: by default the client is the address connected to the server. Behind a load balancer or proxy, list its addresses in trustedProxies: X-Forwarded-For is read only when the connection comes from one of them, since anyone can send that header.
  • Limits: Next.js requests have no route pattern (Next doesn't expose one).

Crashes​

The SDK never changes whether your process lives or dies:

  • After an uncaught exception, if your application has no uncaughtException listener of its own, it prints the error as Node would, sends it (waiting at most 2 seconds), and exits with code 1. If your application has a listener, it only reports and your listener decides.
  • A crash that ends the process is reported at level fatal; one your listener handles is an ordinary error.
  • Unhandled rejections follow Node's --unhandled-rejections mode.
  • exitOnUncaught: false keeps the process running after an uncaught exception. Only use it if you know the process can carry on.

Shutting down​

The SDK sends what's queued before the process exits on its own, but adds no SIGTERM or SIGINT listener (that would change how your application stops). If you have your own shutdown hook, flush there:

process.on("SIGTERM", async () => {
await server.close();
await Collector.flush(2000);
process.exit(0);
});

In serverless functions, call await Collector.flush() before the handler returns.

Source lines and source maps​

When your server runs its own source files (unbundled Node, most Express apps), the SDK reads them from disk and sends the lines: nothing to do.

When the server code is bundled (Next.js's .next/server, esbuild, tsup), upload its maps before you deploy, with the same release the application reports:

collector upload .next/server --url-prefix /.next/server --release "$GIT_SHA"

File paths are sent relative to the application's root, so the maps match wherever it's deployed. If Node already maps stack traces (--enable-source-maps, or Next's experimental.serverSourceMaps), no upload is needed. See Source maps.

Options​

OptionDefault
dsnCOLLECTOR_DSNYour project's DSN. Without it, nothing is sent.
environmentCOLLECTOR_ENVIRONMENT, then NODE_ENV"production", "staging", …
releaseCOLLECTOR_RELEASEYour application's version or git sha.
debugfalseLogs what the SDK does, prefixed [collector].
enabledtruefalse turns everything off.
beforeSendnone(event) => event | null, to change or drop events.
ignoreErrorsnoneStrings (matched anywhere in "Type: message") or regexps.
inAppPathsoutside node_modulesStrings or regexps for paths that are your code; it decides how errors group.
rootprocess.cwd()The application's root; file paths are sent relative to it.
stripQuerytrueRemoves ?query and #hash from request URLs.
breadcrumbsall on{ console, http }, each true or false.
maxBreadcrumbs50How many "what happened before" entries to keep per request.
heartbeattruefalse stops the signals.
exitOnUncaughttrueSee Crashes.
logson with COLLECTOR_SERVER_KEYSee Logs, requests and sign-ins.

Other functions: setTags(tags), addBreadcrumb({ message, category?, level? }), signIn(outcome, account, opts?), pinoStream(), winstonTransport(), flush(timeoutMs?) and close(timeoutMs?).