sentry-node-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > Node.js / Bun / Deno SDK
所有技能 > SDK配置 > Node.js / Bun / Deno SDK

Sentry Node.js / Bun / Deno SDK

Sentry Node.js / Bun / Deno SDK

Opinionated wizard that scans your project and guides you through complete Sentry setup for server-side JavaScript and TypeScript runtimes: Node.js, Bun, and Deno.
这是一个预设配置的向导工具,会扫描你的项目并引导你完成服务器端JavaScript和TypeScript运行时(Node.js、Bun和Deno)的完整Sentry配置。

Invoke This Skill When

何时调用本技能

  • User asks to "add Sentry to Node.js", "Bun", or "Deno"
  • User wants to install or configure
    @sentry/node
    ,
    @sentry/bun
    , or
    @sentry/deno
  • User wants error monitoring, tracing, logging, profiling, crons, metrics, or AI monitoring for a backend JS/TS app
  • User asks about
    instrument.js
    ,
    --import ./instrument.mjs
    ,
    bun --preload
    , or
    npm:@sentry/deno
  • User wants to monitor Express, Fastify, Koa, Hapi, Connect, Bun.serve(), or Deno.serve()
NestJS? Use
sentry-nestjs-sdk
instead — it uses
@sentry/nestjs
with NestJS-native decorators and filters. Next.js? Use
sentry-nextjs-sdk
instead — it handles the three-runtime architecture (browser, server, edge).
Note: SDK versions below reflect current Sentry docs at time of writing (
@sentry/node
≥10.42.0,
@sentry/bun
≥10.42.0,
@sentry/deno
≥10.42.0). Always verify against docs.sentry.io/platforms/javascript/guides/node/ before implementing.

  • 用户要求“为Node.js、Bun或Deno添加Sentry”
  • 用户想要安装或配置
    @sentry/node
    @sentry/bun
    @sentry/deno
  • 用户想要为后端JS/TS应用配置错误监控、链路追踪、日志记录、性能分析、任务调度、指标监控或AI监控
  • 用户询问
    instrument.js
    --import ./instrument.mjs
    bun --preload
    npm:@sentry/deno
    相关内容
  • 用户想要监控Express、Fastify、Koa、Hapi、Connect、Bun.serve()或Deno.serve()
NestJS? 请改用
sentry-nestjs-sdk
—— 它使用
@sentry/nestjs
,支持NestJS原生装饰器和过滤器。 Next.js? 请改用
sentry-nextjs-sdk
—— 它适配三运行时架构(浏览器、服务器、边缘端)。
注意: 下文提到的SDK版本基于编写时的Sentry官方文档(
@sentry/node
≥10.42.0、
@sentry/bun
≥10.42.0、
@sentry/deno
≥10.42.0)。 实施前请务必对照docs.sentry.io/platforms/javascript/guides/node/进行验证。

Phase 1: Detect

阶段1:检测

Run these commands to identify the runtime, framework, and existing Sentry setup:
bash
undefined
运行以下命令识别运行时、框架以及已有的Sentry配置:
bash
undefined

Detect runtime

检测运行时

bun --version 2>/dev/null && echo "Bun detected" deno --version 2>/dev/null && echo "Deno detected" node --version 2>/dev/null && echo "Node.js detected"
bun --version 2>/dev/null && echo "Bun detected" deno --version 2>/dev/null && echo "Deno detected" node --version 2>/dev/null && echo "Node.js detected"

Detect existing Sentry packages

检测已安装的Sentry包

cat package.json 2>/dev/null | grep -E '"@sentry/' cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
cat package.json 2>/dev/null | grep -E '"@sentry/' cat deno.json deno.jsonc 2>/dev/null | grep -i sentry

Detect Node.js framework

检测Node.js框架

cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'

Detect Bun-specific frameworks

检测Bun专属框架

cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'

Detect Deno frameworks (deno.json imports)

检测Deno框架(deno.json中的导入)

cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'

Detect module system (Node.js)

检测模块系统(Node.js)

cat package.json 2>/dev/null | grep '"type"' ls *.mjs *.cjs 2>/dev/null | head -5
cat package.json 2>/dev/null | grep '"type"' ls *.mjs *.cjs 2>/dev/null | head -5

Detect existing instrument file

检测已有的instrument文件

ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null
ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null

Detect logging libraries

检测日志库

cat package.json 2>/dev/null | grep -E '"winston"|"pino"|"bunyan"'
cat package.json 2>/dev/null | grep -E '"winston"|"pino"|"bunyan"'

Detect cron / scheduling

检测任务调度工具

cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'

Detect AI / LLM usage

检测AI/LLM使用情况

cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'

Detect OpenTelemetry tracing

检测OpenTelemetry链路追踪

cat package.json 2>/dev/null | grep -E '"@opentelemetry/sdk-node"|"@opentelemetry/sdk-trace-node"|"@opentelemetry/sdk-trace-base"' grep -rn "NodeTracerProvider|trace.getTracer|startActiveSpan"
--include=".ts" --include=".js" --include="*.mjs" 2>/dev/null | head -5
cat package.json 2>/dev/null | grep -E '"@opentelemetry/sdk-node"|"@opentelemetry/sdk-trace-node"|"@opentelemetry/sdk-trace-base"' grep -rn "NodeTracerProvider\|trace\.getTracer\|startActiveSpan" \ --include=".ts" --include=".js" --include="*.mjs" 2>/dev/null | head -5

Check for companion frontend

检查是否存在配套前端

ls frontend/ web/ client/ ui/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'

**What to determine:**

| Question | Impact |
|----------|--------|
| Which runtime? (Node.js / Bun / Deno) | Determines package, init pattern, and preload flag |
| Node.js: ESM or CJS? | ESM requires `--import ./instrument.mjs`; CJS uses `require("./instrument")` |
| Framework detected? | Determines which error handler to register |
| `@sentry/*` already installed? | Skip install, go straight to feature config |
| `instrument.js` / `instrument.mjs` already exists? | Merge into it rather than overwrite |
| Logging library detected? | Recommend Sentry Logs |
| Cron / job scheduler detected? | Recommend Crons monitoring |
| AI library detected? | Recommend AI Monitoring |
| OpenTelemetry tracing detected? | Use OTLP path instead of native tracing |
| Companion frontend found? | Trigger Phase 4 cross-link |

---
ls frontend/ web/ client/ ui/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'

**需要确定的信息:**

| 问题 | 影响 |
|----------|--------|
| 使用哪种运行时?(Node.js / Bun / Deno) | 决定要安装的包、初始化方式以及预加载参数 |
| Node.js:使用ESM还是CJS? | ESM需要`--import ./instrument.mjs`;CJS使用`require("./instrument")` |
| 是否检测到框架? | 决定要注册的错误处理器 |
| 是否已安装`@sentry/*`包? | 跳过安装步骤,直接进入功能配置 |
| 是否已存在`instrument.js`/`instrument.mjs`? | 合并内容而非覆盖文件 |
| 是否检测到日志库? | 推荐使用Sentry Logs |
| 是否检测到任务调度工具? | 推荐使用任务调度监控 |
| 是否检测到AI库? | 推荐使用AI监控 |
| 是否检测到OpenTelemetry链路追踪? | 使用OTLP路径替代原生链路追踪 |
| 是否存在配套前端? | 触发阶段4的跨服务关联配置 |

---

Phase 2: Recommend

