sentry-cloudflare-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
All Skills > SDK Setup > Cloudflare SDK
所有技能 > SDK设置 > Cloudflare SDK

Sentry Cloudflare SDK

Sentry Cloudflare SDK

Opinionated wizard that scans your Cloudflare project and guides you through complete Sentry setup for Workers, Pages, Durable Objects, Queues, Workflows, and Hono.
这是一个预设规则的向导工具,会扫描你的Cloudflare项目,并引导你完成Workers、Pages、Durable Objects、Queues、Workflows以及Hono的完整Sentry配置流程。

Invoke This Skill When

何时调用本技能

  • User asks to "add Sentry to Cloudflare Workers" or "set up Sentry" in a Cloudflare project
  • User wants to install or configure
    @sentry/cloudflare
  • User wants error monitoring, tracing, logging, crons, or AI monitoring for Cloudflare Workers or Pages
  • User asks about
    withSentry
    ,
    sentryPagesPlugin
    ,
    instrumentDurableObjectWithSentry
    , or
    instrumentD1WithSentry
  • User wants to monitor Durable Objects, Queues, Workflows, Scheduled handlers, or Email handlers on Cloudflare
Note: SDK versions and APIs below reflect current Sentry docs at time of writing (
@sentry/cloudflare
v10.43.0). Always verify against docs.sentry.io/platforms/javascript/guides/cloudflare/ before implementing.

  • 用户要求“为Cloudflare Workers添加Sentry”或在Cloudflare项目中“设置Sentry”
  • 用户想要安装或配置
    @sentry/cloudflare
  • 用户想要为Cloudflare Workers或Pages配置错误监控、链路追踪、日志记录、定时任务监控或AI监控
  • 用户询问
    withSentry
    sentryPagesPlugin
    instrumentDurableObjectWithSentry
    instrumentD1WithSentry
    的相关用法
  • 用户想要监控Cloudflare上的Durable Objects、Queues、Workflows、定时触发器或邮件处理器
注意: 以下SDK版本和API基于编写时的最新Sentry文档(
@sentry/cloudflare
v10.43.0)。 实施前请务必对照Sentry官方文档进行验证。

Phase 1: Detect

阶段1:项目检测

Run these commands to understand the project before making any recommendations:
bash
undefined
在给出任何建议前,运行以下命令了解项目情况:
bash
undefined

Detect Cloudflare project

检测Cloudflare项目

ls wrangler.toml wrangler.jsonc wrangler.json 2>/dev/null
ls wrangler.toml wrangler.jsonc wrangler.json 2>/dev/null

Detect existing Sentry

检测是否已安装Sentry

cat package.json 2>/dev/null | grep -E '"@sentry/'
cat package.json 2>/dev/null | grep -E '"@sentry/'

Detect project type (Workers vs Pages)

检测项目类型(Workers或Pages)

ls functions/ functions/_middleware.js functions/_middleware.ts 2>/dev/null && echo "Pages detected" cat wrangler.toml 2>/dev/null | grep -E 'main|pages_build_output_dir'
ls functions/ functions/_middleware.js functions/_middleware.ts 2>/dev/null && echo "Pages detected" cat wrangler.toml 2>/dev/null | grep -E 'main|pages_build_output_dir'

Detect framework

检测使用的框架

cat package.json 2>/dev/null | grep -E '"hono"|"remix"|"astro"|"svelte"'
cat package.json 2>/dev/null | grep -E '"hono"|"remix"|"astro"|"svelte"'

Detect Durable Objects

检测Durable Objects

cat wrangler.toml 2>/dev/null | grep -i 'durable_objects'
cat wrangler.toml 2>/dev/null | grep -i 'durable_objects'

Detect D1 databases

检测D1数据库

cat wrangler.toml 2>/dev/null | grep -i 'd1_databases'
cat wrangler.toml 2>/dev/null | grep -i 'd1_databases'

Detect Queues

检测Queues

cat wrangler.toml 2>/dev/null | grep -i 'queues'
cat wrangler.toml 2>/dev/null | grep -i 'queues'

Detect Workflows

检测Workflows

cat wrangler.toml 2>/dev/null | grep -i 'workflows'
cat wrangler.toml 2>/dev/null | grep -i 'workflows'

Detect Scheduled handlers (cron triggers)

检测定时触发器(Cron Triggers)

cat wrangler.toml 2>/dev/null | grep -i 'crons|triggers'
cat wrangler.toml 2>/dev/null | grep -i 'crons\|triggers'

Detect compatibility flags

检测兼容性标志

