sentry-browser-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All 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
    @sentry/browser
    or configure the Loader Script
  • 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
@sentry/browser
≥10.0.0. Always verify against docs.sentry.io/platforms/javascript/ before implementing.

  • 用户要求「给网站添加Sentry」或为原生JavaScript设置Sentry
  • 用户想要安装
    @sentry/browser
    或配置Loader Script
  • 用户拥有WordPress、Shopify、Squarespace或静态HTML站点
  • 用户希望在不依赖框架的情况下实现错误监控、链路追踪、会话重放或日志功能
  • 没有适用的框架专属SDK
注意: 以下SDK版本和API对应
@sentry/browser
≥10.0.0。 实施前请务必对照docs.sentry.io/platforms/javascript/进行验证。

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提供更全面的覆盖范围,在继续使用
@sentry/browser
之前,必须优先推荐框架专属SDK。

Step 1A: Framework Detection (Redirect If Found)

步骤1A:框架检测(若检测到则跳转)

bash
undefined
bash
undefined

Check 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
undefined
bash
undefined

Check 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
    Sentry.logger.*
    ; requires npm or CDN logs bundle (not available via Loader Script)
  • Profiling — JS Self-Profiling API; beta, Chromium-only, requires
    Document-Policy: js-profiling
    response header
Feature recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways for interactive pages — page load + navigation spans are high-value
Session ReplayUser-facing app, support flows, or checkout pages
User FeedbackSupport-focused app; want in-app bug reports with screenshots
LoggingStructured log search or log-to-trace correlation needed; npm path only
ProfilingPerformance-critical, Chromium-only app;
Document-Policy: js-profiling
header required
Installation path recommendation:
ScenarioRecommended path
Project has
package.json
+ bundler
Path A (npm) — full features, source maps, tree-shaking
WordPress, Shopify, Squarespace, static HTMLPath B (Loader Script) — zero build tooling, always up to date
Static HTML without Loader Script accessPath 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?"

根据检测结果给出推荐方案。直接给出具体建议,不要提出开放式问题。
推荐核心功能(基础覆盖):
  • 错误监控——必选;捕获未处理错误和Promise拒绝
  • 链路追踪——所有交互式站点推荐使用;追踪页面加载和用户交互
  • 会话重放——面向用户的应用推荐使用;记录错误发生前后的会话内容
可选功能(增强可观测性):
  • 用户反馈——错误发生后直接从用户端收集反馈报告
  • 日志功能——通过
    Sentry.logger.*
    实现结构化日志;仅支持npm或CDN日志包(Loader Script不支持)
  • 性能分析——基于JS Self-Profiling API;处于Beta阶段,仅支持Chromium浏览器,需要配置
    Document-Policy: js-profiling
    响应头
功能推荐逻辑:
功能推荐场景
错误监控始终推荐——不可缺少的基础功能
链路追踪所有交互式页面均推荐——页面加载和导航链路的价值很高
会话重放面向用户的应用、支持流程或结账页面
用户反馈以支持为核心的应用;希望在应用内收集带截图的Bug报告
日志功能需要结构化日志搜索或日志-链路关联;仅支持npm路径
性能分析性能敏感型、仅支持Chromium的应用;需配置
Document-Policy: js-profiling
响应头
安装路径推荐:
场景推荐路径
项目存在package.json且使用打包工具路径A(npm)——功能完整,支持source maps和tree-shaking
WordPress、Shopify、Squarespace、静态HTML站点路径B(Loader Script)——无需构建工具,始终保持最新版本
静态HTML站点无法配置Loader Script路径C(CDN包)——手动添加
<script>
标签
推荐话术示例:"我推荐使用路径A(npm)来配置错误监控 + 链路追踪 + 会话重放功能。是否需要同时添加日志功能或用户反馈功能?"

Phase 3: Guide

阶段3:分步指南

Path A: npm / yarn / pnpm (Recommended — Bundler Projects)

路径A:npm / yarn / pnpm(推荐——打包工具项目)

Install

安装

bash
npm install @sentry/browser --save
bash
npm install @sentry/browser --save