阶段2:推荐

Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Route from OTel detection:
  • OTel tracing detected (
    @opentelemetry/sdk-node
    or
    @opentelemetry/sdk-trace-node
    in
    package.json
    , or
    NodeTracerProvider
    in source) → use OTLP path:
    otlpIntegration()
    via
    @sentry/node-core/light
    ; do not set
    tracesSampleRate
    ; Sentry links errors to OTel traces automatically
Recommended (core coverage):
  • Error Monitoring — always; captures unhandled exceptions, promise rejections, and framework errors
  • Tracing — automatic HTTP, DB, and queue instrumentation via OpenTelemetry
Optional (enhanced observability):
  • Logging — structured logs via
    Sentry.logger.*
    ; recommend when
    winston
    /
    pino
    /
    bunyan
    or log search is needed
  • Profiling — continuous CPU profiling (Node.js only; not available on Bun or Deno); not available with OTLP path
  • AI Monitoring — OpenAI, Anthropic, LangChain, Vercel AI SDK; recommend when AI/LLM calls detected
  • Crons — detect missed or failed scheduled jobs; recommend when node-cron, Bull, or Agenda is detected
  • Metrics — custom counters, gauges, distributions; recommend when custom KPIs needed
  • Runtime Metrics — automatic collection of memory, CPU, and event loop metrics;
    nodeRuntimeMetricsIntegration()
    (Node.js) /
    bunRuntimeMetricsIntegration()
    (Bun)
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
OTLP IntegrationOTel tracing detected — replaces native Tracing
TracingAlways for server apps — HTTP spans + DB spans are high-value; skip if OTel tracing detected
LoggingApp uses winston, pino, bunyan, or needs log-to-trace correlation
ProfilingNode.js only — performance-critical service; native addon compatible; skip if OTel tracing detected (requires
tracesSampleRate
, incompatible with OTLP)
AI MonitoringApp calls OpenAI, Anthropic, LangChain, Vercel AI, or Google GenAI
CronsApp uses node-cron, Bull, BullMQ, Agenda, or any scheduled task pattern
MetricsApp needs custom counters, gauges, or histograms
Runtime MetricsAny Node.js or Bun service wanting automatic memory/CPU/event-loop visibility
OTel tracing detected: "I see OpenTelemetry tracing in the project. I recommend Sentry's OTLP integration for tracing (via your existing OTel setup) + Error Monitoring + Sentry Logging [+ Metrics/Crons/AI Monitoring if applicable]. Shall I proceed?"
No OTel: "I recommend setting up Error Monitoring + Tracing. Want me to also add Logging or Profiling?"

根据检测结果给出具体的配置建议,不要提出开放式问题,直接给出方案:
检测到OTel的处理路径:
  • 检测到OTel链路追踪
    package.json
    中存在
    @opentelemetry/sdk-node
    @opentelemetry/sdk-trace-node
    ,或源码中存在
    NodeTracerProvider
    )→ 使用OTLP路径:通过
    @sentry/node-core/light
    启用
    otlpIntegration()
    不要设置
    tracesSampleRate
    ;Sentry会自动将错误与OTel链路关联
推荐的核心覆盖功能:
  • 错误监控 —— 必选;捕获未处理异常、Promise拒绝以及框架错误
  • 链路追踪 —— 通过OpenTelemetry自动监控HTTP、数据库和队列操作
可选的增强可观测性功能:
  • 日志记录 —— 通过
    Sentry.logger.*
    实现结构化日志;当检测到
    winston
    /
    pino
    /
    bunyan
    或需要日志与链路关联时推荐使用
  • 性能分析 —— 持续CPU分析(仅支持Node.js;Bun和Deno暂不支持);OTLP路径下不可用
  • AI监控 —— 支持OpenAI、Anthropic、LangChain、Vercel AI SDK;检测到AI/LLM调用时推荐使用
  • 任务调度监控 —— 检测遗漏或失败的定时任务;检测到node-cron、Bull或Agenda时推荐使用
  • 指标监控 —— 自定义计数器、仪表盘、分布统计;需要自定义关键指标时推荐使用
  • 运行时指标 —— 自动收集内存、CPU和事件循环指标;
    nodeRuntimeMetricsIntegration()
    (Node.js)/
    bunRuntimeMetricsIntegration()
    (Bun)
推荐逻辑:
功能推荐场景
错误监控始终启用 —— 不可缺少的基础功能
OTLP集成检测到OTel链路追踪 —— 替代原生链路追踪
链路追踪服务器应用必选 —— HTTP链路和数据库链路价值高;检测到OTel链路追踪时跳过
日志记录应用使用winston、pino、bunyan,或需要日志与链路关联
性能分析仅Node.js —— 性能敏感型服务;兼容原生插件;检测到OTel链路追踪时跳过(需要
tracesSampleRate
,与OTLP不兼容)
AI监控应用调用OpenAI、Anthropic、LangChain、Vercel AI或Google GenAI
任务调度监控应用使用node-cron、Bull、BullMQ、Agenda或任何定时任务模式
指标监控应用需要自定义计数器、仪表盘或直方图
运行时指标任何需要自动监控内存/CPU/事件循环的Node.js或Bun服务
检测到OTel链路追踪时的话术: “我在项目中检测到了OpenTelemetry链路追踪。我推荐使用Sentry的OTLP集成实现链路追踪(基于你已有的OTel配置)+ 错误监控 + Sentry日志记录 [+ 若适用则添加指标监控/任务调度监控/AI监控]。是否继续?”
未检测到OTel时的话术: “我推荐配置错误监控 + 链路追踪。需要我同时添加日志记录或性能分析吗?”

Phase 3: Guide

阶段3:引导

Runtime: Node.js

运行时:Node.js

Option 1: Wizard (Recommended for Node.js)

选项1:向导工具(Node.js推荐方式)

You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:
npx @sentry/wizard@latest -i node
It handles login, org/project selection, SDK installation,
instrument.js
creation, and package.json script updates.
Once it finishes, come back and skip to Verification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.

你需要自行运行此命令 —— 向导会打开浏览器进行登录,需要交互式操作,无法由代理完成。请复制以下命令到终端执行:
npx @sentry/wizard@latest -i node
它会处理登录、组织/项目选择、SDK安装、
instrument.js
创建以及package.json脚本更新。
完成后返回,直接跳转到验证步骤。
如果用户跳过向导工具,请继续执行选项2(手动配置)。

Option 2: Manual Setup — Node.js

选项2:手动配置 — Node.js

Install
安装
bash
npm install @sentry/node --save
bash
npm install @sentry/node --save

or

yarn add @sentry/node
yarn add @sentry/node

or

pnpm add @sentry/node
undefined
pnpm add @sentry/node
undefined
Create the Instrument File
创建Instrument文件
CommonJS (
instrument.js
):
javascript
// instrument.js — must be loaded before all other modules
const Sentry = require("@sentry/node");

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  sendDefaultPii: true,

  // 100% in dev, lower in production
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,

  // Capture local variable values in stack frames
  includeLocalVariables: true,

  enableLogs: true,
});
ESM (
instrument.mjs
):
javascript
// instrument.mjs — loaded via --import flag before any other module
import * as Sentry from "@sentry/node";

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  sendDefaultPii: true,
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  includeLocalVariables: true,
  enableLogs: true,
});
CommonJS格式(
instrument.js
):
javascript
// instrument.js —— 必须在所有其他模块之前加载
const Sentry = require("@sentry/node");

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  sendDefaultPii: true,

  // 开发环境采样100%,生产环境降低采样率
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,

  // 在堆栈帧中捕获局部变量值
  includeLocalVariables: true,

  enableLogs: true,
});
ESM格式(
instrument.mjs
):
javascript
// instrument.mjs —— 通过--import参数在所有其他模块之前加载
import * as Sentry from "@sentry/node";

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  sendDefaultPii: true,
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  includeLocalVariables: true,
  enableLogs: true,
});
Start Your App with Sentry Loaded First
确保Sentry优先加载并启动应用
CommonJS — add
require("./instrument")
as the very first line of your entry file:
javascript
// app.js
require("./instrument"); // must be first