cat wrangler.toml 2>/dev/null | grep -i 'compatibility_flags' cat wrangler.jsonc 2>/dev/null | grep -i 'compatibility_flags'
cat wrangler.toml 2>/dev/null | grep -i 'compatibility_flags' cat wrangler.jsonc 2>/dev/null | grep -i 'compatibility_flags'

Detect AI/LLM libraries

检测AI/LLM库

cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"ai"|"@google/generative-ai"|"@langchain"'
cat package.json 2>/dev/null | grep -E '"openai"|"@anthropic-ai"|"ai"|"@google/generative-ai"|"@langchain"'

Detect logging libraries

检测日志库

cat package.json 2>/dev/null | grep -E '"pino"|"winston"'
cat package.json 2>/dev/null | grep -E '"pino"|"winston"'

Check for companion frontend

检查是否存在关联前端项目

ls frontend/ web/ client/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'

**What to determine:**

| Question | Impact |
|----------|--------|
| Workers or Pages? | Determines wrapper: `withSentry` vs `sentryPagesPlugin` |
| Hono framework? | Automatic Hono error handler integration via `honoIntegration` |
| `@sentry/cloudflare` already installed? | Skip install, go to feature config |
| Durable Objects configured? | Recommend `instrumentDurableObjectWithSentry` |
| D1 databases bound? | Recommend `instrumentD1WithSentry` |
| Queues configured? | `withSentry` auto-instruments queue handlers |
| Workflows configured? | Recommend `instrumentWorkflowWithSentry` |
| Cron triggers configured? | `withSentry` auto-instruments scheduled handlers; recommend Crons monitoring |
| `nodejs_als` or `nodejs_compat` flag set? | **Required** — SDK needs `AsyncLocalStorage` |
| AI/LLM libraries? | Recommend AI Monitoring integrations |
| Companion frontend? | Trigger Phase 4 cross-link |

---
ls frontend/ web/ client/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"'

**需要确定的信息:**

| 问题 | 影响 |
|----------|--------|
| 项目是Workers还是Pages? | 决定使用的封装方式:`withSentry` vs `sentryPagesPlugin` |
| 是否使用Hono框架? | 可通过`honoIntegration`自动集成Hono错误处理器 |
| 是否已安装`@sentry/cloudflare`? | 跳过安装步骤,直接进入功能配置 |
| 是否配置了Durable Objects? | 建议使用`instrumentDurableObjectWithSentry` |
| 是否绑定了D1数据库? | 建议使用`instrumentD1WithSentry` |
| 是否配置了Queues? | `withSentry`会自动为队列处理器添加监控 |
| 是否配置了Workflows? | 建议使用`instrumentWorkflowWithSentry` |
| 是否配置了定时触发器? | `withSentry`会自动为定时处理器添加监控;建议开启定时任务监控 |
| 是否设置了`nodejs_als`或`nodejs_compat`标志? | **必填** — SDK依赖`AsyncLocalStorage` |
| 是否使用了AI/LLM库? | 建议集成AI监控功能 |
| 是否存在关联前端项目? | 触发阶段4的跨服务配置建议 |

---

Phase 2: Recommend

阶段2:配置建议

Present a concrete recommendation based on what you found. Don't ask open-ended questions — lead with a proposal:
Recommended (core coverage):
  • Error Monitoring — always; captures unhandled exceptions in fetch, scheduled, queue, email, and Durable Object handlers
  • Tracing — automatic HTTP request spans, outbound fetch tracing, D1 query spans
Optional (enhanced observability):
  • Logging — structured logs via
    Sentry.logger.*
    ; recommend when log search is needed
  • Crons — detect missed/failed scheduled jobs; recommend when cron triggers are configured
  • D1 Instrumentation — automatic query spans and breadcrumbs; recommend when D1 is bound
  • Durable Objects — automatic error capture and spans for DO methods; recommend when DOs are configured
  • Workflows — automatic span creation for workflow steps; recommend when Workflows are configured
  • AI Monitoring — Vercel AI SDK, OpenAI, Anthropic, LangChain; recommend when AI libraries detected
Recommendation logic:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways — HTTP request tracing and outbound fetch are high-value
LoggingApp needs structured log search or log-to-trace correlation
CronsCron triggers configured in
wrangler.toml
D1 InstrumentationD1 database bindings present
Durable ObjectsDurable Object bindings configured
WorkflowsWorkflow bindings configured
AI MonitoringApp uses Vercel AI SDK, OpenAI, Anthropic, or LangChain
MetricsApp needs custom counters, gauges, or distributions
Propose: "I recommend setting up Error Monitoring + Tracing. Want me to also add D1 instrumentation and Crons monitoring?"

