@chrom-ar/collector-node
Reports your Node app's errors to Collector,
which groups them into issues, emails you when one is new or comes back,
and shows you what broke and why.
Made for Express and Next.js (Node runtime), and works with any Node
server. Needs Node 24 or newer, and has no dependencies. For browser code,
use @chrom-ar/collector.
Installation
npm install @chrom-ar/collector-node
Give it your project's DSN (from its setup page in Collector) in the
COLLECTOR_DSN environment variable of the deployed app, and call init()
before your app 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 defaults to COLLECTOR_ENVIRONMENT, then NODE_ENV as it
is (production, development, …). Issues are counted per environment.
It also sends a heartbeat when the app starts and every hour after, so
Collector knows the app is up even when nothing breaks.
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 error handlers still run.
Errors with a 4xx status (status, statusCode, Boom's
output.statusCode), like a not found, aren't bugs 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 running 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
(e.g. in middleware) the package loads a version that does nothing, so
your Edge code keeps working.
For the browser side, install
@chrom-ar/collector
too and call its init() from client code.
Logs, requests and sign-ins
To help Collector spot attacks (login abuse, scanning, unusual volume),
the SDK can also send what your server logs, every request it serves,
and its sign-in attempts. It's off until you create a server key in
the project's settings ("Server keys", or collector server-keys create)
and give it to the server as COLLECTOR_SERVER_KEY, next to
COLLECTOR_DSN. The key is a secret: it's only read from that variable.
From then on, with nothing else to add:
- Requests: one record per request the app's HTTP servers serve,
404s and 500s included: method, path, query string, status, time,
client IP, user agent, size. The route pattern (
/users/:id) and its
params are read on their own, for Express and Next.js (App and Pages
Router). A path segment matched by a route param named token,
password or secret is sent as :token, :password or :secret.
Collector stores query and param values that look secret (by name,
like token or email, or by look, like an email or a JWT) only as a
keyed hash: searchable, never read back.
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. What your app prints about an error is sent
as a log line too (Express's default handler prints the stack with
console.error), next to the error's own report.
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 });
account is what was typed (trimmed and lowercased), for failures and
successes alike. 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", // debug, info, notice, warning, error, critical, alert, emergency
skipPaths: ["/health", "/internal/*"], // exact, or a prefix ending in /*
trustedProxies: ["10.0.0.0/8"], // see below
dropParams: ["invite"], // query and route params never sent
},
});
logs: false turns all of it off.
Client IPs. By default the client is the address connected to the
server. Behind a load balancer or proxy, list its addresses in
trustedProxies (CIDRs): X-Forwarded-For is read only when the
connection comes from one of them, since anyone can send that header.
An IPv4 range also matches IPv4 in IPv6 form (::ffff:10.0.1.147, how a
server listening on IPv6 sees IPv4 peers); an IPv6 range matches IPv6
only. Express's own trust proxy setting isn't used.
Routes. Next.js has no public API for a request's route: the SDK
reads the match Next keeps on each request, and if a Next release changes
that, matches the path against the build's routes-manifest.json. A path
no route matches (a 404, a static file) is sent without one, and
Collector groups it. Express routers mounted at a path with params
(app.use("/orgs/:org", router)) report the full pattern with Express 5.3
and newer (router 2.3); before, that part of the route is the actual path.
Shutting down. Records go out every second. A process that ends on
its own sends what's left first (waiting up to 5 s). One stopped by a
signal doesn't, unless your handler flushes: await Collector.flush()
(see Shutting down). In serverless functions, call
await Collector.flush() before the handler returns.
Privacy. Collector stores log lines and fields as sent, for a year,
and doesn't mask them: what your app logs is your responsibility.
Sign-ins keep what people typed, usually emails. Requests carry no
headers or bodies.
Checking your setup
const result = await Collector.test();
// { ok: true, id: "…" } or { ok: false, reason: "Collector rejected the key (HTTP 401)…" }
It also logs one line, [collector] Test event sent (202)… or why it
wasn't. Or from a shell, with the same DSN:
COLLECTOR_DSN=https://clt_…@app.clt.chrom.ar collector test # the collector CLI
Reporting things yourself
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");
Both return the event's id, or undefined when nothing was sent.
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 breadcrumbs, with no middleware to add. Outside a
request (at startup, in a job), they apply to everything after.
Crashes
The SDK never changes whether your process lives or dies:
- After an uncaught exception, if your app 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 app has a listener, it
only reports and your listener decides.
- A crash that ends the process is reported at level
fatal; one your
app's listener handles is an ordinary error.
- Unhandled rejections follow Node's
--unhandled-rejections mode (from
the command line or NODE_OPTIONS): in the default mode, a rejection
nothing handles crashes the process, after being reported.
exitOnUncaught: false keeps the process running after an uncaught
exception. Node normally exits there, so 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 it
adds no SIGTERM or SIGINT listener (that would change how your app
stops). If you have your own shutdown hook, flush there:
process.on("SIGTERM", async () => {
await server.close();
await Collector.flush(2000);
process.exit(0);
});
Source lines and source maps
Collector shows the lines around each frame of your code. When your server
runs its own source files (plain Node, most Express apps), the SDK reads
them from disk and sends those lines: nothing to do.
When the server code is bundled (Next.js's .next/server, esbuild, tsup),
upload its source maps before you deploy with the
collector CLI, with the same
release the app reports:
collector upload .next/server --url-prefix /.next/server --release "$GIT_SHA"
File paths are sent relative to the app's root (/.next/server/chunks/123.js),
so the maps match wherever the app is deployed. Set root if the app
doesn't start from its own directory. Without maps, frames in bundled code
show the built code, and a deploy can open new issues.
If Node maps stack traces itself (--enable-source-maps, or Next's
experimental.serverSourceMaps), frames already show your original files,
and no upload is needed.
Privacy
- Request URLs are sent without their query string (
stripQuery: false
keeps it).
- Cookies,
Authorization, API keys, any header with token, secret,
session, auth or password in its name, and headers that carry the
client's IP are never sent. Neither are request bodies.
- Console breadcrumbs keep a short summary of what was logged. If your app
logs personal data, turn them off with
breadcrumbs: { console: false }.
beforeSend sees every event last, and can edit it or drop it (return
null).
Options
| Option |
Default |
|
dsn |
COLLECTOR_DSN |
Your project's DSN. Without it, nothing is sent |
environment |
COLLECTOR_ENVIRONMENT, then NODE_ENV |
e.g. "production", "staging" |
release |
COLLECTOR_RELEASE |
Your app's version or git sha |
debug |
false |
Logs what the SDK does, prefixed [collector] |
enabled |
true |
false turns everything off |
beforeSend |
none |
(event) => event \| null, to edit or drop events |
ignoreErrors |
none |
Strings (matched anywhere in "Type: message") or regexps |
inAppPaths |
outside node_modules |
Strings or regexps for paths that are your app's own code; this decides how errors group into issues |
root |
process.cwd() |
The app's root; file paths are sent relative to it |
stripQuery |
true |
Remove ?query and #hash from request URLs |
breadcrumbs |
all on |
{ console, http }, each true/false |
maxBreadcrumbs |
50 |
How many breadcrumbs to keep per request |
heartbeat |
true |
false stops the heartbeats |
exitOnUncaught |
true |
See Crashes |
logs |
on with COLLECTOR_SERVER_KEY |
See Logs, requests and sign-ins |
Other functions: setTags(tags), addBreadcrumb({ message, category?, level? }),
signIn(outcome, account, opts?), pinoStream(), winstonTransport(),
flush(timeoutMs?) and close(timeoutMs?) (removes everything the SDK
installed).
How it behaves
Events are sent in the background, one at a time, from a bounded queue
(the oldest is dropped past 1000), so a slow or unreachable Collector never
slows your app down. Failed sends are retried with the same id, so nothing
is counted twice; when Collector asks to slow down, it does. Every
occurrence of an error is sent, so Collector's counts show how big an
incident is, up to 100 events every 10 seconds per process (an error in a
tight loop stops there). If Collector can't be reached, a process that's
ending waits at most 2 seconds for it. It never throws into your app, and keeps quiet in the console
unless something's misconfigured (or you set debug: true).
License
MIT