const express = require("express");
// ... rest of your app
ESM — use the
--import
flag so Sentry loads before all other modules (Node.js 18.19.0+ required):
bash
node --import ./instrument.mjs app.mjs
Add to
package.json
scripts:
json
{
  "scripts": {
    "start": "node --import ./instrument.mjs server.mjs",
    "dev": "node --import ./instrument.mjs --watch server.mjs"
  }
}
Or via environment variable (useful for wrapping existing start commands):
bash
NODE_OPTIONS="--import ./instrument.mjs" npm start
CommonJS格式 —— 在入口文件的第一行添加
require("./instrument")
javascript
// app.js
require("./instrument"); // 必须是第一行

const express = require("express");
// ... 应用其余代码
ESM格式 —— 使用
--import
参数确保Sentry在所有模块之前加载(需要Node.js 18.19.0+):
bash
node --import ./instrument.mjs app.mjs
将命令添加到
package.json
的脚本中:
json
{
  "scripts": {
    "start": "node --import ./instrument.mjs server.mjs",
    "dev": "node --import ./instrument.mjs --watch server.mjs"
  }
}
或通过环境变量设置(适合包装已有的启动命令):
bash
NODE_OPTIONS="--import ./instrument.mjs" npm start
Framework Error Handlers
框架错误处理器
Register the Sentry error handler after all routes so it can capture framework errors:
Express:
javascript
const express = require("express");
const Sentry = require("@sentry/node");

const app = express();

// ... your routes

// Add AFTER all routes — captures 5xx errors by default
Sentry.setupExpressErrorHandler(app);

// Optional: capture 4xx errors too
// Sentry.setupExpressErrorHandler(app, {
//   shouldHandleError(error) { return error.status >= 400; },
// });

app.listen(3000);
Fastify:
javascript
const Fastify = require("fastify");
const Sentry = require("@sentry/node");

const fastify = Fastify();

// Add BEFORE routes (unlike Express!)
Sentry.setupFastifyErrorHandler(fastify);

// ... your routes

await fastify.listen({ port: 3000 });
Koa:
javascript
const Koa = require("koa");
const Sentry = require("@sentry/node");

const app = new Koa();

// Add as FIRST middleware (catches errors thrown by later middleware)
Sentry.setupKoaErrorHandler(app);

// ... your other middleware and routes

app.listen(3000);
Hapi (async — must await):
javascript
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");

const server = Hapi.server({ port: 3000 });

// ... your routes

// Must await — Hapi registration is async
await Sentry.setupHapiErrorHandler(server);

await server.start();
Connect:
javascript
const connect = require("connect");
const Sentry = require("@sentry/node");

const app = connect();

// Add BEFORE routes (like Fastify and Koa)
Sentry.setupConnectErrorHandler(app);

// ... your middleware and routes

require("http").createServer(app).listen(3000);
NestJS — has its own dedicated skill with full coverage:
Use the
sentry-nestjs-sdk
skill instead.
NestJS uses a separate package (
@sentry/nestjs
) with NestJS-native constructs:
SentryModule.forRoot()
,
SentryGlobalFilter
,
@SentryTraced
,
@SentryCron
decorators, and GraphQL/Microservices support. Load that skill for complete NestJS setup.
Vanilla Node.js
http
module
— wrap request handler manually:
javascript
const http = require("http");
const Sentry = require("@sentry/node");

const server = http.createServer((req, res) => {
  Sentry.withIsolationScope(() => {
    try {
      // your handler
      res.end("OK");
    } catch (err) {
      Sentry.captureException(err);
      res.writeHead(500);
      res.end("Internal Server Error");
    }
  });
});

server.listen(3000);
Framework error handler summary:
FrameworkFunctionPlacementAsync?
Express
setupExpressErrorHandler(app)
After all routesNo
Fastify
setupFastifyErrorHandler(fastify)
Before routesNo
Koa
setupKoaErrorHandler(app)
First middlewareNo
Hapi
setupHapiErrorHandler(server)
Before
server.start()
Yes
Connect
setupConnectErrorHandler(app)
Before routesNo
NestJS→ Use
sentry-nestjs-sdk
Dedicated skill

在所有路由之后注册Sentry错误处理器,以便捕获框架错误:
Express:
javascript
const express = require("express");
const Sentry = require("@sentry/node");

const app = express();

// ... 你的路由

// 在所有路由之后添加 —— 默认捕获5xx错误
Sentry.setupExpressErrorHandler(app);

// 可选:同时捕获4xx错误
// Sentry.setupExpressErrorHandler(app, {
//   shouldHandleError(error) { return error.status >= 400; },
// });

app.listen(3000);
Fastify:
javascript
const Fastify = require("fastify");
const Sentry = require("@sentry/node");

const fastify = Fastify();

// 在路由之前添加(与Express不同!)
Sentry.setupFastifyErrorHandler(fastify);

// ... 你的路由

await fastify.listen({ port: 3000 });
Koa:
javascript
const Koa = require("koa");
const Sentry = require("@sentry/node");

const app = new Koa();

// 作为第一个中间件添加(捕获后续中间件抛出的错误)
Sentry.setupKoaErrorHandler(app);

// ... 你的其他中间件和路由

app.listen(3000);
Hapi(异步操作 — 必须使用await):
javascript
const Hapi = require("@hapi/hapi");
const Sentry = require("@sentry/node");

const server = Hapi.server({ port: 3000 });

// ... 你的路由

// 必须使用await — Hapi的注册是异步操作
await Sentry.setupHapiErrorHandler(server);

await server.start();
Connect:
javascript
const connect = require("connect");
const Sentry = require("@sentry/node");

const app = connect();

// 在路由之前添加(与Fastify和Koa相同)
Sentry.setupConnectErrorHandler(app);

// ... 你的中间件和路由

require("http").createServer(app).listen(3000);
NestJS —— 有专门的技能提供完整覆盖:
请改用
sentry-nestjs-sdk
技能。
NestJS使用单独的包(
@sentry/nestjs
),支持NestJS原生结构:
SentryModule.forRoot()
SentryGlobalFilter
@SentryTraced
@SentryCron
装饰器, 以及GraphQL/微服务支持。加载该技能以完成完整的NestJS配置。
原生Node.js
http
模块
—— 手动包装请求处理器:
javascript
const http = require("http");
const Sentry = require("@sentry/node");

const server = http.createServer((req, res) => {
  Sentry.withIsolationScope(() => {
    try {
      // 你的处理器逻辑
      res.end("OK");
    } catch (err) {
      Sentry.captureException(err);
      res.writeHead(500);
      res.end("Internal Server Error");
    }
  });
});