根据检测结果给出具体建议,不要提出开放式问题,直接给出方案:
推荐(核心覆盖):
  • 错误监控 — 必选;捕获fetch、定时任务、队列、邮件和Durable Object处理器中的未处理异常
  • 链路追踪 — 自动捕获HTTP请求链路、出站fetch调用追踪、D1查询链路
可选(增强可观测性):
  • 日志记录 — 通过
    Sentry.logger.*
    实现结构化日志;当需要日志搜索功能时推荐使用
  • 定时任务监控 — 检测遗漏/失败的定时任务;当配置了定时触发器时推荐使用
  • D1数据库监控 — 自动捕获查询链路和运行轨迹;当绑定了D1数据库时推荐使用
  • Durable Objects监控 — 自动捕获Durable Object方法的错误和链路;当配置了Durable Objects时推荐使用
  • Workflows监控 — 自动为工作流步骤创建链路;当配置了Workflows时推荐使用
  • AI监控 — 支持Vercel AI SDK、OpenAI、Anthropic、LangChain;当检测到AI库时推荐使用
推荐逻辑:
功能推荐场景
错误监控必选 — 基础监控能力,不可或缺
链路追踪必选 — HTTP请求追踪和出站fetch调用追踪价值较高
日志记录应用需要结构化日志搜索或日志与链路关联功能时
定时任务监控
wrangler.toml
中配置了定时触发器时
D1数据库监控存在D1数据库绑定时
Durable Objects监控配置了Durable Objects绑定时
Workflows监控配置了Workflows绑定时
AI监控应用使用Vercel AI SDK、OpenAI、Anthropic或LangChain时
指标监控应用需要自定义计数器、仪表盘或分布统计时
建议话术:"我建议配置错误监控+链路追踪。是否需要同时添加D1数据库监控和定时任务监控?"

Phase 3: Guide

阶段3:配置指引

Option 1: Source Maps Wizard

选项1:Source Maps向导

You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:
npx @sentry/wizard@latest -i sourcemaps
This sets up source map uploading so your production stack traces show readable code. It does not set up the SDK initialization — you still need to follow Option 2 below for the actual SDK setup.
Once it finishes, continue with Option 2 for SDK setup.
Note: Unlike framework SDKs (Next.js, SvelteKit), there is no Cloudflare-specific wizard integration. The
sourcemaps
wizard only handles source map upload configuration.

需要你手动执行 — 该向导会打开浏览器进行登录,需要交互式操作,无法由代理自动完成。请将以下命令复制到终端执行:
npx @sentry/wizard@latest -i sourcemaps
该命令会配置Source Maps上传,使生产环境的堆栈跟踪显示可读代码。但它不会完成SDK初始化 — 你仍需要按照选项2完成SDK的实际设置。
向导完成后,请继续执行选项2的SDK设置步骤。
注意: 与框架SDK(Next.js、SvelteKit)不同,目前没有针对Cloudflare的专属向导集成。
sourcemaps
向导仅处理Source Maps上传配置。

Option 2: Manual Setup

选项2:手动设置

Prerequisites: Compatibility Flags

前置条件:兼容性标志

The SDK requires
AsyncLocalStorage
. Add one of these flags to your Wrangler config:
wrangler.toml:
toml
compatibility_flags = ["nodejs_als"]
SDK依赖
AsyncLocalStorage
,请在Wrangler配置中添加以下任一标志:
wrangler.toml:
toml
compatibility_flags = ["nodejs_als"]

or: compatibility_flags = ["nodejs_compat"]

或:compatibility_flags = ["nodejs_compat"]


**wrangler.jsonc:**
```jsonc
{
  "compatibility_flags": ["nodejs_als"]
}
nodejs_als
is lighter — it only enables
AsyncLocalStorage
. Use
nodejs_compat
if your code also needs other Node.js APIs.

**wrangler.jsonc:**
```jsonc
{
  "compatibility_flags": ["nodejs_als"]
}
nodejs_als
更轻量化 — 仅启用
AsyncLocalStorage
。如果你的代码还需要其他Node.js API,请使用
nodejs_compat

Install

安装SDK

bash
npm install @sentry/cloudflare
bash
npm install @sentry/cloudflare

Workers Setup

Workers项目设置

Wrap your handler with
withSentry
. This automatically instruments
fetch
,
scheduled
,
queue
,
email
, and
tail
handlers:
typescript
import * as Sentry from "@sentry/cloudflare";

