sentry-node-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > Node.js / Bun / Deno SDK
All Skills > SDK Setup > 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"'

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 |
| 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日志功能 |
| 是否检测到定时任务/调度工具? | 推荐开启Crons定时任务监控 |
| 是否检测到AI库? | 推荐开启AI监控 |
| 是否找到配套前端项目? | 触发阶段4的关联配置引导 |

---

Phase 2: Recommend

阶段2:方案推荐

Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
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)
  • 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
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways for server apps — HTTP spans + DB spans are high-value
LoggingApp uses winston, pino, bunyan, or needs log-to-trace correlation
ProfilingNode.js only — performance-critical service; native addon compatible
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
Propose: "I recommend setting up Error Monitoring + Tracing. Want me to also add Logging or Profiling?"

根据检测结果给出具体的配置建议,不要提出开放式问题,直接给出方案:
推荐核心功能(基础覆盖):
  • 错误监控 — 必选,可捕获未处理异常、Promise拒绝和框架错误
  • 链路追踪 — 基于OpenTelemetry自动埋点HTTP、数据库和队列操作
可选增强功能(提升可观测性):
  • 日志功能 — 通过
    Sentry.logger.*
    输出结构化日志;检测到
    winston
    /
    pino
    /
    bunyan
    或有日志检索需求时推荐开启
  • 性能分析 — 持续CPU性能分析(仅支持Node.js,Bun和Deno暂不支持)
  • AI监控 — 支持OpenAI、Anthropic、LangChain、Vercel AI SDK;检测到AI/LLM调用时推荐开启
  • 定时任务监控 — 检测漏执行或失败的定时任务;检测到node-cron、Bull或Agenda时推荐开启
  • 指标统计 — 自定义计数器、计量器、分布统计;有自定义KPI统计需求时推荐开启
推荐逻辑:
功能推荐开启时机
错误监控始终开启 — 基础必选功能
链路追踪服务端应用始终开启 — HTTP和数据库埋点价值极高
日志功能应用使用winston、pino、bunyan,或者需要日志与链路关联能力
性能分析仅Node.js — 性能敏感的服务,且兼容原生扩展
AI监控应用调用OpenAI、Anthropic、LangChain、Vercel AI或Google GenAI
定时任务监控应用使用node-cron、Bull、BullMQ、Agenda或任何定时任务模式
指标统计应用需要自定义计数器、计量器或直方图统计
建议话术:「我推荐配置错误监控+链路追踪。需要我同时添加日志或性能分析功能吗?」

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.

需要你手动执行 — 引导工具会打开浏览器完成登录,需要交互输入,Agent无法自动处理。复制到终端运行即可:
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.*
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.*
定时任务监控✅ 完整支持使用
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
registry已经废弃。

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 Cron集成

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.*
Crons✅ Full
denoCronIntegration()
+
Sentry.withMonitor()
AI Monitoring✅ PartialVercel AI SDK integration works; OpenAI/Anthropic via
npm:

功能Deno支持情况说明
错误监控✅ 完整支持未处理异常 +
captureException
链路追踪✅ 自定义OTel实现自动为
Deno.serve()
fetch
生成 span
日志功能✅ 完整支持开启
enableLogs: true
+ 使用
Sentry.logger.*
性能分析❌ 暂不支持Deno暂无可支持的性能分析扩展
指标统计✅ 完整支持使用
Sentry.metrics.*
定时任务监控✅ 完整支持
denoCronIntegration()
+
Sentry.withMonitor()
AI监控✅ 部分支持Vercel AI SDK集成可正常工作;OpenAI/Anthropic通过
npm:
导入使用

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
Tracing
references/tracing.md
OTel auto-instrumentation, custom spans, distributed tracing, sampling
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
Metrics
references/metrics.md
Custom counters, gauges, distributions
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钩子
链路追踪
references/tracing.md
OTel自动埋点、自定义span、分布式追踪、采样规则
日志功能
references/logging.md
结构化日志、
Sentry.logger.*
、日志与链路关联
性能分析
references/profiling.md
仅Node.js — CPU性能分析,注明Bun/Deno暂不支持
指标统计
references/metrics.md
自定义计数器、计量器、分布统计
定时任务监控
references/crons.md
定时任务监控、node-cron、Bull、Agenda、Deno.cron
AI监控加载
sentry-setup-ai-monitoring
技能
OpenAI、Anthropic、LangChain、Vercel AI、Google GenAI
每个功能配置完成后,先验证通过再进入下一个功能的配置。

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 Issues面板 — 错误应该会在30秒内出现。
验证检查清单:
检查项验证方式
错误正常捕获在处理器中抛出错误,在Sentry Issues中确认收到
链路追踪正常工作检查Performance面板,应该能看到HTTP span
includeLocalVariables
生效
Sentry中的栈帧应该显示变量值
源码映射正常工作栈追踪显示可读的文件名,不是压缩后的文件名

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
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之间的数值,开启链路追踪必填
sendDefaultPii
boolean
false
是否包含IP、请求头、用户信息
includeLocalVariables
boolean
false
栈帧中添加本地变量值(仅Node.js)
enableLogs
boolean
false
开启Sentry日志功能(v9.41.0+版本支持)
environment
string
"production"
部署环境,也可通过
SENTRY_ENVIRONMENT
环境变量配置
release
string
发布版本号,也可通过
SENTRY_RELEASE
环境变量配置,支持从git自动识别
debug
boolean
false
将SDK活动日志输出到控制台
enabled
boolean
true
测试环境可设为
false
禁用事件上报
sampleRate
number
1.0
错误事件采样率(0–1)
shutdownTimeout
number
2000
进程退出前刷新事件的超时时间(毫秒)

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);
});
进程退出前刷新缓存的事件 — 对短生命周期脚本和Serverless场景非常重要:
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
源码映射上传令牌构建阶段
SENTRY_ORG
组织slug,用于源码映射上传构建阶段
SENTRY_PROJECT
项目slug,用于源码映射上传构建阶段
NODE_OPTIONS
为ESM设置
--import ./instrument.mjs
参数
Node.js

Source Maps (Node.js)

源码映射(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
生产环境下要获得可读的栈追踪需要上传源码映射,使用
@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 auth令牌

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`和源码映射上传 |

**配套前端项目推荐:**

| 检测到 | 推荐技能 |
|---------|---------|
| 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
问题原因解决方案
事件没有上报
instrument.js
加载太晚
确保它是第一个
require()
的模块,或通过
--import
/
--preload
参数加载
链路追踪span缺失没有设置
tracesSampleRate
Sentry.init()
中添加
tracesSampleRate: 1.0
ESM instrumentation不生效缺少
--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
;检查源码映射配置
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)
栈追踪显示压缩后的代码没有上传源码映射在构建步骤中配置
@sentry/cli
上传源码映射