server.listen(3000);
框架错误处理器汇总:
框架函数位置是否异步
Express
setupExpressErrorHandler(app)
所有路由之后
Fastify
setupFastifyErrorHandler(fastify)
路由之前
Koa
setupKoaErrorHandler(app)
第一个中间件
Hapi
setupHapiErrorHandler(server)
server.start()
之前
Connect
setupConnectErrorHandler(app)
路由之前
NestJS→ 使用
sentry-nestjs-sdk
专用技能

Runtime: Bun

运行时:Bun

No wizard available for Bun. Manual setup only.
Bun暂无向导工具。 仅支持手动配置。

Install

安装

bash
bun add @sentry/bun
bash
bun add @sentry/bun

Create
instrument.ts
(or
instrument.js
)

创建
instrument.ts
(或
instrument.js

typescript
// instrument.ts
import * as Sentry from "@sentry/bun";

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  sendDefaultPii: true,
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  enableLogs: true,
});
typescript
// instrument.ts
import * as Sentry from "@sentry/bun";

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? "___DSN___",

  sendDefaultPii: true,
  tracesSampleRate: process.env.NODE_ENV === "development" ? 1.0 : 0.1,
  enableLogs: true,
});

Start Your App with
--preload

使用
--preload
启动应用

bash
bun --preload ./instrument.ts server.ts
Add to
package.json
:
json
{
  "scripts": {
    "start": "bun --preload ./instrument.ts server.ts",
    "dev": "bun --watch --preload ./instrument.ts server.ts"
  }
}
bash
bun --preload ./instrument.ts server.ts
添加到
package.json
json
{
  "scripts": {
    "start": "bun --preload ./instrument.ts server.ts",
    "dev": "bun --watch --preload ./instrument.ts server.ts"
  }
}

Bun.serve() — Auto-Instrumentation

Bun.serve() — 自动插桩

@sentry/bun
automatically instruments
Bun.serve()
via JavaScript Proxy. No extra setup is required — just initialize with
--preload
and your
Bun.serve()
calls are traced:
typescript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello from Bun!");
  },
});
@sentry/bun
通过JavaScript Proxy自动为
Bun.serve()
插桩。无需额外配置 —— 只需通过
--preload
初始化,你的
Bun.serve()
调用就会被自动追踪:
typescript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello from Bun!");
  },
});

Framework Error Handlers on Bun

Bun上的框架错误处理器

Bun can run Express, Fastify, Hono, and Elysia. Use the same
@sentry/bun
import and the
@sentry/node
error handler functions (re-exported by
@sentry/bun
):
typescript
import * as Sentry from "@sentry/bun";
import express from "express";

const app = express();
// ... routes
Sentry.setupExpressErrorHandler(app);
app.listen(3000);
Bun可以运行Express、Fastify、Hono和Elysia。使用相同的
@sentry/bun
导入,并使用
@sentry/node
的错误处理器函数(由
@sentry/bun
重新导出):
typescript
import * as Sentry from "@sentry/bun";
import express from "express";

const app = express();
// ... 路由
Sentry.setupExpressErrorHandler(app);
app.listen(3000);

Bun Feature Support

Bun功能支持情况

FeatureBun SupportNotes
Error Monitoring✅ FullSame API as Node
Tracing✅ Via
@sentry/node
OTel
Most auto-instrumentations work
Logging✅ Full
enableLogs: true
+
Sentry.logger.*
Profiling❌ Not available
@sentry/profiling-node
uses native addons incompatible with Bun
Metrics✅ Full
Sentry.metrics.*
Runtime Metrics✅ Full
bunRuntimeMetricsIntegration()
— memory, CPU, event loop (no event loop delay percentiles)
Crons✅ Full
Sentry.withMonitor()
AI Monitoring✅ FullOpenAI, Anthropic integrations work

功能Bun支持情况说明
错误监控✅ 完整支持与Node.js API相同
链路追踪✅ 通过
@sentry/node
OTEL
大多数自动插桩功能可用
日志记录✅ 完整支持
enableLogs: true
+
Sentry.logger.*
性能分析❌ 暂不支持
@sentry/profiling-node
使用的原生插件与Bun不兼容
指标监控✅ 完整支持
Sentry.metrics.*
运行时指标✅ 完整支持
bunRuntimeMetricsIntegration()
—— 内存、CPU、事件循环(无事件循环延迟百分位数)
任务调度监控✅ 完整支持
Sentry.withMonitor()
AI监控✅ 完整支持OpenAI、Anthropic集成可用

Runtime: Deno

运行时:Deno

No wizard available for Deno. Manual setup only. Requires Deno 2.0+. Deno 1.x is not supported. Use
npm:
specifier.
The
deno.land/x/sentry
registry is deprecated.
Deno暂无向导工具。 仅支持手动配置。 需要Deno 2.0+。 Deno 1.x版本不被支持。 使用
npm:
标识符。
deno.land/x/sentry
注册表已被弃用。

Install via
deno.json
(Recommended)

通过
deno.json
安装(推荐方式)

json
{
  "imports": {
    "@sentry/deno": "npm:@sentry/deno@10.42.0"
  }
}
Or import directly with the
npm:
specifier:
typescript
import * as Sentry from "npm:@sentry/deno";
json
{
  "imports": {
    "@sentry/deno": "npm:@sentry/deno@10.42.0"
  }
}
或直接使用
npm:
标识符导入:
typescript
import * as Sentry from "npm:@sentry/deno";

Initialize — Add to Entry File

初始化 — 添加到入口文件

typescript
// main.ts — Sentry.init() must be called before any other code
import * as Sentry from "@sentry/deno";

Sentry.init({
  dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",

  sendDefaultPii: true,
  tracesSampleRate: Deno.env.get("DENO_ENV") === "development" ? 1.0 : 0.1,
  enableLogs: true,
});

// Your application code follows
Deno.serve({ port: 8000 }, (req) => {
  return new Response("Hello from Deno!");
});
Unlike Node.js and Bun, Deno does not have a
--preload
or
--import
flag. Sentry must be the first
import
in your entry file.
typescript
// main.ts —— Sentry.init()必须在其他代码之前调用
import * as Sentry from "@sentry/deno";

Sentry.init({
  dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",

  sendDefaultPii: true,
  tracesSampleRate: Deno.env.get("DENO_ENV") === "development" ? 1.0 : 0.1,
  enableLogs: true,
});

// 你的应用代码写在后面
Deno.serve({ port: 8000 }, (req) => {
  return new Response("Hello from Deno!");
});
与Node.js和Bun不同,Deno没有
--preload
--import
参数。Sentry必须是入口文件中的第一个
import

Required Deno Permissions

Deno所需权限

The SDK requires network access to reach your Sentry ingest domain:
bash
deno run \
  --allow-net=o<ORG_ID>.ingest.sentry.io \
  --allow-read=./src \
  --allow-env=SENTRY_DSN,SENTRY_RELEASE \
  main.ts
For development,
--allow-all
works but is not recommended for production.
SDK需要网络权限以连接到你的Sentry数据接收域名:
bash
deno run \\
  --allow-net=o<ORG_ID>.ingest.sentry.io \\
  --allow-read=./src \\
  --allow-env=SENTRY_DSN,SENTRY_RELEASE \\
  main.ts
开发环境下可以使用
--allow-all
,但不推荐在生产环境使用。

Deno Cron Integration

Deno任务调度集成

Deno provides native cron scheduling. Use
denoCronIntegration
for automatic monitoring:
typescript
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";