export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    sendDefaultPii: true,
    tracesSampleRate: 1.0,
    enableLogs: true,
  }),
  {
    async fetch(request, env, ctx) {
      return new Response("Hello World!");
    },
  } satisfies ExportedHandler<Env>,
);
Key points:
  • The first argument is a callback that receives
    env
    — use this to read secrets like
    SENTRY_DSN
  • The SDK reads DSN, environment, release, debug, tunnel, and traces sample rate from
    env
    automatically (see Environment Variables)
  • withSentry
    wraps all exported handlers — you do not need separate wrappers for
    scheduled
    ,
    queue
    , etc.
使用
withSentry
封装你的处理器,它会自动为
fetch
scheduled
queue
email
tail
处理器添加监控:
typescript
import * as Sentry from "@sentry/cloudflare";

export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    sendDefaultPii: true,
    tracesSampleRate: 1.0,
    enableLogs: true,
  }),
  {
    async fetch(request, env, ctx) {
      return new Response("Hello World!");
    },
  } satisfies ExportedHandler<Env>,
);
关键点:
  • 第一个参数是接收
    env
    的回调函数 — 可用于读取
    SENTRY_DSN
    等密钥
  • SDK会自动从
    env
    中读取DSN、环境、版本、调试模式、隧道和链路采样率(详见环境变量
  • withSentry
    会封装所有导出的处理器 — 无需为
    Scheduled
    queue
    等单独封装

Pages Setup

Pages项目设置

Use
sentryPagesPlugin
as middleware:
typescript
// functions/_middleware.ts
import * as Sentry from "@sentry/cloudflare";

export const onRequest = Sentry.sentryPagesPlugin((context) => ({
  dsn: context.env.SENTRY_DSN,
  sendDefaultPii: true,
  tracesSampleRate: 1.0,
  enableLogs: true,
}));
Chaining multiple middlewares:
typescript
import * as Sentry from "@sentry/cloudflare";

export const onRequest = [
  // Sentry must be first
  Sentry.sentryPagesPlugin((context) => ({
    dsn: context.env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  })),
  // Add more middlewares here
];
Using
wrapRequestHandler
directly
(for frameworks like SvelteKit on Cloudflare Pages):
typescript
import * as Sentry from "@sentry/cloudflare";

export const handle = ({ event, resolve }) => {
  return Sentry.wrapRequestHandler(
    {
      options: {
        dsn: event.platform.env.SENTRY_DSN,
        tracesSampleRate: 1.0,
      },
      request: event.request,
      context: event.platform.ctx,
    },
    () => resolve(event),
  );
};
sentryPagesPlugin
作为中间件使用:
typescript
// functions/_middleware.ts
import * as Sentry from "@sentry/cloudflare";

export const onRequest = Sentry.sentryPagesPlugin((context) => ({
  dsn: context.env.SENTRY_DSN,
  sendDefaultPii: true,
  tracesSampleRate: 1.0,
  enableLogs: true,
}));
多个中间件链式调用:
typescript
import * as Sentry from "@sentry/cloudflare";

export const onRequest = [
  // Sentry必须放在第一个
  Sentry.sentryPagesPlugin((context) => ({
    dsn: context.env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  })),
  // 在此添加其他中间件
];
直接使用
wrapRequestHandler
(适用于Cloudflare Pages上的SvelteKit等框架):
typescript
import * as Sentry from "@sentry/cloudflare";

export const handle = ({ event, resolve }) => {
  return Sentry.wrapRequestHandler(
    {
      options: {
        dsn: event.platform.env.SENTRY_DSN,
        tracesSampleRate: 1.0,
      },
      request: event.request,
      context: event.platform.ctx,
    },
    () => resolve(event),
  );
};

Hono on Cloudflare Workers

Cloudflare Workers上的Hono项目设置

Hono apps are objects with a
fetch
method — wrap them with
withSentry
directly:
typescript
import { Hono } from "hono";
import * as Sentry from "@sentry/cloudflare";

const app = new Hono();

app.get("/", (ctx) => ctx.json({ message: "Hello" }));

app.get("/error", () => {
  throw new Error("Test error");
});

app.onError((err, ctx) => {
  return ctx.json({ error: err.message }, 500);
});

export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  }),
  app,
);
The
honoIntegration
(enabled by default) automatically captures errors from Hono's
onError
handler and sets the correct transaction name with the route path.
Hono应用是带有
fetch
方法的对象 — 可直接使用
withSentry
封装:
typescript
import { Hono } from "hono";
import * as Sentry from "@sentry/cloudflare";

const app = new Hono();

app.get("/", (ctx) => ctx.json({ message: "Hello" }));

