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触发器)

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` 还是 `sentryPagesPlugin` |
| 是否使用Hono框架? | 通过`honoIntegration`自动集成Hono错误处理器 |
| 是否已安装`@sentry/cloudflare`? | 跳过安装步骤,直接进入功能配置 |
| 是否已配置Durable Objects? | 推荐使用`instrumentDurableObjectWithSentry` |
| 是否已绑定D1数据库? | 推荐使用`instrumentD1WithSentry` |
| 是否已配置Queues? | `withSentry`会自动为队列处理器添加埋点 |
| 是否已配置Workflows? | 推荐使用`instrumentWorkflowWithSentry` |
| 是否已配置Cron触发器? | `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.*
    生成结构化日志;当需要日志搜索时推荐配置
  • 定时任务监控 — 检测定时任务的遗漏/失败情况;当配置了Cron触发器时推荐配置
  • D1埋点 — 自动生成查询链路和运行轨迹;当绑定了D1数据库时推荐配置
  • Durable Objects监控 — 自动捕获DO方法的错误并生成链路;当配置了DO时推荐配置
  • Workflows监控 — 自动为工作流步骤生成链路;当配置了Workflows时推荐配置
  • AI监控 — 支持Vercel AI SDK、OpenAI、Anthropic、LangChain;当检测到AI库时推荐配置
建议逻辑:
功能推荐场景
错误监控始终必选 — 不可缺少的基础配置
链路追踪始终必选 — HTTP请求追踪和出站fetch追踪价值极高
日志记录应用需要结构化日志搜索或日志与链路关联时
定时任务监控
wrangler.toml
中配置了Cron触发器时
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 Map上传,让生产环境的堆栈跟踪显示可读代码。但它不会完成SDK初始化 — 你仍需要按照下方选项2完成SDK的实际设置。
完成后,请继续执行选项2的SDK设置步骤。
注意: 与框架SDK(如Next.js、SvelteKit)不同,目前没有针对Cloudflare的专属向导集成。
sourcemaps
向导仅处理Source Map上传配置。

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

生产环境:设置为密钥

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可以让生产环境的堆栈跟踪显示可读代码。如果没有它,你只会看到压缩/打包后的代码。
步骤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 test error — delete me");
    },
  } satisfies ExportedHandler<Env>,
);
部署并触发该路由,然后查看你的Sentry问题面板 — 错误应该会在约30秒内显示。
验证清单:
检查项验证方式
错误捕获正常在fetch处理器中抛出错误,在Sentry中验证
链路追踪正常在性能面板中查看HTTP链路
Source Maps正常检查堆栈跟踪显示可读的文件/行号
D1链路正常(若配置)运行D1查询,查看是否存在
db.query
链路
定时任务监控正常(若配置)触发定时任务,查看定时任务面板

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

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
防止重复事件(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设置后,检查是否存在配套服务:
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
问题原因解决方案
事件未显示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
",