Sentry.init({
  dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
  integrations: [denoCronIntegration()],
});

// Cron is automatically monitored
Deno.cron("daily-cleanup", "0 0 * * *", () => {
  // cleanup logic
});
Deno提供原生任务调度功能。使用
denoCronIntegration
实现自动监控:
typescript
import * as Sentry from "@sentry/deno";
import { denoCronIntegration } from "@sentry/deno";

Sentry.init({
  dsn: Deno.env.get("SENTRY_DSN") ?? "___DSN___",
  integrations: [denoCronIntegration()],
});

// 任务调度会被自动监控
Deno.cron("daily-cleanup", "0 0 * * *", () => {
  // 清理逻辑
});

Deno Feature Support

Deno功能支持情况

FeatureDeno SupportNotes
Error Monitoring✅ FullUnhandled exceptions +
captureException
Tracing✅ Custom OTelAutomatic spans for
Deno.serve()
and
fetch
Logging✅ Full
enableLogs: true
+
Sentry.logger.*
Profiling❌ Not availableNo profiling addon for Deno
Metrics✅ Full
Sentry.metrics.*
Runtime Metrics❌ Not availableNo runtime metrics integration for Deno
Crons✅ Full
denoCronIntegration()
+
Sentry.withMonitor()
AI Monitoring✅ PartialVercel AI SDK integration works; OpenAI/Anthropic via
npm:

功能Deno支持情况说明
错误监控✅ 完整支持未处理异常 +
captureException
链路追踪✅ 自定义OTEL自动为
Deno.serve()
fetch
创建链路
日志记录✅ 完整支持
enableLogs: true
+
Sentry.logger.*
性能分析❌ 暂不支持暂无针对Deno的性能分析插件
指标监控✅ 完整支持
Sentry.metrics.*
运行时指标❌ 暂不支持暂无针对Deno的运行时指标集成
任务调度监控✅ 完整支持
denoCronIntegration()
+
Sentry.withMonitor()
AI监控✅ 部分支持Vercel AI SDK集成可用;OpenAI/Anthropic需通过
npm:
使用

OTLP Integration (OTel-First Projects — Node.js Only)

OTLP集成(仅适用于以OTel为主的Node.js项目)

Use this path only when OpenTelemetry tracing was detected in Phase 1 (e.g.,
@opentelemetry/sdk-node
or
@opentelemetry/sdk-trace-node
in
package.json
). For projects without an existing OTel setup, use the standard
@sentry/node
path above.
The OTLP integration uses
@sentry/node-core/light
— a lightweight Sentry SDK that does not bundle its own OpenTelemetry. Instead, it hooks into the user's existing OTel
TracerProvider
and exports spans to Sentry via OTLP.
仅当阶段1中检测到OpenTelemetry链路追踪时使用此路径 (例如
package.json
中存在
@opentelemetry/sdk-node
@opentelemetry/sdk-trace-node
)。 对于没有现有OTel配置的项目,请使用上文的标准
@sentry/node
路径。
OTLP集成使用
@sentry/node-core/light
—— 轻量级Sentry SDK,不包含内置的OpenTelemetry。相反,它会挂钩到用户已有的OTel
TracerProvider
,并通过OTLP将链路导出到Sentry。

When to Use

使用场景

ScenarioRecommended path
New project, no existing OTelStandard
@sentry/node
(above) — includes built-in OTel
Existing OTel setup, want Sentry tracing
@sentry/node-core/light
+
otlpIntegration()
Existing OTel setup, sending to own Collector
@sentry/node-core/light
+
otlpIntegration({ collectorUrl })
场景推荐路径
新项目,无现有OTel标准
@sentry/node
(上文)—— 包含内置OTel
已有OTel配置,需要Sentry链路追踪
@sentry/node-core/light
+
otlpIntegration()
已有OTel配置,发送到自有Collector
@sentry/node-core/light
+
otlpIntegration({ collectorUrl })

Install

安装

bash
npm install @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
bash
npm install @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base

or

yarn add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
yarn add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base

or

pnpm add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base

> The `@opentelemetry/*` packages are peer dependencies. If the project already has them installed, skip duplicates.
pnpm add @sentry/node-core @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base

> `@opentelemetry/*`包是对等依赖项。如果项目已安装这些包,请跳过重复安装。

Initialize

初始化

javascript
// instrument.mjs — load via --import flag before any other module
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import * as Sentry from '@sentry/node-core/light';
import { otlpIntegration } from '@sentry/node-core/light/otlp';

// Register the user's OTel TracerProvider first
const provider = new NodeTracerProvider();
provider.register();

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? '___DSN___',

  sendDefaultPii: true,
  enableLogs: true,

  // Do NOT set tracesSampleRate — OTel controls sampling
  integrations: [
    otlpIntegration({
      // Export OTel spans to Sentry via OTLP (default: true)
      setupOtlpTracesExporter: true,
    }),
  ],
});
With a custom Collector endpoint:
javascript
Sentry.init({
  dsn: process.env.SENTRY_DSN ?? '___DSN___',
  integrations: [
    otlpIntegration({
      collectorUrl: 'http://localhost:4318/v1/traces',
    }),
  ],
});
javascript
// instrument.mjs —— 通过--import参数在所有其他模块之前加载
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import * as Sentry from '@sentry/node-core/light';
import { otlpIntegration } from '@sentry/node-core/light/otlp';

// 先注册用户的OTel TracerProvider
const provider = new NodeTracerProvider();
provider.register();

Sentry.init({
  dsn: process.env.SENTRY_DSN ?? '___DSN___',

  sendDefaultPii: true,
  enableLogs: true,

  // 不要设置tracesSampleRate —— OTel控制采样
  integrations: [
    otlpIntegration({
      // 通过OTLP将OTel链路导出到Sentry(默认:true)
      setupOtlpTracesExporter: true,
    }),
  ],
});
使用自定义Collector端点:
javascript
Sentry.init({
  dsn: process.env.SENTRY_DSN ?? '___DSN___',
  integrations: [
    otlpIntegration({
      collectorUrl: 'http://localhost:4318/v1/traces',
    }),
  ],
});

Start Your App

启动应用

Same
--import
pattern as the standard Node.js setup:
bash
node --import ./instrument.mjs app.mjs
与标准Node.js配置相同,使用
--import
模式:
bash
node --import ./instrument.mjs app.mjs

Key Differences from Standard
@sentry/node

与标准
@sentry/node
的主要区别

Aspect
@sentry/node
(standard)
@sentry/node-core/light
(OTLP)
OTel bundled✅ Yes — built-in TracerProvider❌ No — uses your existing provider
Tracing control
tracesSampleRate
in
Sentry.init()
OTel SDK controls sampling
Auto-instrumentation✅ Built-in (HTTP, DB, etc.)❌ You manage OTel instrumentations
Profiling✅ Available❌ Not compatible
Error ↔ trace linking✅ Automatic✅ Automatic (via
otlpIntegration
)
Package sizeLarger (includes OTel)Smaller (light mode)