app.get("/error", () => {
  throw new Error("Test error");
});

app.onError((err, ctx) => {
  return ctx.json({ error: err.message }, 500);
});

export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  }),
  app,
);
honoIntegration
(默认启用)会自动捕获Hono的
onError
处理器中的错误,并根据路由路径设置正确的事务名称。

Set Up the SENTRY_DSN Secret

设置SENTRY_DSN密钥

Store your DSN as a Cloudflare secret — do not hardcode it:
bash
undefined
请将你的DSN存储为Cloudflare密钥 — 不要硬编码:
bash
undefined

Local development: add to .dev.vars

本地开发:添加到.dev.vars

echo 'SENTRY_DSN="https://examplePublicKey@o0.ingest.sentry.io/0"' >> .dev.vars
echo 'SENTRY_DSN="https://examplePublicKey@o0.ingest.sentry.io/0"' >> .dev.vars

Production: set as a secret

生产环境:设置为Cloudflare密钥

npx wrangler secret put SENTRY_DSN

Add the binding to your `Env` type:

```typescript
interface Env {
  SENTRY_DSN: string;
  // ... other bindings
}
npx wrangler secret put SENTRY_DSN

在`Env`类型中添加绑定:

```typescript
interface Env {
  SENTRY_DSN: string;
  // ... 其他绑定
}

Source Maps Setup

Source Maps设置

Source maps make production stack traces readable. Without them, you see minified/bundled code.
Step 1: Generate a Sentry auth token
Go to sentry.io/settings/auth-tokens/ and create a token with
project:releases
and
org:read
scopes.
Step 2: Install the Sentry Vite plugin (most Cloudflare projects use Vite via Wrangler):
bash
npm install @sentry/vite-plugin --save-dev
Step 3: Configure
vite.config.ts
(if your project has one):
typescript
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  build: {
    sourcemap: true,
  },
  plugins: [
    sentryVitePlugin({
      org: "___ORG_SLUG___",
      project: "___PROJECT_SLUG___",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});
Step 4: Set environment variables in CI
bash
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org
SENTRY_PROJECT=my-project
Step 5: Add to
.gitignore
.dev.vars
.env.sentry-build-plugin

Source Maps可让生产环境的堆栈跟踪显示可读代码。如果没有Source Maps,你将看到混淆/打包后的代码。
步骤1:生成Sentry认证令牌
访问sentry.io/settings/auth-tokens/创建一个令牌,需包含
project:releases
org:read
权限。
步骤2:安装Sentry Vite插件(大多数Cloudflare项目通过Wrangler使用Vite):
bash
npm install @sentry/vite-plugin --save-dev
步骤3:配置
vite.config.ts
(如果项目中有该文件):
typescript
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  build: {
    sourcemap: true,
  },
  plugins: [
    sentryVitePlugin({
      org: "___ORG_SLUG___",
      project: "___PROJECT_SLUG___",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});
步骤4:在CI中设置环境变量
bash
SENTRY_AUTH_TOKEN=sntrys_eyJ...
SENTRY_ORG=my-org
SENTRY_PROJECT=my-project
步骤5:添加到
.gitignore
.dev.vars
.env.sentry-build-plugin

Automatic Release Detection

自动版本检测

The SDK can automatically detect the release version via Cloudflare's version metadata binding:
wrangler.toml:
toml
[version_metadata]
binding = "CF_VERSION_METADATA"
Release priority (highest to lowest):
  1. release
    option passed to
    Sentry.init()
  2. SENTRY_RELEASE
    environment variable
  3. CF_VERSION_METADATA.id
    binding

SDK可通过Cloudflare的版本元数据绑定自动检测版本号:
wrangler.toml:
toml
[version_metadata]
binding = "CF_VERSION_METADATA"
版本优先级(从高到低):
  1. 传递给
    Sentry.init()
    release
    选项
  2. SENTRY_RELEASE
    环境变量
  3. CF_VERSION_METADATA.id
    绑定

For Each Agreed Feature

针对每个确认的功能

Load the corresponding reference file and follow its steps:
FeatureReference fileLoad when...
Error Monitoring
references/error-monitoring.md
Always (baseline) — unhandled exceptions, manual capture, scopes, enrichment
Tracing
references/tracing.md
HTTP request tracing, outbound fetch spans, D1 query spans, distributed tracing
Logging
references/logging.md
Structured logs via
Sentry.logger.*
, log-to-trace correlation
Crons
references/crons.md
Scheduled handler monitoring,
withMonitor
, check-in API
Durable Objects
references/durable-objects.md
Instrument Durable Object classes for error capture and spans
For each feature: read the reference file, follow its steps exactly, and verify before moving on.

加载对应的参考文件并按照步骤操作:
功能参考文件加载场景
错误监控
references/error-monitoring.md
必选(基础功能) — 未处理异常、手动捕获、作用域、事件增强
链路追踪
references/tracing.md
HTTP请求追踪、出站fetch链路、D1查询链路、分布式追踪
日志记录
references/logging.md
通过
Sentry.logger.*
实现结构化日志、日志与链路关联
定时任务监控
references/crons.md
定时处理器监控、
withMonitor
、检查点API
Durable Objects监控
references/durable-objects.md
为Durable Object类添加监控以捕获错误和链路
对于每个功能:请仔细阅读参考文件,严格按照步骤操作,并在完成后进行验证。

Verification

验证配置

After setup, verify Sentry is working:
typescript
// Add temporarily to your fetch handler, then remove
export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  }),
  {
    async fetch(request, env, ctx) {
      throw new Error("Sentry test error — delete me");
    },
  } satisfies ExportedHandler<Env>,
);
Deploy and trigger the route, then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
CheckHow
Errors capturedThrow in a fetch handler, verify in Sentry
Tracing workingCheck Performance tab for HTTP spans
Source maps workingCheck stack trace shows readable file/line names
D1 spans (if configured)Run a D1 query, check for
db.query
spans
Scheduled monitoring (if configured)Trigger a cron, check Crons dashboard

