Skip to main content

Node.js

Install​

npm install @sentry/node @sentry/profiling-node

Initialize first​

Sentry.init() must run before anything else is imported, so the SDK can patch http, your framework and your database driver. Put it in its own file:

// instrument.js
import * as Sentry from "@sentry/node";
import { nodeProfilingIntegration } from "@sentry/profiling-node";

Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV,
release: process.env.APP_VERSION,

tracesSampleRate: 0.2,
profilesSampleRate: 1.0, // fraction of sampled transactions
integrations: [nodeProfilingIntegration()],

_experiments: { enableLogs: true },
sendDefaultPii: false,
});

Load it before your app:

node --import ./instrument.js ./server.js

CommonJS: require("./instrument.js") on the very first line of your entry file.

Express​

import "./instrument.js";
import express from "express";
import * as Sentry from "@sentry/node";

const app = express();
// … your routes …
Sentry.setupExpressErrorHandler(app); // after routes, before other error middleware
app.listen(3000);

Fastify (Sentry.setupFastifyErrorHandler(app)), NestJS (@sentry/nestjs) and Koa have equivalent one-liners.

Logs​

const { logger } = Sentry;
logger.info("payment captured", { orderId, amount });
logger.error("gateway rejected", { orderId, code });

They land in Logs, correlated with the active trace.

Cron check-ins​

import * as Sentry from "@sentry/node";

const checkInId = Sentry.captureCheckIn(
{ monitorSlug: "nightly-report", status: "in_progress" },
{ schedule: { type: "crontab", value: "0 3 * * *" }, checkinMargin: 5, maxRuntime: 30, timezone: "Asia/Tehran" },
);

try {
await runNightlyReport();
Sentry.captureCheckIn({ checkInId, monitorSlug: "nightly-report", status: "ok" });
} catch (err) {
Sentry.captureCheckIn({ checkInId, monitorSlug: "nightly-report", status: "error" });
throw err;
}

See Cron monitoring for schedules, margins and thresholds.

Metrics​

Sentry.metrics.increment("checkout.attempt", 1, { tags: { plan: "pro" } });
Sentry.metrics.distribution("checkout.latency", 421, { unit: "millisecond" });

See Metrics.

Verify​

Sentry.captureException(new Error("Errora smoke test"));