方面
@sentry/node
(标准)
@sentry/node-core/light
(OTLP)
内置OTel✅ 是 —— 包含内置TracerProvider❌ 否 —— 使用用户已有的Provider
链路追踪控制
Sentry.init()
中设置
tracesSampleRate
OTel SDK控制采样
自动插桩✅ 内置(HTTP、数据库等)❌ 用户自行管理OTel插桩
性能分析✅ 可用❌ 不兼容
错误与链路关联✅ 自动关联✅ 自动关联(通过
otlpIntegration
包大小较大(包含OTel)较小(轻量模式)

For Each Agreed Feature

针对每个确认的功能

Load the corresponding reference file and follow its steps:
FeatureReference fileLoad when...
Error Monitoring
references/error-monitoring.md
Always (baseline) — captures, scopes, enrichment, beforeSend
OTLP IntegrationSee OTLP Integration aboveOTel tracing detected — replaces native Tracing
Tracing
references/tracing.md
OTel auto-instrumentation, custom spans, distributed tracing, sampling; skip if OTel tracing detected
Logging
references/logging.md
Structured logs,
Sentry.logger.*
, log-to-trace correlation
Profiling
references/profiling.md
Node.js only — CPU profiling, Bun/Deno gaps documented; skip if OTel tracing detected
Metrics
references/metrics.md
Custom counters, gauges, distributions
Runtime MetricsSee inline belowAutomatic memory, CPU, and event loop metrics for Node.js and Bun
Crons
references/crons.md
Scheduled job monitoring, node-cron, Bull, Agenda, Deno.cron
AI MonitoringLoad
sentry-setup-ai-monitoring
skill
OpenAI, Anthropic, LangChain, Vercel AI, Google GenAI
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
加载对应的参考文件并按照步骤操作:
功能参考文件加载时机
错误监控
references/error-monitoring.md
始终加载(基础功能)—— 捕获、作用域、增强、beforeSend
OTLP集成参见上文OTLP集成检测到OTel链路追踪 —— 替代原生链路追踪
链路追踪
references/tracing.md
OTel自动插桩、自定义链路、分布式追踪、采样;检测到OTel链路追踪时跳过
日志记录
references/logging.md
结构化日志、
Sentry.logger.*
、日志与链路关联
性能分析
references/profiling.md
仅Node.js —— CPU分析,Bun/Deno不支持;检测到OTel链路追踪时跳过
指标监控
references/metrics.md
自定义计数器、仪表盘、分布统计
运行时指标参见下文内联内容自动收集Node.js和Bun的内存、CPU和事件循环指标
任务调度监控
references/crons.md
定时任务监控、node-cron、Bull、Agenda、Deno.cron
AI监控加载
sentry-setup-ai-monitoring
技能
OpenAI、Anthropic、LangChain、Vercel AI、Google GenAI
针对每个功能:读取参考文件,严格按照步骤操作,并在进行下一步前验证配置。

Runtime Metrics

运行时指标

Automatically collect Node.js and Bun runtime health metrics (memory, CPU utilization, event loop delay/utilization, uptime) at a configurable interval. Metrics appear in Sentry's Metrics product under the
node.runtime.*
/
bun.runtime.*
namespace.
Node.js — add
nodeRuntimeMetricsIntegration()
to your
instrument.js
:
javascript
const Sentry = require("@sentry/node");

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  integrations: [
    Sentry.nodeRuntimeMetricsIntegration(),
    // Optional: change collection interval (default 30 000 ms)
    // Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
  ],
});
Metrics collected by default:
node.runtime.mem.rss
,
node.runtime.mem.heap_used
,
node.runtime.mem.heap_total
,
node.runtime.cpu.utilization
,
node.runtime.event_loop.delay.p50
,
node.runtime.event_loop.delay.p99
,
node.runtime.event_loop.utilization
,
node.runtime.process.uptime
.
Bun — add
bunRuntimeMetricsIntegration()
to your
instrument.ts
:
typescript
import * as Sentry from "@sentry/bun";
import { bunRuntimeMetricsIntegration } from "@sentry/bun";

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  integrations: [
    bunRuntimeMetricsIntegration(),
    // Optional: change collection interval (default 30 000 ms)
    // bunRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
  ],
});
Metrics collected: same as Node.js except no event loop delay percentiles (unavailable in Bun). Prefixed with
bun.runtime.*
.

自动收集Node.js和Bun的运行时健康指标(内存、CPU使用率、事件循环延迟/使用率、运行时间),可配置收集间隔。指标会显示在Sentry的Metrics产品中,命名空间为
node.runtime.*
/
bun.runtime.*
Node.js —— 在
instrument.js
中添加
nodeRuntimeMetricsIntegration()
javascript
const Sentry = require("@sentry/node");

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  integrations: [
    Sentry.nodeRuntimeMetricsIntegration(),
    // 可选:修改收集间隔(默认30000毫秒)
    // Sentry.nodeRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
  ],
});
默认收集的指标:
node.runtime.mem.rss
node.runtime.mem.heap_used
node.runtime.mem.heap_total
node.runtime.cpu.utilization
node.runtime.event_loop.delay.p50
node.runtime.event_loop.delay.p99
node.runtime.event_loop.utilization
node.runtime.process.uptime
Bun —— 在
instrument.ts
中添加
bunRuntimeMetricsIntegration()
typescript
import * as Sentry from "@sentry/bun";
import { bunRuntimeMetricsIntegration } from "@sentry/bun";

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  integrations: [
    bunRuntimeMetricsIntegration(),
    // 可选:修改收集间隔(默认30000毫秒)
    // bunRuntimeMetricsIntegration({ collectionIntervalMs: 60_000 }),
  ],
});
收集的指标:与Node.js相同,但不包含事件循环延迟百分位数(Bun暂不支持)。指标前缀为
bun.runtime.*

Verification

验证

After setup, verify Sentry is receiving events:
javascript
// Add temporarily to your entry file or a test route, then remove
import * as Sentry from "@sentry/node"; // or @sentry/bun / @sentry/deno

Sentry.captureException(new Error("Sentry test error — delete me"));
Or trigger an unhandled exception:
javascript
// In a route handler or startup — will be captured automatically
throw new Error("Sentry test error — delete me");
Then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
CheckHow
Error capturedThrow in a handler, verify in Sentry Issues
Tracing workingCheck Performance tab — should show HTTP spans
includeLocalVariables
working
Stack frame in Sentry should show variable values
Source maps workingStack trace shows readable file names, not minified

配置完成后,验证Sentry是否正在接收事件:
javascript
// 临时添加到入口文件或测试路由,之后删除
import * as Sentry from "@sentry/node"; // 或@sentry/bun / @sentry/deno

Sentry.captureException(new Error("Sentry测试错误 —— 请删除此代码"));
或触发一个未处理异常:
javascript
// 在路由处理器或启动代码中添加 —— 会被自动捕获
throw new Error("Sentry测试错误 —— 请删除此代码");
然后查看你的Sentry问题仪表板 —— 错误应该会在约30秒内显示。
验证清单:
检查项检查方式
错误已捕获在处理器中抛出错误,在Sentry问题列表中验证
链路追踪正常工作查看Performance标签页 —— 应显示HTTP链路
includeLocalVariables
正常工作
Sentry中的堆栈帧应显示变量值
Source Maps正常工作堆栈跟踪显示可读的文件名,而非混淆后的名称

Config Reference

配置参考

Sentry.init()
Core Options

Sentry.init()
核心选项