or

yarn add @sentry/browser
yarn add @sentry/browser

or

pnpm add @sentry/browser
undefined
pnpm add @sentry/browser
undefined

Create
src/instrument.ts

创建
src/instrument.ts

Sentry must initialize before any other code runs. Put
Sentry.init()
in a dedicated sidecar file:
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 ToolVariable NameAccess 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
SENTRY_DSN
process.env.SENTRY_DSN
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
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

Entry Point Setup

入口文件设置

Import
instrument.ts
as the very first import in your entry file:
typescript
// src/main.ts or src/index.ts
import "./instrument";  // ← MUST be first

// ... rest of your app
在你的入口文件中第一行导入
instrument.ts
typescript
// 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 no
npx @sentry/wizard -i browser
flag. The closest is
npx @sentry/wizard@latest -i sourcemaps
which configures source map upload only for an already-initialized SDK.
Vite (
vite.config.ts
):
typescript
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
):
javascript
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
):
javascript
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
):
javascript
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
. Use
sentry-cli
instead if code splitting is enabled.
Using
sentry-cli
(any toolchain / CI):
bash
undefined
如果没有source maps,堆栈跟踪将显示压缩后的代码。请配置构建工具插件以自动上传source maps:
注意:没有专门的浏览器向导: 不存在
npx @sentry/wizard -i browser
命令。最接近的是
npx @sentry/wizard@latest -i sourcemaps
,它仅会为已初始化的SDK配置source map上传。
Vite(
vite.config.ts
):
typescript
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
):
javascript
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
):
javascript
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
):
javascript
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环境):
bash
undefined

After 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-slug

npx @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-slug

Path 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
<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:
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:
ModeHowWhen SDK loads
Lazy (default)Nothing extraOn first error or manual Sentry call
EagerAdd
data-lazy="no"
to
<script>
After all page scripts finish
ManualCall
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, 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
    Sentry.logger.*
    (logging) — npm path only
  • ❌ 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
    defer
    (not
    async
    ) on all other scripts when using the loader
CSP requirements:
script-src: https://browser.sentry-cdn.com https://js.sentry-cdn.com
connect-src: *.sentry.io