设置完成后,验证Sentry是否正常工作:
typescript
// 临时添加到fetch处理器中,验证完成后删除
export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  }),
  {
    async fetch(request, env, ctx) {
      throw new Error("Sentry测试错误 — 请删除此代码");
    },
  } satisfies ExportedHandler<Env>,
);
部署并触发该路由,然后检查你的Sentry问题面板 — 错误应该会在约30秒内显示。
验证清单:
检查项验证方式
错误是否被捕获在fetch处理器中抛出错误,在Sentry中查看是否显示
链路追踪是否正常查看Performance面板中的HTTP链路
Source Maps是否生效检查堆栈跟踪是否显示可读的文件/行号
D1查询链路是否正常(若配置)执行D1查询,查看是否存在
db.query
链路
定时任务监控是否正常(若配置)触发定时任务,查看Crons面板

Config Reference

配置参考

Sentry.init()
Options

Sentry.init()
选项

OptionTypeDefaultNotes
dsn
string
Required. Read from
env.SENTRY_DSN
automatically if not set
tracesSampleRate
number
0–1; 1.0 in dev, lower in prod recommended
tracesSampler
function
Dynamic sampling function; mutually exclusive with
tracesSampleRate
sendDefaultPii
boolean
false
Include request headers and cookies in events
enableLogs
boolean
false
Enable Sentry Logs product
environment
string
autoRead from
env.SENTRY_ENVIRONMENT
if not set
release
string
autoDetected from
CF_VERSION_METADATA.id
or
SENTRY_RELEASE
debug
boolean
false
Read from
env.SENTRY_DEBUG
if not set. Log SDK activity to console
tunnel
string
Read from
env.SENTRY_TUNNEL
if not set
beforeSend
function
Filter/modify error events before sending
beforeSendTransaction
function
Filter/modify transaction events before sending
beforeSendLog
function
Filter/modify log entries before sending
tracePropagationTargets
(string|RegExp)[]
all URLsControl which outbound requests get trace headers
skipOpenTelemetrySetup
boolean
false
Opt-out of OpenTelemetry compatibility tracer
instrumentPrototypeMethods
boolean | string[]
false
Durable Object: instrument prototype methods for RPC spans
选项类型默认值说明
dsn
string
必填。若未设置,会自动从
env.SENTRY_DSN
读取
tracesSampleRate
number
0–1;开发环境建议设为1.0,生产环境建议降低
tracesSampler
function
动态采样函数;与
tracesSampleRate
互斥
sendDefaultPii
boolean
false
是否在事件中包含请求头和Cookie
enableLogs
boolean
false
是否启用Sentry日志功能
environment
string
自动检测若未设置,会自动从
env.SENTRY_ENVIRONMENT
读取
release
string
自动检测
CF_VERSION_METADATA.id
SENTRY_RELEASE
自动检测
debug
boolean
false
若未设置,会自动从
env.SENTRY_DEBUG
读取。启用后会在控制台打印SDK活动日志
tunnel
string
若未设置,会自动从
env.SENTRY_TUNNEL
读取
beforeSend
function
发送前过滤/修改错误事件
beforeSendTransaction
function
发送前过滤/修改事务事件
beforeSendLog
function
发送前过滤/修改日志条目
tracePropagationTargets
(string|RegExp)[]
所有URL控制哪些出站请求会添加追踪头
skipOpenTelemetrySetup
boolean
false
是否选择不启用OpenTelemetry兼容追踪器
instrumentPrototypeMethods
boolean | string[]
false
Durable Object:为原型方法添加监控以捕获RPC链路