OptionTypeDefaultNotes
dsn
string
Required. Also from
SENTRY_DSN
env var
tracesSampleRate
number
0–1; required to enable tracing; do not set when using OTLP path
sendDefaultPii
boolean
false
Include IP, request headers, user info
includeLocalVariables
boolean
false
Add local variable values to stack frames (Node.js)
enableLogs
boolean
false
Enable Sentry Logs product (v9.41.0+)
environment
string
"production"
Also from
SENTRY_ENVIRONMENT
env var
release
string
Also from
SENTRY_RELEASE
env var
debug
boolean
false
Log SDK activity to console
enabled
boolean
true
Set
false
in tests to disable sending
sampleRate
number
1.0
Fraction of error events to send (0–1)
shutdownTimeout
number
2000
Milliseconds to flush events before process exit
选项类型默认值说明
dsn
string
必填项。也可通过
SENTRY_DSN
环境变量设置
tracesSampleRate
number
0–1;启用链路追踪时必填;使用OTLP路径时不要设置
sendDefaultPii
boolean
false
包含IP、请求头、用户信息
includeLocalVariables
boolean
false
在堆栈帧中添加局部变量值(仅Node.js)
enableLogs
boolean
false
启用Sentry Logs产品(v9.41.0+)
environment
string
"production"
也可通过
SENTRY_ENVIRONMENT
环境变量设置
release
string
也可通过
SENTRY_RELEASE
环境变量设置
debug
boolean
false
将SDK活动日志输出到控制台
enabled
boolean
true
测试环境中设置为
false
以禁用事件发送
sampleRate
number
1.0
要发送的错误事件比例(0–1)
shutdownTimeout
number
2000
进程退出前刷新事件的毫秒数

nativeNodeFetchIntegration()
Options

nativeNodeFetchIntegration()
选项

Configures outgoing
fetch
/
undici
span capture. Since
@opentelemetry/instrumentation-undici@0.22.0
, response headers like
content-length
are no longer captured automatically — use
headersToSpanAttributes
to opt in:
javascript
Sentry.init({
  integrations: [
    Sentry.nativeNodeFetchIntegration({
      headersToSpanAttributes: {
        requestHeaders: ["x-request-id"],
        responseHeaders: ["content-length", "content-type"],
      },
    }),
  ],
});
OptionTypeDefaultNotes
breadcrumbs
boolean
true
Record breadcrumbs for outgoing fetch requests
headersToSpanAttributes.requestHeaders
string[]
Request header names to capture as span attributes
headersToSpanAttributes.responseHeaders
string[]
Response header names to capture as span attributes
配置 outgoing
fetch
/
undici
链路捕获。自
@opentelemetry/instrumentation-undici@0.22.0
起,
content-length
等响应头不再被自动捕获 —— 使用
headersToSpanAttributes
选择启用:
javascript
Sentry.init({
  integrations: [
    Sentry.nativeNodeFetchIntegration({
      headersToSpanAttributes: {
        requestHeaders: ["x-request-id"],
        responseHeaders: ["content-length", "content-type"],
      },
    }),
  ],
});
选项类型默认值说明
breadcrumbs
boolean
true
为 outgoing fetch请求记录面包屑
headersToSpanAttributes.requestHeaders
string[]
要捕获为链路属性的请求头名称
headersToSpanAttributes.responseHeaders
string[]
要捕获为链路属性的响应头名称

otlpIntegration()
Options (
@sentry/node-core/light/otlp
)