最佳适用场景: 没有构建系统的站点。Loader Script是一个单独的
<script>
标签,会通过Sentry的CDN懒加载完整SDK,并且在SDK加载完成前会缓存错误信息。
获取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方法时
立即加载
<script>
标签中添加
data-lazy="no"
所有页面脚本加载完成后
手动加载调用
Sentry.forceLoad()
调用该方法时
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的限制:
  • ❌ 不支持
    Sentry.logger.*
    (日志功能)——仅支持npm路径
  • ❌ 不支持框架专属功能(如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.io

Path 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:
BundleFeaturesWhen to use
bundle.min.js
Errors onlyAbsolute minimum footprint
bundle.tracing.min.js
+ TracingPerformance monitoring
bundle.replay.min.js
+ ReplaySession recording
bundle.tracing.replay.min.js
+ Tracing + ReplayFull observability
bundle.tracing.replay.feedback.min.js
+ User Feedback+ in-app feedback widget
bundle.logs.metrics.min.js
+ Logs + MetricsStructured logs (CDN)
bundle.tracing.replay.feedback.logs.metrics.min.js
EverythingMax 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包变体汇总:
包名称包含功能适用场景
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
所有功能需要最大覆盖范围时使用
在脚本标签之后初始化:
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.io

For Each Agreed Feature

针对每个已确认的功能

Walk through features one at a time. Load the reference file, follow its steps, verify before moving on:
FeatureReferenceLoad 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
Performance-critical, Chromium-only
User Feedback
${SKILL_ROOT}/references/user-feedback.md
Capture user reports after errors
For each feature:
Read ${SKILL_ROOT}/references/<feature>.md
, follow steps exactly, verify it works.

逐个功能进行配置。加载参考文件,严格按照步骤操作,验证通过后再进行下一步:
功能参考文档加载时机
错误监控
${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
需要在错误发生后收集用户报告时
对于每个功能:阅读
${SKILL_ROOT}/references/<feature>.md
,严格按照步骤操作,验证功能正常工作。

Configuration Reference

配置参考

Key
Sentry.init()
Options

Sentry.init()
关键选项

OptionTypeDefaultNotes
dsn
string
Required. SDK disabled when empty
environment
string
"production"
e.g.,
"staging"
,
"development"
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-originOutgoing URLs that receive distributed tracing headers
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)[]
[]
Drop errors matching these patterns
denyUrls
(string|RegExp)[]
[]
Drop errors from scripts at these URLs
allowUrls
(string|RegExp)[]
[]
Only capture errors from these script URLs
spotlight
boolean|string
false
Forward events to Spotlight local dev overlay
选项类型默认值说明
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)[]`同域
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

Browser-Specific Options

浏览器专属选项

OptionTypeDefaultNotes
cdnBaseUrl
string
Base URL for lazy-loading integrations
skipBrowserExtensionCheck
boolean
false
Skip check for browser extension context
选项类型默认值说明
cdnBaseUrl
string
懒加载集成的基础URL
skipBrowserExtensionCheck
boolean
false
是否跳过浏览器扩展上下文检查

window.SENTRY_RELEASE
Global (CDN / Loader Path)

window.SENTRY_RELEASE
全局变量(CDN / Loader路径适用)

Set 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
debug: true
in
Sentry.init()
and check the browser console if nothing appears.

触发测试事件以确认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: true
并检查浏览器控制台。

Phase 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 -3
If a backend exists without Sentry configured, suggest the matching skill:
Backend detectedSuggest skill
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
)
See docs.sentry.io/platforms/java/
Node.js (Express, Fastify)
sentry-node-sdk
NestJS (
@nestjs/core
)
sentry-nestjs-sdk

完成浏览器端设置后,检查是否存在未配置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(
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

Troubleshooting

故障排除

IssueSolution
Events not appearingSet
debug: true
, check DSN, open browser console for SDK errors
Source maps not workingBuild in production mode (
npm run build
); verify
SENTRY_AUTH_TOKEN
is set
Minified stack tracesSource maps not uploading — check build plugin config; run
npx @sentry/wizard@latest -i sourcemaps
CDN bundle not foundCheck version number in URL; see browser.sentry-cdn.com for latest
SRI integrity errorHash mismatch — re-copy the full
<script>
tag including
integrity
attribute from this skill
Loader Script not firingVerify it's the first
<script>
on the page; check for CSP errors in console
Tracing not working with LoaderFetch 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 workingVerify
Document-Policy: js-profiling
header on document responses; Chromium-only
Ad blockers dropping eventsSet
tunnel: "/sentry-tunnel"
and add a server-side relay endpoint
Session replay not recordingConfirm
replayIntegration()
is in init; check
replaysSessionSampleRate
> 0
Replay CSP errorsAdd
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 extensionAdd
denyUrls: [/chrome-extension:\/\//]
to filter extension errors
High event volumeLower
sampleRate
(errors) and
tracesSampleRate
from
1.0
in production
Source maps uploaded after deploySource maps must be uploaded before errors occur — integrate into CI/CD
esbuild splitting conflict
sentryEsbuildPlugin
doesn't support
splitting: true
— use
sentry-cli
instead
问题解决方案
事件未显示设置
debug: true
,检查DSN是否正确,查看浏览器控制台的SDK错误信息
Source maps不生效以生产模式构建(
npm run build
);验证
SENTRY_AUTH_TOKEN
是否已设置
堆栈跟踪显示压缩代码Source maps未上传——检查构建插件配置;运行
npx @sentry/wizard@latest -i sourcemaps
CDN包未找到检查URL中的版本号;查看browser.sentry-cdn.com获取最新版本
SRI完整性错误哈希不匹配——重新复制本指南中包含
integrity
属性的完整
<script>
标签
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
Source maps在部署后才上传Source maps必须在错误发生上传——将其集成到CI/CD流程中
esbuild代码分割冲突
sentryEsbuildPlugin
不支持
splitting: true
——改用
sentry-cli
",