sentry-browser-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAll Skills > SDK Setup > Browser SDK
所有技能 > SDK设置 > Browser SDK
Sentry Browser SDK
Sentry 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.
这是一个指导性的向导工具,会扫描你的项目并引导你完成浏览器JavaScript项目的完整Sentry设置——包括原生JS、jQuery、静态站点、WordPress,以及任何没有对应框架专属SDK的JS项目。
Invoke This Skill When
何时调用本指南
- User asks to "add Sentry to a website" or set up Sentry for plain JavaScript
- User wants to install or configure the Loader Script
@sentry/browser - User has a WordPress, Shopify, Squarespace, or static HTML site
- User wants error monitoring, tracing, session replay, or logging without a framework
- No framework-specific SDK applies
Note: SDK versions and APIs below reflect≥10.0.0. Always verify against docs.sentry.io/platforms/javascript/ before implementing.@sentry/browser
- 用户要求「给网站添加Sentry」或为原生JavaScript设置Sentry
- 用户想要安装或配置Loader Script
@sentry/browser - 用户拥有WordPress、Shopify、Squarespace或静态HTML站点
- 用户希望在不依赖框架的情况下实现错误监控、链路追踪、会话重放或日志功能
- 没有适用的框架专属SDK
注意: 以下SDK版本和API对应≥10.0.0。 实施前请务必对照docs.sentry.io/platforms/javascript/进行验证。@sentry/browser
Phase 1: Detect
阶段1:检测
CRITICAL — Check for frameworks first. Framework-specific SDKs provide significantly better coverage and must be recommended before proceeding with .
@sentry/browser关键步骤——先检查框架。 框架专属SDK提供更全面的覆盖范围,在继续使用之前,必须优先推荐框架专属SDK。
@sentry/browserStep 1A: Framework Detection (Redirect If Found)
步骤1A:框架检测(若检测到则跳转)
bash
undefinedbash
undefinedCheck for React
检查是否使用React
cat package.json 2>/dev/null | grep -E '"react"'
cat package.json 2>/dev/null | grep -E '"react"'
Check for Next.js
检查是否使用Next.js
cat package.json 2>/dev/null | grep '"next"'
cat package.json 2>/dev/null | grep '"next"'
Check for Vue
检查是否使用Vue
cat package.json 2>/dev/null | grep '"vue"'
cat package.json 2>/dev/null | grep '"vue"'
Check for Angular
检查是否使用Angular
cat package.json 2>/dev/null | grep '"@angular/core"'
cat package.json 2>/dev/null | grep '"@angular/core"'
Check for Svelte / SvelteKit
检查是否使用Svelte / SvelteKit
cat package.json 2>/dev/null | grep -E '"svelte"|"@sveltejs/kit"'
cat package.json 2>/dev/null | grep -E '"svelte"|"@sveltejs/kit"'
Check for Remix
检查是否使用Remix
cat package.json 2>/dev/null | grep -E '"@remix-run/react"|"@remix-run/node"'
cat package.json 2>/dev/null | grep -E '"@remix-run/react"|"@remix-run/node"'
Check for Nuxt
检查是否使用Nuxt
cat package.json 2>/dev/null | grep '"nuxt"'
cat package.json 2>/dev/null | grep '"nuxt"'
Check for Astro
检查是否使用Astro
cat package.json 2>/dev/null | grep '"astro"'
cat package.json 2>/dev/null | grep '"astro"'
Check for Ember
检查是否使用Ember
cat package.json 2>/dev/null | grep '"ember-source"'
cat package.json 2>/dev/null | grep '"ember-source"'
Check for Node.js server frameworks (wrong SDK entirely)
检查是否使用Node.js服务端框架(需使用其他SDK)
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/](https://docs.sentry.io/platforms/javascript/guides/vue/) |
| `@angular/core` | Suggest `@sentry/angular` — see [docs.sentry.io/platforms/javascript/guides/angular/](https://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/](https://docs.sentry.io/platforms/javascript/guides/svelte/) |
| `@remix-run` | Suggest `@sentry/remix` — see [docs.sentry.io/platforms/javascript/guides/remix/](https://docs.sentry.io/platforms/javascript/guides/remix/) |
| `nuxt` | Suggest `@sentry/nuxt` — see [docs.sentry.io/platforms/javascript/guides/nuxt/](https://docs.sentry.io/platforms/javascript/guides/nuxt/) |
| `astro` | Suggest `@sentry/astro` — see [docs.sentry.io/platforms/javascript/guides/astro/](https://docs.sentry.io/platforms/javascript/guides/astro/) |
| `ember-source` | Suggest `@sentry/ember` — see [docs.sentry.io/platforms/javascript/guides/ember/](https://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 |
> **Why redirect matters:** Framework SDKs add router-aware transactions, error boundaries, component tracking, and often SSR coverage. Using `@sentry/browser` directly in a React or Next.js app loses all of that.
Only continue with `@sentry/browser` if **no framework is detected**.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/](https://docs.sentry.io/platforms/javascript/guides/vue/) |
| `@angular/core` | 推荐使用`@sentry/angular`——查看[docs.sentry.io/platforms/javascript/guides/angular/](https://docs.sentry.io/platforms/javascript/guides/angular/) |
| `@sveltejs/kit` | 加载`sentry-svelte-sdk`指南——**请勿继续当前流程** |
| `svelte`(单页应用,未使用Kit) | 推荐使用`@sentry/svelte`——查看[docs.sentry.io/platforms/javascript/guides/svelte/](https://docs.sentry.io/platforms/javascript/guides/svelte/) |
| `@remix-run` | 推荐使用`@sentry/remix`——查看[docs.sentry.io/platforms/javascript/guides/remix/](https://docs.sentry.io/platforms/javascript/guides/remix/) |
| `nuxt` | 推荐使用`@sentry/nuxt`——查看[docs.sentry.io/platforms/javascript/guides/nuxt/](https://docs.sentry.io/platforms/javascript/guides/nuxt/) |
| `astro` | 推荐使用`@sentry/astro`——查看[docs.sentry.io/platforms/javascript/guides/astro/](https://docs.sentry.io/platforms/javascript/guides/astro/) |
| `ember-source` | 推荐使用`@sentry/ember`——查看[docs.sentry.io/platforms/javascript/guides/ember/](https://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`。Step 1B: Installation Method Detection
步骤1B:安装方式检测
bash
undefinedbash
undefinedCheck if there's a package.json at all (bundler environment)
检查是否存在package.json(即是否使用打包工具环境)
ls package.json 2>/dev/null
ls package.json 2>/dev/null
Check package manager
检查包管理器
ls package-lock.json yarn.lock pnpm-lock.yaml bun.lockb 2>/dev/null
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"'
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
检查是否为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
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
检查是否已存在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 |
---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? | 需要配置source maps插件 |
---Phase 2: Recommend
阶段2:推荐方案
Present a recommendation based on what you found. Lead with a concrete proposal, don't ask open-ended questions.
Recommended (core coverage):
- ✅ Error Monitoring — always; captures unhandled errors and promise rejections
- ✅ Tracing — recommended for any interactive site; tracks page load and user interactions
- ✅ Session Replay — recommended for user-facing apps; records sessions around errors
Optional (enhanced observability):
- ⚡ User Feedback — capture reports directly from users after errors
- ⚡ Logging — structured logs via ; requires npm or CDN logs bundle (not available via Loader Script)
Sentry.logger.* - ⚡ Profiling — JS Self-Profiling API; beta, Chromium-only, requires response header
Document-Policy: js-profiling
Feature 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; |
Installation path recommendation:
| Scenario | Recommended path |
|---|---|
Project has | 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 |
Propose: "I recommend setting up Error Monitoring + Tracing + Session Replay using Path A (npm). Want me to also add Logging or User Feedback?"
根据检测结果给出推荐方案。直接给出具体建议,不要提出开放式问题。
推荐核心功能(基础覆盖):
- ✅ 错误监控——必选;捕获未处理错误和Promise拒绝
- ✅ 链路追踪——所有交互式站点推荐使用;追踪页面加载和用户交互
- ✅ 会话重放——面向用户的应用推荐使用;记录错误发生前后的会话内容
可选功能(增强可观测性):
- ⚡ 用户反馈——错误发生后直接从用户端收集反馈报告
- ⚡ 日志功能——通过实现结构化日志;仅支持npm或CDN日志包(Loader Script不支持)
Sentry.logger.* - ⚡ 性能分析——基于JS Self-Profiling API;处于Beta阶段,仅支持Chromium浏览器,需要配置响应头
Document-Policy: js-profiling
功能推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终推荐——不可缺少的基础功能 |
| 链路追踪 | 所有交互式页面均推荐——页面加载和导航链路的价值很高 |
| 会话重放 | 面向用户的应用、支持流程或结账页面 |
| 用户反馈 | 以支持为核心的应用;希望在应用内收集带截图的Bug报告 |
| 日志功能 | 需要结构化日志搜索或日志-链路关联;仅支持npm路径 |
| 性能分析 | 性能敏感型、仅支持Chromium的应用;需配置 |
安装路径推荐:
| 场景 | 推荐路径 |
|---|---|
| 项目存在package.json且使用打包工具 | 路径A(npm)——功能完整,支持source maps和tree-shaking |
| WordPress、Shopify、Squarespace、静态HTML站点 | 路径B(Loader Script)——无需构建工具,始终保持最新版本 |
| 静态HTML站点无法配置Loader Script | 路径C(CDN包)——手动添加 |
推荐话术示例:"我推荐使用路径A(npm)来配置错误监控 + 链路追踪 + 会话重放功能。是否需要同时添加日志功能或用户反馈功能?"
Phase 3: Guide
阶段3:分步指南
Path A: npm / yarn / pnpm (Recommended — Bundler Projects)
路径A:npm / yarn / pnpm(推荐——打包工具项目)
Install
安装
bash
npm install @sentry/browser --savebash
npm install @sentry/browser --saveor
或
yarn add @sentry/browser
yarn add @sentry/browser
or
或
pnpm add @sentry/browser
undefinedpnpm add @sentry/browser
undefinedCreate src/instrument.ts
src/instrument.ts创建src/instrument.ts
src/instrument.tsSentry must initialize before any other code runs. Put in a dedicated sidecar file:
Sentry.init()typescript
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 | | |
| Custom webpack | | |
| esbuild | | |
| Rollup | | |
Sentry必须在其他所有代码运行前初始化。将放在一个独立的文件中:
Sentry.init()typescript
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 | | |
| 自定义webpack | | |
| esbuild | | |
| Rollup | | |
Entry Point Setup
入口文件设置
Import as the very first import in your entry file:
instrument.tstypescript
// src/main.ts or src/index.ts
import "./instrument"; // ← MUST be first
// ... rest of your app在你的入口文件中第一行导入:
instrument.tstypescript
// src/main.ts 或 src/index.ts
import "./instrument"; // ← 必须是第一行
// ... 应用其余代码Source Maps Setup (Strongly Recommended)
Source Maps设置(强烈推荐)
Without source maps, stack traces show minified code. Set up the build plugin to upload source maps automatically:
No dedicated browser wizard: There is noflag. The closest isnpx @sentry/wizard -i browserwhich configures source map upload only for an already-initialized SDK.npx @sentry/wizard@latest -i sourcemaps
Vite ():
vite.config.tstypescript
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.jsjavascript
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.jsjavascript
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.jsjavascript
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. Usesplitting: trueinstead if code splitting is enabled.sentry-cli
Using (any toolchain / CI):
sentry-clibash
undefined如果没有source maps,堆栈跟踪将显示压缩后的代码。请配置构建工具插件以自动上传source maps:
注意:没有专门的浏览器向导: 不存在命令。最接近的是npx @sentry/wizard -i browser,它仅会为已初始化的SDK配置source map上传。npx @sentry/wizard@latest -i sourcemaps
Vite():
vite.config.tstypescript
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.jsjavascript
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.jsjavascript
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.jsjavascript
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
使用(适用于任何工具链/CI环境):
sentry-clibash
undefinedAfter your build step:
构建完成后执行:
npx @sentry/cli sourcemaps inject ./dist
npx @sentry/cli sourcemaps upload ./dist
Add `.env` for auth (never commit):
```bash
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slugnpx @sentry/cli sourcemaps inject ./dist
npx @sentry/cli sourcemaps upload ./dist
添加`.env`文件存储认证信息(切勿提交到代码仓库):
```bash
SENTRY_AUTH_TOKEN=sntrys_...
SENTRY_ORG=my-org-slug
SENTRY_PROJECT=my-project-slugPath B: Loader Script (WordPress, Static Sites, Shopify, Squarespace)
路径B:Loader Script(WordPress、静态站点、Shopify、Squarespace)
Best for: Sites without a build system. The Loader Script is a single tag that lazily loads the full SDK, always stays up to date via Sentry's CDN, and buffers errors before the SDK loads.
<script>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:
html
<!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 | After all page scripts finish |
| Manual | Call | Whenever you call it |
Safe to call before SDK loads (buffered):
Sentry.captureException()Sentry.captureMessage()Sentry.captureEvent()Sentry.addBreadcrumb()Sentry.withScope()
For other methods, use :
Sentry.onLoad()html
<script>
window.Sentry && Sentry.onLoad(function () {
Sentry.setUser({ id: "123" });
});
</script>Set release via global (optional):
html
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>Loader Script limitations:
- ❌ No (logging) — npm path only
Sentry.logger.* - ❌ No framework-specific features (React ErrorBoundary, Vue Router tracking, etc.)
- ❌ Tracing headers only added to fetch calls made after SDK loads
- ❌ Version changes take a few minutes to propagate via CDN cache
- ⚠️ Use (not
defer) on all other scripts when using the loaderasync
CSP requirements:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.io最佳适用场景: 没有构建系统的站点。Loader Script是一个单独的标签,会通过Sentry的CDN懒加载完整SDK,并且在SDK加载完成前会缓存错误信息。
<script>获取Loader Script:
进入Sentry UI → 设置 → 项目 → (你的项目) → SDK设置 → Loader Script
复制生成的标签,并将其放在每个页面的第一个脚本位置:
html
<!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方法时 |
| 立即加载 | 在 | 所有页面脚本加载完成后 |
| 手动加载 | 调用 | 调用该方法时 |
SDK加载前可安全调用的方法(会被缓存):
Sentry.captureException()Sentry.captureMessage()Sentry.captureEvent()Sentry.addBreadcrumb()Sentry.withScope()
对于其他方法,请使用:
Sentry.onLoad()html
<script>
window.Sentry && Sentry.onLoad(function () {
Sentry.setUser({ id: "123" });
});
</script>通过全局变量设置版本(可选):
html
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>Loader Script的限制:
- ❌ 不支持(日志功能)——仅支持npm路径
Sentry.logger.* - ❌ 不支持框架专属功能(如React ErrorBoundary、Vue Router追踪等)
- ❌ SDK加载前发起的fetch请求不会添加追踪头
- ❌ 版本更新需要几分钟时间通过CDN缓存传播
- ⚠️ 使用Loader时,所有其他脚本请使用(不要使用
defer)async
CSP要求:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.ioPath C: CDN Bundles (Manual Script Tags)
路径C:CDN包(手动脚本标签)
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):
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.min.js"
integrity="sha384-L/HYBH2QCeLyXhcZ0hPTxWMnyMJburPJyVoBmRk4OoilqrOWq5kU4PNTLFYrCYPr"
crossorigin="anonymous"
></script>Errors + Tracing:
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.min.js"
integrity="sha384-DIqcfVcfIewrWiNWfVZcGWExO5v673hkkC5ixJnmAprAfJajpUDEAL35QgkOB5gw"
crossorigin="anonymous"
></script>Errors + Session Replay:
html
<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):
html
<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:
html
<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):
html
<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 |
|---|---|---|
| Errors only | Absolute minimum footprint |
| + Tracing | Performance monitoring |
| + Replay | Session recording |
| + Tracing + Replay | Full observability |
| + User Feedback | + in-app feedback widget |
| + Logs + Metrics | Structured logs (CDN) |
| Everything | Max coverage |
Initialize after the script tag:
html
<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最佳适用场景: 无法使用Loader Script但需要同步加载SDK的页面。
根据所需功能选择对应的包,并将其放在所有其他脚本之前:
仅错误监控(最小体积):
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.min.js"
integrity="sha384-L/HYBH2QCeLyXhcZ0hPTxWMnyMJburPJyVoBmRk4OoilqrOWq5kU4PNTLFYrCYPr"
crossorigin="anonymous"
></script>错误监控 + 链路追踪:
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.min.js"
integrity="sha384-DIqcfVcfIewrWiNWfVZcGWExO5v673hkkC5ixJnmAprAfJajpUDEAL35QgkOB5gw"
crossorigin="anonymous"
></script>错误监控 + 会话重放:
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.replay.min.js"
integrity="sha384-sbojwIJFpv9duIzsI9FRm87g7pB15s4QwJS1m1xMSOdV1CF3pwgrPPEu38Em7M9+"
crossorigin="anonymous"
></script>错误监控 + 链路追踪 + 会话重放(推荐完整配置):
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.min.js"
integrity="sha384-oo2U4zsTxaHSPXJEnXtaQPeS4Z/qbTqoBL9xFgGxvjJHKQjIrB+VRlu97/iXBtzw"
crossorigin="anonymous"
></script>错误监控 + 链路追踪 + 会话重放 + 用户反馈:
html
<script
src="https://browser.sentry-cdn.com/10.42.0/bundle.tracing.replay.feedback.min.js"
integrity="sha384-SmHU39Qs9cua0KLtq3A6gis1/cqM1nZ6fnGzlvWAPiwhBDO5SmwFQV65BBpJnB3n"
crossorigin="anonymous"
></script>完整包(包含所有功能):
html
<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包变体汇总:
| 包名称 | 包含功能 | 适用场景 |
|---|---|---|
| 仅错误监控 | 追求最小体积时使用 |
| + 链路追踪 | 需要性能监控时使用 |
| + 会话重放 | 需要会话录制时使用 |
| + 链路追踪 + 会话重放 | 需要完整可观测性时使用 |
| + 用户反馈 | + 需要应用内反馈组件时使用 |
| + 日志 + 指标 | 需要结构化日志(CDN方式)时使用 |
| 所有功能 | 需要最大覆盖范围时使用 |
在脚本标签之后初始化:
html
<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.ioFor Each Agreed Feature
针对每个已确认的功能
Walk through features one at a time. Load the reference file, follow its steps, verify before moving on:
| Feature | Reference | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing | | Page load / API call tracing |
| Session Replay | | User-facing app |
| Logging | | Structured log search; npm or CDN logs bundle (not Loader Script) |
| Profiling | | Performance-critical, Chromium-only |
| User Feedback | | Capture user reports after errors |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个功能进行配置。加载参考文件,严格按照步骤操作,验证通过后再进行下一步:
| 功能 | 参考文档 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能) |
| 链路追踪 | | 需要页面加载/API调用追踪时 |
| 会话重放 | | 面向用户的应用 |
| 日志功能 | | 需要结构化日志搜索;仅支持npm或CDN日志包(不支持Loader Script) |
| 性能分析 | | 性能敏感型、仅支持Chromium的应用 |
| 用户反馈 | | 需要在错误发生后收集用户报告时 |
对于每个功能:阅读,严格按照步骤操作,验证功能正常工作。
${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
配置参考
Key Sentry.init()
Options
Sentry.init()Sentry.init()
关键选项
Sentry.init()| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Required. SDK disabled when empty |
| | | e.g., |
| | — | e.g., |
| | | Includes IP addresses and request headers |
| | — | 0–1; |
| | — | Per-transaction sampling; overrides rate |
| | same-origin | Outgoing URLs that receive distributed tracing headers |
| | — | Fraction of all sessions recorded |
| | — | Fraction of error sessions recorded |
| | | Enable |
| | | Stack traces on |
| | | Breadcrumbs stored per event |
| | | Verbose SDK output to console |
| | — | Proxy URL to bypass ad blockers |
| | | Drop errors matching these patterns |
| | | Drop errors from scripts at these URLs |
| | | Only capture errors from these script URLs |
| | | Forward events to Spotlight local dev overlay |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 必填项。 为空时SDK会被禁用 |
| | | 例如: |
| | — | 例如: |
| | | 是否包含IP地址和请求头 |
| | — | 0–1;开发环境设为 |
| | — | 按事务采样;优先级高于采样率 |
| `(string\ | RegExp)[]` | 同域 |
| | — | 录制的会话比例 |
| | — | 发生错误的会话的录制比例 |
| | | 启用 |
| | | 调用 |
| | | 每个事件存储的面包屑数量 |
| | | 是否在控制台输出详细的SDK日志 |
| | — | 用于绕过广告拦截的代理URL |
| `(string\ | RegExp)[]` | |
| `(string\ | RegExp)[]` | |
| `(string\ | RegExp)[]` | |
| `boolean\ | string` | |
Browser-Specific Options
浏览器专属选项
| Option | Type | Default | Notes |
|---|---|---|---|
| | — | Base URL for lazy-loading integrations |
| | | Skip check for browser extension context |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | — | 懒加载集成的基础URL |
| | | 是否跳过浏览器扩展上下文检查 |
window.SENTRY_RELEASE
Global (CDN / Loader Path)
window.SENTRY_RELEASEwindow.SENTRY_RELEASE
全局变量(CDN / Loader路径适用)
window.SENTRY_RELEASESet the release version before the SDK loads:
html
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>在SDK加载前设置版本号:
html
<script>
window.SENTRY_RELEASE = { id: "my-app@1.0.0" };
</script>Verification
验证
Trigger test events to confirm Sentry is receiving data:
npm / CDN path:
html
<!-- Add temporarily to your page -->
<button onclick="throw new Error('Sentry Browser Test Error')">
Test Error
</button>Performance verification (npm path):
javascript
import * as Sentry from "@sentry/browser";
Sentry.startSpan({ name: "Test Span", op: "test" }, () => {
// your operation
});Manual capture:
javascript
Sentry.captureException(new Error("Manual test"));
Sentry.captureMessage("Manual test message", "info");Check the Sentry dashboard:
- Issues → error appears within seconds
- Traces → page load transaction visible
- Replays → session recording visible after page interaction
- Logs → structured log entries if logging enabled (npm or CDN logs bundle)
Set in and check the browser console if nothing appears.
debug: trueSentry.init()触发测试事件以确认Sentry正在接收数据:
npm / CDN路径:
html
<!-- 临时添加到页面中 -->
<button onclick="throw new Error('Sentry Browser Test Error')">
测试错误
</button>性能验证(npm路径):
javascript
import * as Sentry from "@sentry/browser";
Sentry.startSpan({ name: "Test Span", op: "test" }, () => {
// 你的操作代码
});手动捕获事件:
javascript
Sentry.captureException(new Error("Manual test"));
Sentry.captureMessage("Manual test message", "info");检查Sentry仪表盘:
- 问题 → 错误会在几秒内显示
- 链路追踪 → 页面加载事务可见
- 会话重放 → 页面交互后会话录制内容可见
- 日志 → 若启用了日志功能(npm或CDN日志包),结构化日志条目可见
如果没有数据,可在中设置并检查浏览器控制台。
Sentry.init()debug: truePhase 4: Cross-Link
阶段4:关联后端检查
After completing browser setup, check for a companion backend missing Sentry coverage:
bash
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 -3If a backend exists without Sentry configured, suggest the matching skill:
| Backend detected | Suggest skill |
|---|---|
Go ( | |
Python ( | |
Ruby ( | |
PHP ( | |
.NET ( | |
Java ( | See docs.sentry.io/platforms/java/ |
| Node.js (Express, Fastify) | |
NestJS ( | |
完成浏览器端设置后,检查是否存在未配置Sentry的配套后端项目:
bash
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( | |
Python( | |
Ruby( | |
PHP( | |
.NET( | |
Java( | 查看docs.sentry.io/platforms/java/ |
| Node.js(Express、Fastify) | |
NestJS( | |
Troubleshooting
故障排除
| Issue | Solution |
|---|---|
| Events not appearing | Set |
| Source maps not working | Build in production mode ( |
| Minified stack traces | Source maps not uploading — check build plugin config; run |
| 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 |
| Loader Script not firing | Verify it's the first |
| Tracing not working with Loader | Fetch calls before SDK loads won't be traced — wrap early calls in |
| Must define |
| Logging not available | |
| Profiling not working | Verify |
| Ad blockers dropping events | Set |
| Session replay not recording | Confirm |
| Replay CSP errors | Add |
| Check regex escaping; default is same-origin only |
| Events blocked by browser extension | Add |
| High event volume | Lower |
| Source maps uploaded after deploy | Source maps must be uploaded before errors occur — integrate into CI/CD |
| esbuild splitting conflict | |
| 问题 | 解决方案 |
|---|---|
| 事件未显示 | 设置 |
| Source maps不生效 | 以生产模式构建( |
| 堆栈跟踪显示压缩代码 | Source maps未上传——检查构建插件配置;运行 |
| CDN包未找到 | 检查URL中的版本号;查看browser.sentry-cdn.com获取最新版本 |
| SRI完整性错误 | 哈希不匹配——重新复制本指南中包含 |
| Loader Script未触发 | 确认它是页面上第一个 |
| Loader方式下链路追踪不生效 | SDK加载前发起的fetch请求不会被追踪——将早期请求包装在 |
| 必须在loader |
| 日志功能不可用 | |
| 性能分析不生效 | 验证文档响应头是否包含 |
| 事件被广告拦截器拦截 | 设置 |
| 会话重放未录制 | 确认 |
| 会话重放出现CSP错误 | 在CSP中添加 |
| 检查正则表达式转义;默认仅匹配同域 |
| 事件被浏览器扩展拦截 | 添加 |
| 事件量过高 | 在生产环境中降低 |
| Source maps在部署后才上传 | Source maps必须在错误发生前上传——将其集成到CI/CD流程中 |
| esbuild代码分割冲突 | |
| ", |