sentry-node-sdk by getsentry/sentry-for-ai
npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-node-sdk一个经过精心设计的向导,它会扫描您的项目并指导您为服务器端 JavaScript 和 TypeScript 运行时(Node.js、Bun 和 Deno)完成完整的 Sentry 设置。
@sentry/node、@sentry/bun 或 @sentry/denoinstrument.js、--import ./instrument.mjs、bun --preload 或 的问题广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
npm:@sentry/denoNestJS? 请改用
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/ 进行验证。
运行以下命令来识别运行时、框架和现有的 Sentry 设置:
# 检测运行时
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"
# 检测现有的 Sentry 包
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
# 检测 Node.js 框架
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
# 检测 Bun 特定框架
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
# 检测 Deno 框架 (deno.json imports)
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
# 检测模块系统 (Node.js)
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
# 检测现有的 instrument 文件
ls instrument.js instrument.mjs instrument.ts instrument.cjs 2>/dev/null
# 检测日志库
cat package.json 2>/dev/null | grep -E '"winston"|"pino"|"bunyan"'
# 检测定时任务 / 调度
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
# 检测 AI / LLM 使用情况
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"@langchain"|"@vercel/ai"|"@google/generative-ai"'
# 检查是否有配套的前端
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 |
| 检测到定时任务 / 作业调度器了吗? | 推荐 Crons 监控 |
| 检测到 AI 库了吗? | 推荐 AI 监控 |
| 发现配套的前端了吗? | 触发阶段 4 的交叉链接 |
根据您的发现提出具体建议。不要问开放式问题 —— 直接给出方案:
推荐(核心覆盖):
可选(增强可观测性):
Sentry.logger.* 进行结构化日志记录;当需要 winston/pino/bunyan 或日志搜索时推荐推荐逻辑:
| 功能 | 何时推荐... |
|---|---|
| 错误监控 | 始终 —— 不可或缺的基线 |
| 追踪 | 始终用于服务器应用 —— HTTP 跨度 + 数据库跨度价值很高 |
| 日志记录 | 应用使用 winston、pino、bunyan,或需要日志与追踪关联 |
| 性能剖析 | 仅限 Node.js —— 性能关键的服务;原生插件兼容 |
| AI 监控 | 应用调用 OpenAI、Anthropic、LangChain、Vercel AI 或 Google GenAI |
| 定时任务 | 应用使用 node-cron、Bull、BullMQ、Agenda 或任何定时任务模式 |
| 指标 | 应用需要自定义计数器、仪表盘或直方图 |
建议:"我建议设置错误监控 + 追踪。您还想添加日志记录或性能剖析吗?"
您需要自己运行此命令 —— 向导会打开浏览器进行登录,并要求交互式输入,这是代理无法处理的。请复制粘贴到您的终端:
npx @sentry/wizard@latest -i node它会处理登录、组织/项目选择、SDK 安装、
instrument.js创建以及 package.json 脚本更新。完成后,请返回并跳转到验证。
如果用户跳过了向导,请继续下面的选项 2(手动设置)。
npm install @sentry/node --save
# 或
yarn add @sentry/node
# 或
pnpm add @sentry/node
CommonJS (instrument.js):
// 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):
// 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,
});
CommonJS —— 在入口文件的第一行添加 require("./instrument"):
// app.js
require("./instrument"); // 必须是第一行
const express = require("express");
// ... 应用的其余部分
ESM —— 使用 --import 标志,以便 Sentry 在所有其他模块之前加载(需要 Node.js 18.19.0+):
node --import ./instrument.mjs app.mjs
添加到 package.json 脚本:
{
"scripts": {
"start": "node --import ./instrument.mjs server.mjs",
"dev": "node --import ./instrument.mjs --watch server.mjs"
}
}
或通过环境变量(适用于包装现有启动命令):
NODE_OPTIONS="--import ./instrument.mjs" npm start
在所有路由之后注册 Sentry 错误处理器,以便捕获框架错误:
Express:
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:
const Fastify = require("fastify");
const Sentry = require("@sentry/node");
const fastify = Fastify();
// 在路由之前添加(与 Express 不同!)
Sentry.setupFastifyErrorHandler(fastify);
// ... 您的路由
await fastify.listen({ port: 3000 });
Koa:
const Koa = require("koa");
const Sentry = require("@sentry/node");
const app = new Koa();
// 作为第一个中间件添加(捕获后续中间件抛出的错误)
Sentry.setupKoaErrorHandler(app);
// ... 您的其他中间件和路由
app.listen(3000);
Hapi (异步 —— 必须 await):
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:
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 模块 —— 手动包装请求处理器:
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 | 专门技能 | — |
Bun 没有可用的向导。 仅支持手动设置。
bun add @sentry/bun
instrument.ts (或 instrument.js)// 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,
});
--preload 启动您的应用bun --preload ./instrument.ts server.ts
添加到 package.json:
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}
@sentry/bun 通过 JavaScript Proxy 自动检测 Bun.serve()。无需额外设置 —— 只需使用 --preload 初始化,您的 Bun.serve() 调用就会被追踪:
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun!");
},
});
Bun 可以运行 Express、Fastify、Hono 和 Elysia。使用相同的 @sentry/bun 导入和 @sentry/node 错误处理器函数(由 @sentry/bun 重新导出):
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... 路由
Sentry.setupExpressErrorHandler(app);
app.listen(3000);
| 功能 | Bun 支持 | 备注 |
|---|---|---|
| 错误监控 | ✅ 完整 | 与 Node 相同的 API |
| 追踪 | ✅ 通过 @sentry/node OTel | 大多数自动检测功能有效 |
| 日志记录 | ✅ 完整 | enableLogs: true + Sentry.logger.* |
| 性能剖析 | ❌ 不支持 | @sentry/profiling-node 使用与 Bun 不兼容的原生插件 |
| 指标 | ✅ 完整 | Sentry.metrics.* |
| 定时任务 | ✅ 完整 | Sentry.withMonitor() |
| AI 监控 | ✅ 完整 | OpenAI、Anthropic 集成有效 |
Deno 没有可用的向导。 仅支持手动设置。需要 Deno 2.0+。 Deno 1.x 不支持。使用
npm:说明符。deno.land/x/sentry注册表已弃用。
deno.json 安装(推荐){
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}
或直接使用 npm: 说明符导入:
import * as Sentry from "npm:@sentry/deno";
// 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。
SDK 需要网络访问权限以连接到您的 Sentry 接收域名:
deno run \
--allow-net=o<ORG_ID>.ingest.sentry.io \
--allow-read=./src \
--allow-env=SENTRY_DSN,SENTRY_RELEASE \
main.ts
对于开发环境,--allow-all 可用,但不建议用于生产。
Deno 提供原生的定时任务调度。使用 denoCronIntegration 进行自动监控:
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 支持 | 备注 |
|---|---|---|
| 错误监控 | ✅ 完整 | 未处理的异常 + captureException |
| 追踪 | ✅ 自定义 OTel | 为 Deno.serve() 和 fetch 自动生成跨度 |
| 日志记录 | ✅ 完整 | enableLogs: true + Sentry.logger.* |
| 性能剖析 | ❌ 不支持 | Deno 没有性能剖析插件 |
| 指标 | ✅ 完整 | Sentry.metrics.* |
| 定时任务 | ✅ 完整 | denoCronIntegration() + Sentry.withMonitor() |
| AI 监控 | ✅ 部分 | Vercel AI SDK 集成有效;OpenAI/Anthropic 通过 npm: |
加载相应的参考文件并按照其步骤操作:
| 功能 | 参考文件 | 何时加载... |
|---|---|---|
| 错误监控 | references/error-monitoring.md | 始终(基线)—— 捕获、作用域、丰富数据、beforeSend |
| 追踪 | references/tracing.md | OTel 自动检测、自定义跨度、分布式追踪、采样 |
| 日志记录 | 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 |
对于每个功能:阅读参考文件,严格按照其步骤操作,并在继续之前进行验证。
设置完成后,验证 Sentry 是否正在接收事件:
// 临时添加到您的入口文件或测试路由中,然后删除
import * as Sentry from "@sentry/node"; // 或 @sentry/bun / @sentry/deno
Sentry.captureException(new Error("Sentry 测试错误 —— 请删除我"));
或触发一个未处理的异常:
// 在路由处理器或启动过程中 —— 会自动被捕获
throw new Error("Sentry 测试错误 —— 请删除我");
然后检查您的 Sentry Issues 仪表板 —— 错误应该在大约 30 秒内出现。
验证清单:
| 检查项 | 方法 |
|---|---|
| 错误被捕获 | 在处理器中抛出错误,在 Sentry Issues 中验证 |
| 追踪正常工作 | 检查 Performance 选项卡 —— 应显示 HTTP 跨度 |
includeLocalVariables 正常工作 | Sentry 中的堆栈帧应显示变量值 |
| Source maps 正常工作 | 堆栈跟踪显示可读的文件名,而不是压缩后的名称 |
Sentry.init() 核心选项| 选项 | 类型 | 默认值 | 备注 |
|---|---|---|---|
dsn | string | — | 必需。也可从 SENTRY_DSN 环境变量获取 |
tracesSampleRate | number | — | 0–1;启用追踪所必需 |
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() 选项配置外发的 fetch/undici 跨度捕获。自 @opentelemetry/instrumentation-undici@0.22.0 起,像 content-length 这样的响应头不再自动捕获 —— 使用 headersToSpanAttributes 来选择加入:
Sentry.init({
integrations: [
Sentry.nativeNodeFetchIntegration({
headersToSpanAttributes: {
requestHeaders: ["x-request-id"],
responseHeaders: ["content-length", "content-type"],
},
}),
],
});
| 选项 | 类型 | 默认值 | 备注 |
|---|---|---|---|
breadcrumbs | boolean | true | 为外发的 fetch 请求记录面包屑 |
headersToSpanAttributes.requestHeaders | string[] | — | 要捕获为跨度属性的请求头名称 |
headersToSpanAttributes.responseHeaders | string[] | — | 要捕获为跨度属性的响应头名称 |
在进程退出前刷新缓冲的事件 —— 对于短时运行的脚本和无服务器函数很重要:
process.on("SIGTERM", async () => {
await Sentry.close(2000); // 使用 2 秒超时进行刷新
process.exit(0);
});
| 变量 | 用途 | 运行时 |
|---|---|---|
SENTRY_DSN | DSN(替代在 init() 中硬编码) | 全部 |
SENTRY_ENVIRONMENT | 部署环境 | 全部 |
SENTRY_RELEASE | 发布版本字符串(从 git 自动检测) | 全部 |
SENTRY_AUTH_TOKEN | Source map 上传令牌 | 构建时 |
SENTRY_ORG | Source map 上传的组织 slug | 构建时 |
SENTRY_PROJECT | Source map 上传的项目 slug | 构建时 |
NODE_OPTIONS | 为 ESM 设置 --import ./instrument.mjs | Node.js |
生产环境中可读的堆栈跟踪需要上传 source map。使用 @sentry/cli 或 webpack/esbuild/rollup 插件:
npm install @sentry/cli --save-dev
# 在 sentry.io/settings/auth-tokens/ 创建 Sentry 认证令牌
# 在 .env.sentry-build-plugin 中设置(将此文件加入 gitignore):
SENTRY_AUTH_TOKEN=sntrys_eyJ...
将上传步骤添加到您的构建中:
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}
完成后端设置后,检查配套服务:
# 前端配套
ls frontend/ web/ client/ ui/ 2>/dev/null
cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'
# 其他后端服务
ls ../go.mod ../requirements.txt ../Gemfile 2>/dev/null
如果发现前端、特定框架的 SDK 或其他后端,建议使用匹配的技能:
专门的 JavaScript 框架技能(优先于通用的 node-sdk):
| 检测到 | 优先技能 | 原因 |
|---|---|---|
NestJS (package.json 中的 @nestjs/core) | sentry-nestjs-sdk | 使用 @sentry/nestjs 并配合 NestJS 原生的装饰器、过滤器以及 GraphQL 支持 |
Next.js (package.json 中的 next) | sentry-nextjs-sdk | 三运行时架构(浏览器、服务器、边缘)、withSentryConfig、source map 上传 |
前端配套:
| 检测到 | 建议 |
|---|---|
React 应用 (package.json 中的 react) | sentry-react-sdk |
| Svelte/SvelteKit | sentry-svelte-sdk |
其他后端配套:
| 检测到 | 建议 |
|---|---|
Go 后端 (go.mod) | sentry-go-sdk |
Python 后端 (requirements.txt, pyproject.toml) | sentry-python-sdk |
Ruby 后端 (Gemfile) | sentry-ruby-sdk |
使用相同的 DSN 或链接的项目连接前端和后端,可以实现分布式追踪 —— 在一个追踪视图中跨越您的浏览器、API 服务器和数据库的堆栈跟踪。
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未出现 | instrument.js 加载太晚 | 确保它是第一个 require() / 通过 --import 或 --preload 加载 |
| 追踪跨度缺失 | tracesSampleRate 未设置 | 在 Sentry.init() 中添加 tracesSampleRate: 1.0 |
| ESM 检测不工作 | 缺少 --import 标志 | 使用 node --import ./instrument.mjs 运行;在应用内部使用 import "./instrument.mjs" 是不够的 |
@sentry/profiling-node 在 Bun 上安装失败 | 原生插件不兼容 | 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 上传 |
每周安装数
243
仓库
GitHub Stars
82
首次出现
Mar 4, 2026
安全审计
安装在
codex239
cursor236
gemini-cli235
github-copilot235
kimi-cli234
amp234
All Skills > SDK Setup > 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.
@sentry/node, @sentry/bun, or @sentry/denoinstrument.js, --import ./instrument.mjs, bun --preload, or npm:@sentry/denoNestJS? Use
sentry-nestjs-sdkinstead — it uses@sentry/nestjswith NestJS-native decorators and filters. Next.js? Usesentry-nextjs-sdkinstead — 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.
Run these commands to identify the runtime, framework, and existing Sentry setup:
# 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"
# Detect existing Sentry packages
cat package.json 2>/dev/null | grep -E '"@sentry/'
cat deno.json deno.jsonc 2>/dev/null | grep -i sentry
# Detect Node.js framework
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@hapi/hapi"|"koa"|"@nestjs/core"|"connect"'
# Detect Bun-specific frameworks
cat package.json 2>/dev/null | grep -E '"elysia"|"hono"'
# Detect Deno frameworks (deno.json imports)
cat deno.json deno.jsonc 2>/dev/null | grep -E '"oak"|"hono"|"fresh"'
# Detect module system (Node.js)
cat package.json 2>/dev/null | grep '"type"'
ls *.mjs *.cjs 2>/dev/null | head -5
# Detect existing instrument file
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"'
# Detect cron / scheduling
cat package.json 2>/dev/null | grep -E '"node-cron"|"cron"|"agenda"|"bull"|"bullmq"'
# Detect AI / LLM usage
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 |
Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
Optional (enhanced observability):
Sentry.logger.*; recommend when winston/pino/bunyan or log search is neededRecommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always for server apps — HTTP spans + DB spans are high-value |
| Logging | App uses winston, pino, bunyan, or needs log-to-trace correlation |
| Profiling | Node.js only — performance-critical service; native addon compatible |
| AI Monitoring | App calls OpenAI, Anthropic, LangChain, Vercel AI, or Google GenAI |
| Crons | App uses node-cron, Bull, BullMQ, Agenda, or any scheduled task pattern |
| Metrics | App needs custom counters, gauges, or histograms |
Propose: "I recommend setting up Error Monitoring + Tracing. Want me to also add Logging or Profiling?"
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 nodeIt handles login, org/project selection, SDK installation,
instrument.jscreation, and package.json script updates.Once it finishes, come back and skip toVerification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.
npm install @sentry/node --save
# or
yarn add @sentry/node
# or
pnpm add @sentry/node
CommonJS (instrument.js):
// 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):
// 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 — add require("./instrument") as the very first line of your entry file:
// 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):
node --import ./instrument.mjs app.mjs
Add to package.json scripts:
{
"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):
NODE_OPTIONS="--import ./instrument.mjs" npm start
Register the Sentry error handler after all routes so it can capture framework errors:
Express:
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:
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:
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):
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:
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-sdkskill instead. NestJS uses a separate package (@sentry/nestjs) with NestJS-native constructs:SentryModule.forRoot(),SentryGlobalFilter,@SentryTraced,@SentryCrondecorators, and GraphQL/Microservices support. Load that skill for complete NestJS setup.
Vanilla Node.jshttp module — wrap request handler manually:
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:
| Framework | Function | Placement | Async? |
|---|---|---|---|
| Express | setupExpressErrorHandler(app) | After all routes | No |
| Fastify | setupFastifyErrorHandler(fastify) | Before routes | No |
| Koa | setupKoaErrorHandler(app) | First middleware | No |
| Hapi | setupHapiErrorHandler(server) |
No wizard available for Bun. Manual setup only.
bun add @sentry/bun
instrument.ts (or instrument.js)// 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,
});
--preloadbun --preload ./instrument.ts server.ts
Add to package.json:
{
"scripts": {
"start": "bun --preload ./instrument.ts server.ts",
"dev": "bun --watch --preload ./instrument.ts server.ts"
}
}
@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:
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from 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):
import * as Sentry from "@sentry/bun";
import express from "express";
const app = express();
// ... routes
Sentry.setupExpressErrorHandler(app);
app.listen(3000);
| Feature | Bun Support | Notes |
|---|---|---|
| Error Monitoring | ✅ Full | Same 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.* |
No wizard available for Deno. Manual setup only. Requires Deno 2.0+. Deno 1.x is not supported. Use
npm:specifier. Thedeno.land/x/sentryregistry is deprecated.
deno.json (Recommended){
"imports": {
"@sentry/deno": "npm:@sentry/deno@10.42.0"
}
}
Or import directly with the npm: specifier:
import * as Sentry from "npm:@sentry/deno";
// 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
--preloador--importflag. Sentry must be the firstimportin your entry file.
The SDK requires network access to reach your Sentry ingest domain:
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.
Deno provides native cron scheduling. Use denoCronIntegration for automatic monitoring:
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
});
| Feature | Deno Support | Notes |
|---|---|---|
| Error Monitoring | ✅ Full | Unhandled exceptions + captureException |
| Tracing | ✅ Custom OTel | Automatic spans for Deno.serve() and fetch |
| Logging | ✅ Full | enableLogs: true + Sentry.logger.* |
| Profiling | ❌ Not available | No profiling addon for Deno |
| Metrics | ✅ Full |
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load 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 |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
After setup, verify Sentry is receiving events:
// 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:
// 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:
| Check | How |
|---|---|
| Error captured | Throw in a handler, verify in Sentry Issues |
| Tracing working | Check Performance tab — should show HTTP spans |
includeLocalVariables working | Stack frame in Sentry should show variable values |
| Source maps working | Stack trace shows readable file names, not minified |
Sentry.init() Core Options| Option | Type | Default | Notes |
|---|---|---|---|
dsn | string | — | Required. Also from SENTRY_DSN env var |
tracesSampleRate | number | — | 0–1; required to enable tracing |
sendDefaultPii | boolean |
nativeNodeFetchIntegration() OptionsConfigures 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:
Sentry.init({
integrations: [
Sentry.nativeNodeFetchIntegration({
headersToSpanAttributes: {
requestHeaders: ["x-request-id"],
responseHeaders: ["content-length", "content-type"],
},
}),
],
});
| Option | Type | Default | Notes |
|---|---|---|---|
breadcrumbs | boolean | true | Record breadcrumbs for outgoing fetch requests |
headersToSpanAttributes.requestHeaders | string[] | — | Request header names to capture as span attributes |
headersToSpanAttributes.responseHeaders |
Flush buffered events before process exit — important for short-lived scripts and serverless:
process.on("SIGTERM", async () => {
await Sentry.close(2000); // flush with 2s timeout
process.exit(0);
});
| Variable | Purpose | Runtime |
|---|---|---|
SENTRY_DSN | DSN (alternative to hardcoding in init()) | All |
SENTRY_ENVIRONMENT | Deployment environment | All |
SENTRY_RELEASE | Release version string (auto-detected from git) | All |
SENTRY_AUTH_TOKEN | Source map upload token | Build time |
SENTRY_ORG |
Readable stack traces in production require source map upload. Use @sentry/cli or the webpack/esbuild/rollup plugins:
npm install @sentry/cli --save-dev
# Create a Sentry auth token at sentry.io/settings/auth-tokens/
# Set in .env.sentry-build-plugin (gitignore this file):
SENTRY_AUTH_TOKEN=sntrys_eyJ...
Add upload step to your build:
{
"scripts": {
"build": "tsc && sentry-cli sourcemaps inject ./dist && sentry-cli sourcemaps upload ./dist"
}
}
After completing backend setup, check for companion services:
# Frontend companion
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 | Uses @sentry/nestjs with NestJS-native decorators, filters, and GraphQL support |
Next.js (next in package.json) | sentry-nextjs-sdk |
Frontend companions:
| Detected | Suggest |
|---|---|
React app (react in package.json) | sentry-react-sdk |
| Svelte/SvelteKit | sentry-svelte-sdk |
Other backend companions:
| Detected | Suggest |
|---|---|
Go backend (go.mod) | sentry-go-sdk |
Python backend (requirements.txt, pyproject.toml) | sentry-python-sdk |
Ruby backend (Gemfile) |
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.
| Issue | Cause | Solution |
|---|---|---|
| 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 working |
Weekly Installs
243
Repository
GitHub Stars
82
First Seen
Mar 4, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex239
cursor236
gemini-cli235
github-copilot235
kimi-cli234
amp234
Electron应用自动化指南:使用agent-browser通过CDP实现桌面应用自动化
11,900 周安装
| Cron / job scheduler detected? | Recommend Crons monitoring |
| AI library detected? | Recommend AI Monitoring |
| Companion frontend found? | Trigger Phase 4 cross-link |
Before server.start() |
| Yes |
| Connect | setupConnectErrorHandler(app) | Before routes | No |
| NestJS | → Use sentry-nestjs-sdk | Dedicated skill | — |
| Crons | ✅ Full | Sentry.withMonitor() |
| AI Monitoring | ✅ Full | OpenAI, Anthropic integrations work |
Sentry.metrics.* |
| Crons | ✅ Full | denoCronIntegration() + Sentry.withMonitor() |
| AI Monitoring | ✅ Partial | Vercel AI SDK integration works; OpenAI/Anthropic via npm: |
| Metrics | references/metrics.md | Custom counters, gauges, distributions |
| Crons | references/crons.md | Scheduled job monitoring, node-cron, Bull, Agenda, Deno.cron |
| AI Monitoring | Load sentry-setup-ai-monitoring skill | OpenAI, Anthropic, LangChain, Vercel AI, Google GenAI |
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 |
string[]| — |
| Response header names to capture as span attributes |
| Org slug for source map upload |
| Build time |
SENTRY_PROJECT | Project slug for source map upload | Build time |
NODE_OPTIONS | Set --import ./instrument.mjs for ESM | Node.js |
Three-runtime architecture (browser, server, edge), withSentryConfig, source map upload |
sentry-ruby-sdkMissing --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 incompatible | Profiling is not supported on Bun — remove @sentry/profiling-node |
| Deno: events not sent | Missing --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.0 | Switch to npm:@sentry/deno specifier |
includeLocalVariables not showing values | Integration not activated or minified code | Ensure includeLocalVariables: true in init; check source maps |
| NestJS: errors not captured | Wrong SDK or missing filter | Use sentry-nestjs-sdk — NestJS needs @sentry/nestjs, not @sentry/node |
Hapi: setupHapiErrorHandler timing issue | Not awaited | Must await Sentry.setupHapiErrorHandler(server) before server.start() |
| Shutdown: events lost | Process exits before flush | Add await Sentry.close(2000) in SIGTERM/SIGINT handler |
| Stack traces show minified code | Source maps not uploaded | Configure @sentry/cli source map upload in build step |