Environment Variables (Read from
env
)

环境变量(从
env
读取)

The SDK reads these from the Cloudflare
env
object automatically:
VariablePurpose
SENTRY_DSN
DSN for Sentry init
SENTRY_RELEASE
Release version string
SENTRY_ENVIRONMENT
Environment name (
production
,
staging
)
SENTRY_TRACES_SAMPLE_RATE
Traces sample rate (parsed as float)
SENTRY_DEBUG
Enable debug mode (
"true"
/
"1"
)
SENTRY_TUNNEL
Tunnel URL for event proxying
CF_VERSION_METADATA
Cloudflare version metadata binding (auto-detected release)
SDK会自动从Cloudflare的
env
对象中读取以下变量:
变量用途
SENTRY_DSN
Sentry初始化使用的DSN
SENTRY_RELEASE
版本号字符串
SENTRY_ENVIRONMENT
环境名称(如
production
staging
SENTRY_TRACES_SAMPLE_RATE
链路采样率(解析为浮点数)
SENTRY_DEBUG
是否启用调试模式(
"true"
/
"1"
SENTRY_TUNNEL
事件代理的隧道URL
CF_VERSION_METADATA
Cloudflare版本元数据绑定(自动检测版本号)

Default Integrations

默认集成

These are registered automatically by
getDefaultIntegrations()
:
IntegrationPurpose
dedupeIntegration
Prevent duplicate events (disabled for Workflows)
inboundFiltersIntegration
Filter events by type, message, URL
functionToStringIntegration
Preserve original function names
linkedErrorsIntegration
Follow
cause
chains in errors
fetchIntegration
Trace outbound
fetch()
calls, create breadcrumbs
honoIntegration
Auto-capture Hono
onError
exceptions
requestDataIntegration
Attach request data to events
consoleIntegration
Capture
console.*
calls as breadcrumbs

以下集成会通过
getDefaultIntegrations()
自动注册:
集成用途
dedupeIntegration
Prevent duplicate events (disabled for Workflows)
inboundFiltersIntegration
按类型、消息、URL过滤事件
functionToStringIntegration
保留原始函数名
linkedErrorsIntegration
追踪错误中的
cause
fetchIntegration
追踪出站
fetch()
调用,创建运行轨迹
honoIntegration
自动捕获Hono
onError
处理器中的异常
requestDataIntegration
将请求数据附加到事件中
consoleIntegration
console.*
调用捕获为运行轨迹

Phase 4: Cross-Link

阶段4:关联服务配置建议

After completing Cloudflare setup, check for companion services:
bash
undefined
完成Cloudflare项目的Sentry设置后,检查是否存在关联服务:
bash
undefined

Check for companion frontend

检查是否存在关联前端项目

ls frontend/ web/ client/ ui/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"|"astro"'
ls frontend/ web/ client/ ui/ 2>/dev/null cat package.json 2>/dev/null | grep -E '"react"|"vue"|"svelte"|"next"|"astro"'

Check for companion backend in adjacent directories

检查相邻目录中是否存在关联后端项目

ls ../backend ../server ../api 2>/dev/null cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3

If a frontend is found, suggest the matching SDK skill:

| Frontend detected | Suggest skill |
|------------------|--------------|
| React | `sentry-react-sdk` |
| Next.js | `sentry-nextjs-sdk` |
| Svelte/SvelteKit | `sentry-svelte-sdk` |
| Vue/Nuxt | See [docs.sentry.io/platforms/javascript/guides/vue/](https://docs.sentry.io/platforms/javascript/guides/vue/) |

If a backend is found in a different directory:

| Backend detected | Suggest skill |
|-----------------|--------------|
| Go (`go.mod`) | `sentry-go-sdk` |
| Python (`requirements.txt`, `pyproject.toml`) | `sentry-python-sdk` |
| Ruby (`Gemfile`) | `sentry-ruby-sdk` |
| Node.js (Express, Fastify) | `sentry-node-sdk` |

Connecting frontend and backend with linked Sentry projects enables **distributed tracing** — stack traces that span your browser, Cloudflare Worker, and backend API in a single trace view.

---
ls ../backend ../server ../api 2>/dev/null cat ../go.mod ../requirements.txt ../Gemfile 2>/dev/null | head -3

如果检测到前端项目,建议使用对应的SDK技能:

| 检测到的前端框架 | 建议技能 |
|------------------|--------------|
| React | `sentry-react-sdk` |
| Next.js | `sentry-nextjs-sdk` |
| Svelte/SvelteKit | `sentry-svelte-sdk` |
| Vue/Nuxt | 参考[Sentry官方文档](https://docs.sentry.io/platforms/javascript/guides/vue/) |

如果在其他目录中检测到后端项目:

| 检测到的后端技术 | 建议技能 |
|-----------------|--------------|
| Go (`go.mod`) | `sentry-go-sdk` |
| Python (`requirements.txt`, `pyproject.toml`) | `sentry-python-sdk` |
| Ruby (`Gemfile`) | `sentry-ruby-sdk` |
| Node.js (Express, Fastify) | `sentry-node-sdk` |

通过关联Sentry项目连接前端和后端,可实现**分布式追踪** — 即在单个追踪视图中查看跨越浏览器、Cloudflare Worker和后端API的完整堆栈跟踪。

---

Troubleshooting

故障排查

IssueCauseSolution
Events not appearingDSN not set or
debug: false
hiding errors
Set
debug: true
temporarily in init options; verify
SENTRY_DSN
secret is set with
wrangler secret list
AsyncLocalStorage is not defined
Missing compatibility flagAdd
nodejs_als
or
nodejs_compat
to
compatibility_flags
in
wrangler.toml
Stack traces show minified codeSource maps not uploadedConfigure
@sentry/vite-plugin
or run
npx @sentry/wizard -i sourcemaps
; verify
SENTRY_AUTH_TOKEN
in CI
Events lost on short-lived requestsSDK not flushing before worker terminatesEnsure
withSentry
or
sentryPagesPlugin
wraps your handler — they use
ctx.waitUntil()
to flush
Hono errors not capturedHono app not wrapped with
withSentry
Pass the Hono app as the second argument to
Sentry.withSentry()
Durable Object errors missingDO class not instrumentedWrap class with
Sentry.instrumentDurableObjectWithSentry()
— see
references/durable-objects.md
D1 queries not creating spansD1 binding not instrumentedWrap binding with
Sentry.instrumentD1WithSentry(env.DB)
before use
Scheduled handler not monitored
withSentry
not wrapping the handler
Ensure
export default Sentry.withSentry(...)
wraps your entire exported handler object
Release not auto-detected
CF_VERSION_METADATA
binding not configured
Add
[version_metadata]
with
binding = "CF_VERSION_METADATA"
to
wrangler.toml
Duplicate events in WorkflowsDedupe integration filtering step failuresSDK automatically disables dedupe for Workflows; verify you use
instrumentWorkflowWithSentry
问题原因解决方案
事件未出现在Sentry中未设置DSN或
debug: false
隐藏了错误
临时在初始化选项中设置
debug: true
;通过
wrangler secret list
验证
SENTRY_DSN
密钥是否已设置
AsyncLocalStorage is not defined
缺少兼容性标志
wrangler.toml
compatibility_flags
中添加
nodejs_als
nodejs_compat
堆栈跟踪显示混淆代码未上传Source Maps配置
@sentry/vite-plugin
或运行
npx @sentry/wizard -i sourcemaps
;验证CI中的
SENTRY_AUTH_TOKEN
是否正确
短生命周期请求中的事件丢失SDK在Worker终止前未完成事件发送确保使用
withSentry
sentryPagesPlugin
封装处理器 — 它们会使用
ctx.waitUntil()
确保事件发送完成
Hono错误未被捕获Hono应用未使用
withSentry
封装
将Hono应用作为第二个参数传递给
Sentry.withSentry()
Durable Object错误未被捕获未为DO类添加监控使用
Sentry.instrumentDurableObjectWithSentry()
封装类 — 参考
references/durable-objects.md
D1查询未创建链路未为D1绑定添加监控使用
Sentry.instrumentD1WithSentry(env.DB)
封装绑定后再使用
定时处理器未被监控未使用
withSentry
封装处理器
确保
export default Sentry.withSentry(...)
封装了整个导出的处理器对象
版本号未被自动检测未配置
CF_VERSION_METADATA
绑定
wrangler.toml
中添加
[version_metadata]
并设置
binding = "CF_VERSION_METADATA"
Workflows中出现重复事件去重集成过滤步骤失败SDK会自动为Workflows禁用去重集成;确保使用
instrumentWorkflowWithSentry
",