otlpIntegration()
选项(
@sentry/node-core/light/otlp

For OTel-first projects using
@sentry/node-core/light
. Import:
import { otlpIntegration } from '@sentry/node-core/light/otlp'
.
OptionTypeDefaultPurpose
setupOtlpTracesExporter
boolean
true
Auto-configure OTLP exporter to send spans to Sentry; set
false
if you already export to your own Collector
collectorUrl
string
undefined
OTLP HTTP endpoint of an OTel Collector (e.g.,
http://localhost:4318/v1/traces
); when set, spans are sent to the collector instead of the DSN-derived Sentry endpoint
适用于使用
@sentry/node-core/light
的以OTel为主的项目。导入方式:
import { otlpIntegration } from '@sentry/node-core/light/otlp'
选项类型默认值用途
setupOtlpTracesExporter
boolean
true
自动配置OTLP导出器以将链路发送到Sentry;如果已导出到自有Collector,请设置为
false
collectorUrl
string
undefined
OTel Collector的OTLP HTTP端点(例如
http://localhost:4318/v1/traces
);设置后,链路会发送到该Collector而非DSN对应的Sentry端点

Graceful Shutdown

优雅关闭

Flush buffered events before process exit — important for short-lived scripts and serverless:
javascript
process.on("SIGTERM", async () => {
  await Sentry.close(2000); // flush with 2s timeout
  process.exit(0);
});
进程退出前刷新缓冲的事件 —— 对短生命周期脚本和无服务器环境非常重要:
javascript
process.on("SIGTERM", async () => {
  await Sentry.close(2000); // 2秒超时时间内刷新事件
  process.exit(0);
});

Environment Variables

环境变量

VariablePurposeRuntime
SENTRY_DSN
DSN (alternative to hardcoding in
init()
)
All
SENTRY_ENVIRONMENT
Deployment environmentAll
SENTRY_RELEASE
Release version string (auto-detected from git)All
SENTRY_AUTH_TOKEN
Source map upload tokenBuild time
SENTRY_ORG
Org slug for source map uploadBuild time
SENTRY_PROJECT
Project slug for source map uploadBuild time
NODE_OPTIONS
Set
--import ./instrument.mjs
for ESM
Node.js
变量用途运行时
SENTRY_DSN
DSN(替代在
init()
中硬编码)
所有
SENTRY_ENVIRONMENT
部署环境所有
SENTRY_RELEASE
版本字符串(从git自动检测)所有
SENTRY_AUTH_TOKEN
Source Map上传令牌构建时
SENTRY_ORG
Source Map上传的组织标识构建时
SENTRY_PROJECT
Source Map上传的项目标识构建时
NODE_OPTIONS
为ESM设置
--import ./instrument.mjs
Node.js

Source Maps (Node.js)

Source Maps(Node.js)

Readable stack traces in production require source map upload. Use
@sentry/cli
or the webpack/esbuild/rollup plugins:
bash
npm install @sentry/cli --save-dev
bash
undefined
生产环境中可读的堆栈跟踪需要上传Source Map。使用
@sentry/cli
或webpack/esbuild/rollup插件:
bash
npm install @sentry/cli --save-dev
bash
undefined

Create a Sentry auth token at sentry.io/settings/auth-tokens/

在sentry.io/settings/auth-tokens/创建Sentry授权令牌

Set in .env.sentry-build-plugin (gitignore this file):

在.env.sentry-build-plugin中设置(将此文件加入gitignore):

SENTRY_AUTH_TOKEN=sntrys_eyJ...

Add upload step to your build:

```json
{
  "scripts": {
    "build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
  }
}

SENTRY_AUTH_TOKEN=sntrys_eyJ...

在构建步骤中添加上传命令:

```json
{
  "scripts": {
    "build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
  }
}

Phase 4: Cross-Link

阶段4:跨服务关联

After completing backend setup, check for companion services:
bash
undefined
后端配置完成后,检查是否存在配套服务:
bash
undefined

Frontend companion

配套前端

ls frontend/ web/ client/ ui/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
ls frontend/ web/ client/ ui/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'

Other backend services

其他后端服务

ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null

If a frontend, framework-specific SDK, or other backend is found, suggest the matching skill:

**Dedicated JavaScript framework skills (prefer these over generic node-sdk):**

| Detected | Prefer skill | Why |
|----------|-------------|-----|
| NestJS (`@nestjs/core` in `package.json`) | [`sentry-nestjs-sdk`](../sentry-nestjs-sdk/SKILL.md) | Uses `@sentry/nestjs` with NestJS-native decorators, filters, and GraphQL support |
| Next.js (`next` in `package.json`) | [`sentry-nextjs-sdk`](../sentry-nextjs-sdk/SKILL.md) | Three-runtime architecture (browser, server, edge), `withSentryConfig`, source map upload |

**Frontend companions:**

| Detected | Suggest |
|---------|---------|
| React app (`react` in `package.json`) | [`sentry-react-sdk`](../sentry-react-sdk/SKILL.md) |
| Svelte/SvelteKit | [`sentry-svelte-sdk`](../sentry-svelte-sdk/SKILL.md) |

**Other backend companions:**

| Detected | Suggest |
|---------|---------|
| Go backend (`go.mod`) | [`sentry-go-sdk`](../sentry-go-sdk/SKILL.md) |
| Python backend (`requirements.txt`, `pyproject.toml`) | [`sentry-python-sdk`](../sentry-python-sdk/SKILL.md) |
| Ruby backend (`Gemfile`) | [`sentry-ruby-sdk`](../sentry-ruby-sdk/SKILL.md) |

Connecting frontend and backend with the same DSN or linked projects enables **distributed tracing** — stack traces that span your browser, API server, and database in a single trace view.

---
ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null

如果检测到前端、框架专用SDK或其他后端服务,建议使用匹配的技能:

**JavaScript框架专用技能(优先于通用node-sdk):**

| 检测到的内容 | 优先使用的技能 | 原因 |
|----------|-------------|-----|
| NestJS(`package.json`中存在`@nestjs/core`) | [`sentry-nestjs-sdk`](../sentry-nestjs-sdk/SKILL.md) | 使用`@sentry/nestjs`,支持NestJS原生装饰器、过滤器和GraphQL支持 |
| Next.js(`package.json`中存在`next`) | [`sentry-nextjs-sdk`](../sentry-nextjs-sdk/SKILL.md) | 适配三运行时架构(浏览器、服务器、边缘端),支持`withSentryConfig`和Source Map上传 |

**配套前端:**

| 检测到的内容 | 建议使用的技能 |
|---------|---------|
| React应用(`package.json`中存在`react`) | [`sentry-react-sdk`](../sentry-react-sdk/SKILL.md) |
| Svelte/SvelteKit | [`sentry-svelte-sdk`](../sentry-svelte-sdk/SKILL.md) |

**其他配套后端:**

| 检测到的内容 | 建议使用的技能 |
|---------|---------|
| Go后端(`go.mod`) | [`sentry-go-sdk`](../sentry-go-sdk/SKILL.md) |
| Python后端(`requirements.txt`、`pyproject.toml`) | [`sentry-python-sdk`](../sentry-python-sdk/SKILL.md) |
| Ruby后端(`Gemfile`) | [`sentry-ruby-sdk`](../sentry-ruby-sdk/SKILL.md) |

使用相同的DSN或关联项目将前端和后端连接起来,可实现**分布式链路追踪** —— 在单个链路视图中跨浏览器、API服务器和数据库展示完整的堆栈跟踪。

---

Troubleshooting

故障排除

IssueCauseSolution
Events not appearing
instrument.js
loaded too late
Ensure it's the first
require()
/ loaded via
--import
or
--preload
Tracing spans missing
tracesSampleRate
not set
Add
tracesSampleRate: 1.0
to
Sentry.init()
ESM instrumentation not workingMissing
--import
flag
Run with
node --import ./instrument.mjs
;
import "./instrument.mjs"
inside app is not sufficient
@sentry/profiling-node
install fails on Bun
Native addon incompatibleProfiling is not supported on Bun — remove
@sentry/profiling-node
Deno: events not sentMissing
--allow-net
permission
Run with
--allow-net=o<ORG_ID>.ingest.sentry.io
Deno:
deno.land/x/sentry
not working
Deprecated and frozen at v8.55.0Switch to
npm:@sentry/deno
specifier
includeLocalVariables
not showing values
Integration not activated or minified codeEnsure
includeLocalVariables: true
in init; check source maps
NestJS: errors not capturedWrong SDK or missing filterUse
sentry-nestjs-sdk
— NestJS needs
@sentry/nestjs
, not
@sentry/node
Hapi:
setupHapiErrorHandler
timing issue
Not awaitedMust
await Sentry.setupHapiErrorHandler(server)
before
server.start()
Shutdown: events lostProcess exits before flushAdd
await Sentry.close(2000)
in SIGTERM/SIGINT handler
Stack traces show minified codeSource maps not uploadedConfigure
@sentry/cli
source map upload in build step
No traces appearing (OTLP)Missing
@opentelemetry/*
packages or
otlpIntegration
not added
Verify
@opentelemetry/sdk-trace-node
is installed; add
otlpIntegration()
to
integrations
; do not set
tracesSampleRate
OTLP: errors not linked to traces
otlpIntegration
not registered
Ensure
otlpIntegration()
is in the
integrations
array — it registers the propagation context that links errors to OTel traces
Profiling not starting (OTLP)Profiling requires
tracesSampleRate
Profiling is not compatible with the OTLP path; use the standard
@sentry/node
setup instead
问题原因解决方案
事件未显示
instrument.js
加载过晚
确保它是第一个
require()
调用,或通过
--import
/
--preload
加载
链路追踪缺失未设置
tracesSampleRate
Sentry.init()
中添加
tracesSampleRate: 1.0
ESM插桩不生效缺少
--import
参数
使用
node --import ./instrument.mjs
启动;在应用内部
import "./instrument.mjs"
无效
Bun上安装
@sentry/profiling-node
失败
原生插件不兼容Bun不支持性能分析 —— 移除
@sentry/profiling-node
Deno:事件未发送缺少
--allow-net
权限
使用
--allow-net=o<ORG_ID>.ingest.sentry.io
启动
Deno:
deno.land/x/sentry
无法工作
已被弃用并冻结在v8.55.0版本切换到
npm:@sentry/deno
标识符
includeLocalVariables
未显示变量值
集成未激活或代码已混淆确保
init()
中设置
includeLocalVariables: true
;检查Source Maps
NestJS:错误未被捕获使用了错误的SDK或缺少过滤器使用
sentry-nestjs-sdk
—— NestJS需要
@sentry/nestjs
,而非
@sentry/node
Hapi:
setupHapiErrorHandler
时序问题
未使用await必须在
server.start()
之前
await Sentry.setupHapiErrorHandler(server)
关闭时:事件丢失进程在刷新前退出在SIGTERM/SIGINT处理器中添加
await Sentry.close(2000)
堆栈跟踪显示混淆后的代码未上传Source Maps在构建步骤中配置
@sentry/cli
的Source Map上传
OTLP模式下无链路显示缺少
@opentelemetry/*
包或未添加
otlpIntegration
验证
@opentelemetry/sdk-trace-node
已安装;在
integrations
中添加
otlpIntegration()
不要设置
tracesSampleRate
OTLP:错误未与链路关联未注册
otlpIntegration
确保
otlpIntegration()
integrations
数组中 —— 它会注册将错误与OTel链路关联的传播上下文
OTLP模式下性能分析未启动性能分析需要
tracesSampleRate
性能分析与OTLP路径不兼容;改用标准
@sentry/node
配置
",