sentry-browser-sdk by getsentry/sentry-for-ai
npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-browser-sdk一个固执己见的向导,它会扫描您的项目并指导您完成针对浏览器 JavaScript(原生 JS、jQuery、静态站点、WordPress 以及任何没有框架特定 SDK 的 JS 项目)的完整 Sentry 设置。
@sentry/browser 或配置 Loader Script注意: 下面的 SDK 版本和 API 反映的是
@sentry/browser≥10.0.0。在实施前,请务必对照 docs.sentry.io/platforms/javascript/ 进行验证。
关键 — 首先检查框架。 框架特定的 SDK 提供显著更好的覆盖率,必须在继续使用 @sentry/browser 之前推荐它们。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
# 检查 React
cat package.json 2>/dev/null | grep -E '"react"'
# 检查 Next.js
cat package.json 2>/dev/null | grep '"next"'
# 检查 Vue
cat package.json 2>/dev/null | grep '"vue"'
# 检查 Angular
cat package.json 2>/dev/null | grep '"@angular/core"'
# 检查 Svelte / SvelteKit
cat package.json 2>/dev/null | grep -E '"svelte"|"@sveltejs/kit"'
# 检查 Remix
cat package.json 2>/dev/null | grep -E '"@remix-run/react"|"@remix-run/node"'
# 检查 Nuxt
cat package.json 2>/dev/null | grep '"nuxt"'
# 检查 Astro
cat package.json 2>/dev/null | grep '"astro"'
# 检查 Ember
cat package.json 2>/dev/null | grep '"ember-source"'
# 检查 Node.js 服务器框架(完全错误的 SDK)
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@nestjs/core"|"koa"'
如果检测到框架,停止并重定向:
| 检测到的框架 | 重定向到 |
|---|---|
next | 加载 sentry-nextjs-sdk 技能 — 不要在此继续 |
react (没有 Next.js) | 加载 sentry-react-sdk 技能 — 不要在此继续 |
vue | 建议使用 @sentry/vue — 参见 docs.sentry.io/platforms/javascript/guides/vue/ |
@angular/core | 建议使用 @sentry/angular — 参见 docs.sentry.io/platforms/javascript/guides/angular/ |
@sveltejs/kit | 加载 sentry-svelte-sdk 技能 — 不要在此继续 |
svelte (SPA,没有 kit) | 建议使用 @sentry/svelte — 参见 docs.sentry.io/platforms/javascript/guides/svelte/ |
@remix-run | 建议使用 @sentry/remix — 参见 docs.sentry.io/platforms/javascript/guides/remix/ |
nuxt | 建议使用 @sentry/nuxt — 参见 docs.sentry.io/platforms/javascript/guides/nuxt/ |
astro | 建议使用 @sentry/astro — 参见 docs.sentry.io/platforms/javascript/guides/astro/ |
ember-source | 建议使用 @sentry/ember — 参见 docs.sentry.io/platforms/javascript/guides/ember/ |
express / fastify / @nestjs/core | 这是一个 Node.js 服务器 — 加载 sentry-node-sdk 或 sentry-nestjs-sdk 技能 |
为什么重定向很重要: 框架 SDK 增加了路由器感知的事务、错误边界、组件追踪,并且通常支持 SSR 覆盖。在 React 或 Next.js 应用中直接使用
@sentry/browser会失去所有这些功能。
只有在未检测到任何框架时才继续使用 @sentry/browser。
# 检查是否存在 package.json(打包器环境)
ls package.json 2>/dev/null
# 检查包管理器
ls package-lock.json yarn.lock pnpm-lock.yaml bun.lockb 2>/dev/null
# 检查构建工具
ls vite.config.ts vite.config.js webpack.config.js rollup.config.js esbuild.config.js 2>/dev/null
cat package.json 2>/dev/null | grep -E '"vite"|"webpack"|"rollup"|"esbuild"'
# 检查 CMS 或静态站点指示器
ls wp-config.php wp-content/ 2>/dev/null # WordPress
ls _config.yml _config.yaml 2>/dev/null # Jekyll
ls config.toml 2>/dev/null # Hugo
ls .eleventy.js 2>/dev/null # Eleventy
# 检查是否已存在 Sentry
cat package.json 2>/dev/null | grep '"@sentry/'
grep -r "sentry-cdn.com\|js.sentry-cdn.com" . --include="*.html" -l 2>/dev/null | head -3
需要确定的内容:
| 问题 | 影响 |
|---|---|
存在 package.json + 打包器? | → 路径 A: npm 安装 |
| WordPress、Shopify、静态 HTML,没有 npm? | → 路径 B: Loader Script |
| 只有脚本标签,无法访问 Loader Script? | → 路径 C: CDN 捆绑包 |
已经安装了 @sentry/browser? | 跳过安装,直接进入功能配置 |
| 构建工具是 Vite / webpack / Rollup / esbuild? | 需要配置源码映射插件 |
根据您的发现提出建议。以一个具体的方案开头,不要问开放式问题。
推荐(核心覆盖):
可选(增强的可观测性):
Sentry.logger.* 进行结构化日志记录;需要 npm 或 CDN 日志捆绑包(Loader Script 不可用)Document-Policy: js-profiling功能推荐逻辑:
| 功能 | 推荐时机... |
|---|---|
| 错误监控 | 始终 — 不可协商的基线 |
| 追踪 | 对于交互式页面始终推荐 — 页面加载 + 导航跨度具有高价值 |
| 会话回放 | 面向用户的应用、支持流程或结账页面 |
| 用户反馈 | 以支持为中心的应用;希望获得带有截图的应用内错误报告 |
| 日志记录 | 需要结构化日志搜索或日志到追踪的关联;仅限 npm 路径 |
| 性能剖析 | 性能关键、仅限 Chromium 的应用;需要 Document-Policy: js-profiling 响应头 |
安装路径推荐:
| 场景 | 推荐路径 |
|---|---|
项目有 package.json + 打包器 | 路径 A (npm) — 完整功能、源码映射、tree-shaking |
| WordPress、Shopify、Squarespace、静态 HTML | 路径 B (Loader Script) — 零构建工具,始终保持最新 |
| 无法访问 Loader Script 的静态 HTML | 路径 C (CDN 捆绑包) — 手动 <script> 标签 |
建议:“我推荐使用路径 A (npm) 设置错误监控 + 追踪 + 会话回放。您希望我也添加日志记录或用户反馈吗?”
npm install @sentry/browser --save
# 或
yarn add @sentry/browser
# 或
pnpm add @sentry/browser
src/instrument.tsSentry 必须在任何其他代码运行之前初始化。将 Sentry.init() 放在一个专用的辅助文件中:
import * as Sentry from "@sentry/browser";
Sentry.init({
dsn: import.meta.env.VITE_SENTRY_DSN, // 根据构建工具调整(见下表)
environment: import.meta.env.MODE,
release: import.meta.env.VITE_APP_VERSION, // 在构建时注入
sendDefaultPii: true,
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: true,
blockAllMedia: true,
}),
],
// 追踪
tracesSampleRate: 1.0, // 在生产环境中降低到 0.1–0.2
tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],
// 会话回放
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
enableLogs: true,
});
按构建工具的 DSN 环境变量:
| 构建工具 | 变量名 | 代码中访问 |
|---|---|---|
| Vite | VITE_SENTRY_DSN | import.meta.env.VITE_SENTRY_DSN |
| 自定义 webpack | SENTRY_DSN | process.env.SENTRY_DSN |
| esbuild | SENTRY_DSN | process.env.SENTRY_DSN |
| Rollup | SENTRY_DSN | process.env.SENTRY_DSN |
将 instrument.ts 作为第一个导入引入您的入口文件:
// src/main.ts 或 src/index.ts
import "./instrument"; // ← 必须是第一个
// ... 应用的其余部分
没有源码映射,堆栈跟踪将显示压缩后的代码。设置构建插件以自动上传源码映射:
没有专门的浏览器向导: 没有
npx @sentry/wizard -i browser标志。最接近的是npx @sentry/wizard@latest -i sourcemaps,它仅为已初始化的 SDK 配置源码映射上传。
Vite (vite.config.ts):
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";
export default defineConfig({
build: { sourcemap: "hidden" },
plugins: [
// sentryVitePlugin 必须是最后一个
sentryVitePlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});
webpack (webpack.config.js):
const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");
module.exports = {
devtool: "hidden-source-map",
plugins: [
sentryWebpackPlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
};
Rollup (rollup.config.js):
import { sentryRollupPlugin } from "@sentry/rollup-plugin";
export default {
output: { sourcemap: "hidden" },
plugins: [
sentryRollupPlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
};
esbuild (build.js):
const { sentryEsbuildPlugin } = require("@sentry/esbuild-plugin");
require("esbuild").build({
entryPoints: ["src/index.ts"],
bundle: true,
sourcemap: "hidden",
plugins: [
sentryEsbuildPlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});
⚠️ esbuild 插件不完全支持
splitting: true。如果启用了代码分割,请改用sentry-cli。
使用 sentry-cli(任何工具链 / CI):
# 在您的构建步骤之后:
npx @sentry/cli sourcemaps inject ./dist
npx @sentry/cli sourcemaps upload ./dist
添加 .env 用于认证(切勿提交):
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slug
最适合: 没有构建系统的站点。Loader Script 是一个单一的 <script> 标签,它延迟加载完整的 SDK,通过 Sentry 的 CDN 始终保持最新,并在 SDK 加载前缓冲错误。
获取 Loader Script: Sentry UI → Settings → Projects → (your project) → SDK Setup → Loader Script
复制生成的标签,并将其作为每个页面的第一个脚本放置:
<!DOCTYPE html>
<html>
<head>
<!-- 在 loader 标签之前配置 -->
<script>
window.sentryOnLoad = function () {
Sentry.init({
// DSN 已在 loader URL 中配置
tracesSampleRate: 1.0,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
};
</script>
<!-- Loader Script 第一 — 在所有其他脚本之前 -->
<script
src="https://js.sentry-cdn.com/YOUR_PUBLIC_KEY.min.js"
crossorigin="anonymous"
></script>
</head>
...
</html>
Loader 加载模式:
| 模式 | 如何操作 | SDK 何时加载 |
|---|---|---|
| 延迟(默认) | 无需额外操作 | 在第一个错误或手动调用 Sentry 时 |
| 立即 | 在 <script> 中添加 data-lazy="no" | 所有页面脚本完成后 |
| 手动 | 调用 Sentry.forceLoad() | 当您调用它时 |
在 SDK 加载前调用是安全的(会被缓冲):
Sentry.captureException()Sentry.captureMessage()Sentry.captureEvent()Sentry.addBreadcrumb()Sentry.withScope()对于其他方法,使用 Sentry.onLoad():
<script>
window.Sentry && Sentry.onLoad(function () {
Sentry.setUser({ id: "123" });
});
</script>
通过全局变量设置发布版本(可选):
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>
Loader Script 限制:
Sentry.logger.*(日志记录)— 仅限 npm 路径defer(而不是 async)CSP 要求:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.io
最适合: 无法使用 Loader Script 但需要同步加载的页面。
选择符合您功能需求的捆绑包,并将其放在所有其他脚本之前:
仅错误(最小体积):
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.min.js"
integrity="sha384-L/HYBH2QCeLyXhcZ0hPTxWMnyMJburPJyVoBmRk4OoilqrOWq5kU4PNTLFYrCYPr"
crossorigin="anonymous"
></script>
错误 + 追踪:
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.min.js"
integrity="sha384-DIqcfVcfIewrWiNWfVZcGWExO5v673hkkC5ixJnmAprAfJajpUDEAL35QgkOB5gw"
crossorigin="anonymous"
></script>
错误 + 会话回放:
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.replay.min.js"
integrity="sha384-sbojwIJFpv9duIzsI9FRm87g7pB15s4QwJS1m1xMSOdV1CF3pwgrPPEu38Em7M9+"
crossorigin="anonymous"
></script>
错误 + 追踪 + 回放(推荐完整设置):
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.min.js"
integrity="sha384-oo2U4zsTxaHSPXJEnXtaQPeS4Z/qbTqoBL9xFgGxvjJHKQjIrB+VRlu97/iXBtzw"
crossorigin="anonymous"
></script>
错误 + 追踪 + 回放 + 用户反馈:
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.feedback.min.js"
integrity="sha384-SmHU39Qs9cua0KLtq3A6gis1/cqM1nZ6fnGzlvWAPiwhBDO5SmwFQV65BBpJnB3n"
crossorigin="anonymous"
></script>
完整捆绑包(所有功能):
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.feedback.logs.metrics.min.js"
integrity="sha384-gOjSzRxwpXpy0FlT6lg/AVhagqrsUrOWUO7jm6TJwuZ9YVHtYK0MBA2hW2FGrIGl"
crossorigin="anonymous"
></script>
CDN 捆绑包变体摘要:
| 捆绑包 | 功能 | 何时使用 |
|---|---|---|
bundle.min.js | 仅错误 | 绝对最小体积 |
bundle.tracing.min.js | + 追踪 | 性能监控 |
bundle.replay.min.js | + 回放 | 会话录制 |
bundle.tracing.replay.min.js | + 追踪 + 回放 | 完整可观测性 |
bundle.tracing.replay.feedback.min.js | + 用户反馈 | + 应用内反馈组件 |
bundle.logs.metrics.min.js | + 日志 + 指标 | 结构化日志(CDN) |
bundle.tracing.replay.feedback.logs.metrics.min.js | 所有功能 | 最大覆盖 |
在脚本标签后初始化:
<script>
Sentry.init({
dsn: "https://YOUR_KEY@o0.ingest.sentry.io/YOUR_PROJECT",
environment: "production",
release: "my-app@1.0.0",
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: true,
blockAllMedia: true,
}),
],
tracesSampleRate: 1.0,
tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
</script>
CDN CSP 要求:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.io
逐个功能进行指导。加载参考文件,按照其步骤操作,在继续之前进行验证:
| 功能 | 参考 | 何时加载 |
|---|---|---|
| 错误监控 | ${SKILL_ROOT}/references/error-monitoring.md | 始终(基线) |
| 追踪 | ${SKILL_ROOT}/references/tracing.md | 页面加载 / API 调用追踪 |
| 会话回放 | ${SKILL_ROOT}/references/session-replay.md | 面向用户的应用 |
| 日志记录 | ${SKILL_ROOT}/references/logging.md | 结构化日志搜索;npm 或 CDN 日志捆绑包(非 Loader Script) |
| 性能剖析 | ${SKILL_ROOT}/references/profiling.md | 性能关键、仅限 Chromium |
| 用户反馈 | ${SKILL_ROOT}/references/user-feedback.md | 在错误后捕获用户报告 |
对于每个功能:Read ${SKILL_ROOT}/references/<feature>.md,严格按照步骤操作,验证其是否工作。
Sentry.init() 选项| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
dsn | string | — | 必需。 为空时 SDK 被禁用 |
environment | string | "production" | 例如:"staging"、"development" |
release | string | — | 例如:"my-app@1.0.0" 或 git SHA — 将错误链接到发布版本 |
sendDefaultPii | boolean | false | 包含 IP 地址和请求头 |
tracesSampleRate | number | — | 0–1;开发环境用 1.0,生产环境用 0.1–0.2 |
tracesSampler | function | — | 按事务采样;覆盖采样率 |
tracePropagationTargets | `(string | RegExp)[]` | same-origin |
replaysSessionSampleRate | number | — | 记录所有会话的比例 |
replaysOnErrorSampleRate | number | — | 记录错误会话的比例 |
enableLogs | boolean | false | 启用 Sentry.logger.* API(npm 或 CDN 日志捆绑包;Loader Script 不可用) |
attachStackTrace | boolean | false | 在 captureMessage() 调用时附加堆栈跟踪 |
maxBreadcrumbs | number | 100 | 每个事件存储的面包屑数量 |
debug | boolean | false | 将 SDK 详细输出到控制台 |
tunnel | string | — | 代理 URL 以绕过广告拦截器 |
ignoreErrors | `(string | RegExp)[]` | [] |
denyUrls | `(string | RegExp)[]` | [] |
allowUrls | `(string | RegExp)[]` | [] |
spotlight | `boolean | string` | false |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
cdnBaseUrl | string | — | 用于延迟加载集成的基础 URL |
skipBrowserExtensionCheck | boolean | false | 跳过浏览器扩展上下文检查 |
window.SENTRY_RELEASE 全局变量(CDN / Loader 路径)在 SDK 加载前设置发布版本:
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>
触发测试事件以确认 Sentry 正在接收数据:
npm / CDN 路径:
<!-- 临时添加到您的页面 -->
<button onclick="throw new Error('Sentry Browser Test Error')">
测试错误
</button>
性能验证(npm 路径):
import * as Sentry from "@sentry/browser";
Sentry.startSpan({ name: "测试跨度", op: "test" }, () => {
// 您的操作
});
手动捕获:
Sentry.captureException(new Error("手动测试"));
Sentry.captureMessage("手动测试消息", "info");
检查 Sentry 仪表板:
如果没有任何显示,请在 Sentry.init() 中设置 debug: true 并检查浏览器控制台。
完成浏览器设置后,检查是否存在缺少 Sentry 覆盖的配套后端:
ls ../backend ../server ../api ../go ../python 2>/dev/null
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3
cat ../pom.xml 2>/dev/null | grep '<artifactId>' | head -3
cat ../composer.json 2>/dev/null | head -3
如果存在未配置 Sentry 的后端,建议使用匹配的技能:
| 检测到的后端 | 建议技能 |
|---|---|
Go (go.mod) | sentry-go-sdk |
Python (requirements.txt, pyproject.toml) | sentry-python-sdk |
Ruby (Gemfile) | sentry-ruby-sdk |
PHP (composer.json) | sentry-php-sdk |
.NET (*.csproj, *.sln) | sentry-dotnet-sdk |
Java (pom.xml, build.gradle) | 参见 docs.sentry.io/platforms/java/ |
| Node.js (Express, Fastify) | sentry-node-sdk |
NestJS (@nestjs/core) | sentry-nestjs-sdk |
| 问题 | 解决方案 |
|---|---|
| 事件未出现 | 设置 debug: true,检查 DSN,打开浏览器控制台查看 SDK 错误 |
| 源码映射不工作 | 在生产模式下构建 (npm run build);验证 SENTRY_AUTH_TOKEN 是否已设置 |
| 压缩的堆栈跟踪 | 源码映射未上传 — 检查构建插件配置;运行 npx @sentry/wizard@latest -i sourcemaps |
| CDN 捆绑包未找到 | 检查 URL 中的版本号;查看 browser.sentry-cdn.com 获取最新版本 |
| SRI 完整性错误 | 哈希不匹配 — 从此技能中重新复制完整的 <script> 标签,包括 integrity 属性 |
| Loader Script 未触发 | 验证它是页面上的第一个 <script>;检查控制台中的 CSP 错误 |
| Loader 的追踪不工作 | SDK 加载前的 fetch 调用不会被追踪 — 将早期调用包装在 Sentry.onLoad() 中 |
sentryOnLoad 未被调用 | 必须在 loader <script> 标签之前定义 window.sentryOnLoad |
| 日志记录不可用 | Sentry.logger.* 需要 npm 或名称中包含 .logs. 的 CDN 捆绑包 — Loader Script 不支持 |
| 性能剖析不工作 | 验证文档响应上是否有 Document-Policy: js-profiling 响应头;仅限 Chromium |
| 广告拦截器丢弃事件 | 设置 tunnel: "/sentry-tunnel" 并添加服务器端中继端点 |
| 会话回放未录制 | 确认 replayIntegration() 在 init 中;检查 replaysSessionSampleRate > 0 |
| 回放 CSP 错误 | 在您的 CSP 中添加 worker-src 'self' blob: 和 child-src 'self' blob: |
tracePropagationTargets 不匹配 | 检查正则表达式转义;默认仅限同源 |
| 浏览器扩展阻止事件 | 添加 denyUrls: [/chrome-extension:\/\//] 以过滤扩展错误 |
| 事件量过高 | 在生产环境中降低 sampleRate(错误)和 tracesSampleRate 从 1.0 |
| 源码映射在部署后上传 | 源码映射必须在错误发生之前上传 — 集成到 CI/CD 中 |
| esbuild 分割冲突 | sentryEsbuildPlugin 不支持 splitting: true — 改用 sentry-cli |
每周安装次数
258
仓库
GitHub 星标数
82
首次出现
2026年3月4日
安全审计
安装在
codex256
gemini-cli252
github-copilot252
cursor252
opencode252
kimi-cli251
All Skills > SDK Setup > Browser SDK
Opinionated wizard that scans your project and guides you through complete Sentry setup for browser JavaScript — vanilla JS, jQuery, static sites, WordPress, and any JS project without a framework-specific SDK.
@sentry/browser or configure the Loader ScriptNote: SDK versions and APIs below reflect
@sentry/browser≥10.0.0. Always verify against docs.sentry.io/platforms/javascript/ before implementing.
CRITICAL — Check for frameworks first. Framework-specific SDKs provide significantly better coverage and must be recommended before proceeding with @sentry/browser.
# Check for React
cat package.json 2>/dev/null | grep -E '"react"'
# Check for Next.js
cat package.json 2>/dev/null | grep '"next"'
# Check for Vue
cat package.json 2>/dev/null | grep '"vue"'
# Check for Angular
cat package.json 2>/dev/null | grep '"@angular/core"'
# Check for Svelte / SvelteKit
cat package.json 2>/dev/null | grep -E '"svelte"|"@sveltejs/kit"'
# Check for Remix
cat package.json 2>/dev/null | grep -E '"@remix-run/react"|"@remix-run/node"'
# Check for Nuxt
cat package.json 2>/dev/null | grep '"nuxt"'
# Check for Astro
cat package.json 2>/dev/null | grep '"astro"'
# Check for Ember
cat package.json 2>/dev/null | grep '"ember-source"'
# Check for Node.js server frameworks (wrong SDK entirely)
cat package.json 2>/dev/null | grep -E '"express"|"fastify"|"@nestjs/core"|"koa"'
If a framework is detected, stop and redirect:
| Framework detected | Redirect to |
|---|---|
next | Load sentry-nextjs-sdk skill — do not proceed here |
react (without Next.js) | Load sentry-react-sdk skill — do not proceed here |
vue | Suggest @sentry/vue — see docs.sentry.io/platforms/javascript/guides/vue/ |
@angular/core |
Why redirect matters: Framework SDKs add router-aware transactions, error boundaries, component tracking, and often SSR coverage. Using
@sentry/browserdirectly in a React or Next.js app loses all of that.
Only continue with @sentry/browser if no framework is detected.
# Check if there's a package.json at all (bundler environment)
ls package.json 2>/dev/null
# Check package manager
ls package-lock.json yarn.lock pnpm-lock.yaml bun.lockb 2>/dev/null
# Check build tool
ls vite.config.ts vite.config.js webpack.config.js rollup.config.js esbuild.config.js 2>/dev/null
cat package.json 2>/dev/null | grep -E '"vite"|"webpack"|"rollup"|"esbuild"'
# Check for CMS or static site indicators
ls wp-config.php wp-content/ 2>/dev/null # WordPress
ls _config.yml _config.yaml 2>/dev/null # Jekyll
ls config.toml 2>/dev/null # Hugo
ls .eleventy.js 2>/dev/null # Eleventy
# Check for existing Sentry
cat package.json 2>/dev/null | grep '"@sentry/'
grep -r "sentry-cdn.com\|js.sentry-cdn.com" . --include="*.html" -l 2>/dev/null | head -3
What to determine:
| Question | Impact |
|---|---|
package.json exists + bundler? | → Path A: npm install |
| WordPress, Shopify, static HTML, no npm? | → Path B: Loader Script |
| Script tags only, no Loader Script access? | → Path C: CDN bundle |
Already has @sentry/browser? | Skip install, go straight to feature config |
| Build tool is Vite / webpack / Rollup / esbuild? | Source maps plugin to configure |
Present a recommendation based on what you found. Lead with a concrete proposal, don't ask open-ended questions.
Recommended (core coverage):
Optional (enhanced observability):
Sentry.logger.*; requires npm or CDN logs bundle (not available via Loader Script)Document-Policy: js-profiling response headerFeature recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always for interactive pages — page load + navigation spans are high-value |
| Session Replay | User-facing app, support flows, or checkout pages |
| User Feedback | Support-focused app; want in-app bug reports with screenshots |
| Logging | Structured log search or log-to-trace correlation needed; npm path only |
| Profiling | Performance-critical, Chromium-only app; Document-Policy: js-profiling header required |
Installation path recommendation:
| Scenario | Recommended path |
|---|---|
Project has package.json + bundler | Path A (npm) — full features, source maps, tree-shaking |
| WordPress, Shopify, Squarespace, static HTML | Path B (Loader Script) — zero build tooling, always up to date |
| Static HTML without Loader Script access | Path C (CDN bundle) — manual <script> tag |
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay using Path A (npm). Want me to also add Logging or User Feedback?"
npm install @sentry/browser --save
# or
yarn add @sentry/browser
# or
pnpm add @sentry/browser
src/instrument.tsSentry must initialize before any other code runs. Put Sentry.init() in a dedicated sidecar file:
import * as Sentry from "@sentry/browser";
Sentry.init({
dsn: import.meta.env.VITE_SENTRY_DSN, // Adjust per build tool (see table below)
environment: import.meta.env.MODE,
release: import.meta.env.VITE_APP_VERSION, // inject at build time
sendDefaultPii: true,
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: true,
blockAllMedia: true,
}),
],
// Tracing
tracesSampleRate: 1.0, // lower to 0.1–0.2 in production
tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],
// Session Replay
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
enableLogs: true,
});
DSN environment variable by build tool:
| Build Tool | Variable Name | Access in code |
|---|---|---|
| Vite | VITE_SENTRY_DSN | import.meta.env.VITE_SENTRY_DSN |
| Custom webpack | SENTRY_DSN | process.env.SENTRY_DSN |
| esbuild | SENTRY_DSN | process.env.SENTRY_DSN |
| Rollup |
Import instrument.ts as the very first import in your entry file:
// src/main.ts or src/index.ts
import "./instrument"; // ← MUST be first
// ... rest of your app
Without source maps, stack traces show minified code. Set up the build plugin to upload source maps automatically:
No dedicated browser wizard: There is no
npx @sentry/wizard -i browserflag. The closest isnpx @sentry/wizard@latest -i sourcemapswhich configures source map upload only for an already-initialized SDK.
Vite (vite.config.ts):
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";
export default defineConfig({
build: { sourcemap: "hidden" },
plugins: [
// sentryVitePlugin MUST be last
sentryVitePlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});
webpack (webpack.config.js):
const { sentryWebpackPlugin } = require("@sentry/webpack-plugin");
module.exports = {
devtool: "hidden-source-map",
plugins: [
sentryWebpackPlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
};
Rollup (rollup.config.js):
import { sentryRollupPlugin } from "@sentry/rollup-plugin";
export default {
output: { sourcemap: "hidden" },
plugins: [
sentryRollupPlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
};
esbuild (build.js):
const { sentryEsbuildPlugin } = require("@sentry/esbuild-plugin");
require("esbuild").build({
entryPoints: ["src/index.ts"],
bundle: true,
sourcemap: "hidden",
plugins: [
sentryEsbuildPlugin({
org: process.env.SENTRY_ORG,
project: process.env.SENTRY_PROJECT,
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
});
⚠️ esbuild plugin does not fully support
splitting: true. Usesentry-cliinstead if code splitting is enabled.
Usingsentry-cli (any toolchain / CI):
# After your build step:
npx @sentry/cli sourcemaps inject ./dist
npx @sentry/cli sourcemaps upload ./dist
Add .env for auth (never commit):
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slug
Best for: Sites without a build system. The Loader Script is a single <script> tag that lazily loads the full SDK, always stays up to date via Sentry's CDN, and buffers errors before the SDK loads.
Get the Loader Script: Sentry UI → Settings → Projects → (your project) → SDK Setup → Loader Script
Copy the generated tag and place it as the first script on every page :
<!DOCTYPE html>
<html>
<head>
<!-- Configure BEFORE the loader tag -->
<script>
window.sentryOnLoad = function () {
Sentry.init({
// DSN is already configured in the loader URL
tracesSampleRate: 1.0,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
};
</script>
<!-- Loader Script FIRST — before all other scripts -->
<script
src="https://js.sentry-cdn.com/YOUR_PUBLIC_KEY.min.js"
crossorigin="anonymous"
></script>
</head>
...
</html>
Loader loading modes:
| Mode | How | When SDK loads |
|---|---|---|
| Lazy (default) | Nothing extra | On first error or manual Sentry call |
| Eager | Add data-lazy="no" to <script> | After all page scripts finish |
| Manual | Call Sentry.forceLoad() | Whenever you call it |
Safe to call before SDK loads (buffered):
Sentry.captureException()Sentry.captureMessage()Sentry.captureEvent()Sentry.addBreadcrumb()Sentry.withScope()For other methods, useSentry.onLoad():
<script>
window.Sentry && Sentry.onLoad(function () {
Sentry.setUser({ id: "123" });
});
</script>
Set release via global (optional):
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>
Loader Script limitations:
Sentry.logger.* (logging) — npm path onlydefer (not async) on all other scripts when using the loaderCSP requirements:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.io
Best for: Pages that can't use the Loader Script but need synchronous loading.
Pick the bundle that matches your feature needs and place it before all other scripts :
Errors only (minimal footprint):
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.min.js"
integrity="sha384-L/HYBH2QCeLyXhcZ0hPTxWMnyMJburPJyVoBmRk4OoilqrOWq5kU4PNTLFYrCYPr"
crossorigin="anonymous"
></script>
Errors + Tracing:
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.min.js"
integrity="sha384-DIqcfVcfIewrWiNWfVZcGWExO5v673hkkC5ixJnmAprAfJajpUDEAL35QgkOB5gw"
crossorigin="anonymous"
></script>
Errors + Session Replay:
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.replay.min.js"
integrity="sha384-sbojwIJFpv9duIzsI9FRm87g7pB15s4QwJS1m1xMSOdV1CF3pwgrPPEu38Em7M9+"
crossorigin="anonymous"
></script>
Errors + Tracing + Replay (recommended full setup):
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.min.js"
integrity="sha384-oo2U4zsTxaHSPXJEnXtaQPeS4Z/qbTqoBL9xFgGxvjJHKQjIrB+VRlu97/iXBtzw"
crossorigin="anonymous"
></script>
Errors + Tracing + Replay + User Feedback:
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.feedback.min.js"
integrity="sha384-SmHU39Qs9cua0KLtq3A6gis1/cqM1nZ6fnGzlvWAPiwhBDO5SmwFQV65BBpJnB3n"
crossorigin="anonymous"
></script>
Full bundle (all features):
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.feedback.logs.metrics.min.js"
integrity="sha384-gOjSzRxwpXpy0FlT6lg/AVhagqrsUrOWUO7jm6TJwuZ9YVHtYK0MBA2hW2FGrIGl"
crossorigin="anonymous"
></script>
CDN bundle variants summary:
| Bundle | Features | When to use |
|---|---|---|
bundle.min.js | Errors only | Absolute minimum footprint |
bundle.tracing.min.js | + Tracing | Performance monitoring |
bundle.replay.min.js | + Replay | Session recording |
bundle.tracing.replay.min.js | + Tracing + Replay | Full observability |
bundle.tracing.replay.feedback.min.js |
Initialize after the script tag:
<script>
Sentry.init({
dsn: "https://YOUR_KEY@o0.ingest.sentry.io/YOUR_PROJECT",
environment: "production",
release: "my-app@1.0.0",
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration({
maskAllText: true,
blockAllMedia: true,
}),
],
tracesSampleRate: 1.0,
tracePropagationTargets: ["localhost", /^https:\/\/yourapi\.io/],
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
});
</script>
CDN CSP requirements:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.io
Walk through features one at a time. Load the reference file, follow its steps, verify before moving on:
| Feature | Reference | Load when... |
|---|---|---|
| Error Monitoring | ${SKILL_ROOT}/references/error-monitoring.md | Always (baseline) |
| Tracing | ${SKILL_ROOT}/references/tracing.md | Page load / API call tracing |
| Session Replay | ${SKILL_ROOT}/references/session-replay.md | User-facing app |
| Logging | ${SKILL_ROOT}/references/logging.md | Structured log search; npm or CDN logs bundle (not Loader Script) |
| Profiling | ${SKILL_ROOT}/references/profiling.md |
For each feature: Read ${SKILL_ROOT}/references/<feature>.md, follow steps exactly, verify it works.
Sentry.init() Options| Option | Type | Default | Notes |
|---|---|---|---|
dsn | string | — | Required. SDK disabled when empty |
environment | string | "production" | e.g., "staging", "development" |
| Option | Type | Default | Notes |
|---|---|---|---|
cdnBaseUrl | string | — | Base URL for lazy-loading integrations |
skipBrowserExtensionCheck | boolean | false | Skip check for browser extension context |
window.SENTRY_RELEASE Global (CDN / Loader Path)Set the release version before the SDK loads:
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>
Trigger test events to confirm Sentry is receiving data:
npm / CDN path:
<!-- Add temporarily to your page -->
<button onclick="throw new Error('Sentry Browser Test Error')">
Test Error
</button>
Performance verification (npm path):
import * as Sentry from "@sentry/browser";
Sentry.startSpan({ name: "Test Span", op: "test" }, () => {
// your operation
});
Manual capture:
Sentry.captureException(new Error("Manual test"));
Sentry.captureMessage("Manual test message", "info");
Check the Sentry dashboard:
Set debug: true in Sentry.init() and check the browser console if nothing appears.
After completing browser setup, check for a companion backend missing Sentry coverage:
ls ../backend ../server ../api ../go ../python 2>/dev/null
cat ../go.mod 2>/dev/null | head -3
cat ../requirements.txt ../pyproject.toml 2>/dev/null | head -3
cat ../Gemfile 2>/dev/null | head -3
cat ../pom.xml 2>/dev/null | grep '<artifactId>' | head -3
cat ../composer.json 2>/dev/null | head -3
If a backend exists without Sentry configured, suggest the matching skill:
| Backend detected | Suggest skill |
|---|---|
Go (go.mod) | sentry-go-sdk |
Python (requirements.txt, pyproject.toml) | sentry-python-sdk |
Ruby (Gemfile) | sentry-ruby-sdk |
PHP (composer.json) |
| Issue | Solution |
|---|---|
| Events not appearing | Set debug: true, check DSN, open browser console for SDK errors |
| Source maps not working | Build in production mode (npm run build); verify SENTRY_AUTH_TOKEN is set |
| Minified stack traces | Source maps not uploading — check build plugin config; run npx @sentry/wizard@latest -i sourcemaps |
| CDN bundle not found | Check version number in URL; see browser.sentry-cdn.com for latest |
| SRI integrity error | Hash mismatch — re-copy the full <script> tag including attribute from this skill |
Weekly Installs
258
Repository
GitHub Stars
82
First Seen
Mar 4, 2026
Security Audits
Gen Agent Trust HubPassSocketWarnSnykWarn
Installed on
codex256
gemini-cli252
github-copilot252
cursor252
opencode252
kimi-cli251
Next.js 16+ 缓存组件指南:实现部分预渲染(PPR)与混合内容缓存
13,400 周安装
Suggest @sentry/angular — see docs.sentry.io/platforms/javascript/guides/angular/ |
@sveltejs/kit | Load sentry-svelte-sdk skill — do not proceed here |
svelte (SPA, no kit) | Suggest @sentry/svelte — see docs.sentry.io/platforms/javascript/guides/svelte/ |
@remix-run | Suggest @sentry/remix — see docs.sentry.io/platforms/javascript/guides/remix/ |
nuxt | Suggest @sentry/nuxt — see docs.sentry.io/platforms/javascript/guides/nuxt/ |
astro | Suggest @sentry/astro — see docs.sentry.io/platforms/javascript/guides/astro/ |
ember-source | Suggest @sentry/ember — see docs.sentry.io/platforms/javascript/guides/ember/ |
express / fastify / @nestjs/core | This is a Node.js server — load sentry-node-sdk or sentry-nestjs-sdk skill |
SENTRY_DSNprocess.env.SENTRY_DSN |
| + User Feedback |
| + in-app feedback widget |
bundle.logs.metrics.min.js | + Logs + Metrics | Structured logs (CDN) |
bundle.tracing.replay.feedback.logs.metrics.min.js | Everything | Max coverage |
| Performance-critical, Chromium-only |
| User Feedback | ${SKILL_ROOT}/references/user-feedback.md | Capture user reports after errors |
release | string | — | e.g., "my-app@1.0.0" or git SHA — links errors to releases |
sendDefaultPii | boolean | false | Includes IP addresses and request headers |
tracesSampleRate | number | — | 0–1; 1.0 in dev, 0.1–0.2 in prod |
tracesSampler | function | — | Per-transaction sampling; overrides rate |
tracePropagationTargets | `(string | RegExp)[]` | same-origin |
replaysSessionSampleRate | number | — | Fraction of all sessions recorded |
replaysOnErrorSampleRate | number | — | Fraction of error sessions recorded |
enableLogs | boolean | false | Enable Sentry.logger.* API (npm or CDN logs bundle; not Loader Script) |
attachStackTrace | boolean | false | Stack traces on captureMessage() calls |
maxBreadcrumbs | number | 100 | Breadcrumbs stored per event |
debug | boolean | false | Verbose SDK output to console |
tunnel | string | — | Proxy URL to bypass ad blockers |
ignoreErrors | `(string | RegExp)[]` | [] |
denyUrls | `(string | RegExp)[]` | [] |
allowUrls | `(string | RegExp)[]` | [] |
spotlight | `boolean | string` | false |
sentry-php-sdk |
.NET (*.csproj, *.sln) | sentry-dotnet-sdk |
Java (pom.xml, build.gradle) | See docs.sentry.io/platforms/java/ |
| Node.js (Express, Fastify) | sentry-node-sdk |
NestJS (@nestjs/core) | sentry-nestjs-sdk |
integrity| Loader Script not firing | Verify it's the first <script> on the page; check for CSP errors in console |
| Tracing not working with Loader | Fetch calls before SDK loads won't be traced — wrap early calls in Sentry.onLoad() |
sentryOnLoad not called | Must define window.sentryOnLoad before the loader <script> tag |
| Logging not available | Sentry.logger.* requires npm or a CDN bundle with .logs. in its name — not supported via Loader Script |
| Profiling not working | Verify Document-Policy: js-profiling header on document responses; Chromium-only |
| Ad blockers dropping events | Set tunnel: "/sentry-tunnel" and add a server-side relay endpoint |
| Session replay not recording | Confirm replayIntegration() is in init; check replaysSessionSampleRate > 0 |
| Replay CSP errors | Add worker-src 'self' blob: and child-src 'self' blob: to your CSP |
tracePropagationTargets not matching | Check regex escaping; default is same-origin only |
| Events blocked by browser extension | Add denyUrls: [/chrome-extension:\/\//] to filter extension errors |
| High event volume | Lower sampleRate (errors) and tracesSampleRate from 1.0 in production |
| Source maps uploaded after deploy | Source maps must be uploaded before errors occur — integrate into CI/CD |
| esbuild splitting conflict | sentryEsbuildPlugin doesn't support splitting: true — use sentry-cli instead |