Labsco
getsentry logo

sentry-cloudflare-sdk

โ˜… 233

by getsentry ยท part of getsentry/sentry-for-claude

Full Sentry SDK setup for Cloudflare Workers and Pages. Use when asked to "add Sentry to Cloudflare Workers", "install @sentry/cloudflare", or configure error monitoring, tracing, logging, crons, or AI monitoring for Cloudflare Workers, Pages, Durable Objects, Queues, Workflows, or Hono on Cloudflare.

๐Ÿ”Œ This skill ships inside the sentry plugin โ€” install the plugin and you also get 1 slash commands, an MCP server.

This is the playbook your agent receives when the skill activates โ€” you don't need to read it to use the skill, but it's here to audit before installing.

All Skills > SDK Setup > 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.

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.61.0). Always verify against docs.sentry.io/platforms/javascript/guides/cloudflare/ before implementing.


Phase 1: Detect

Run these commands to understand the project before making any recommendations:

# Detect Cloudflare project
ls wrangler.toml wrangler.jsonc wrangler.json 2>/dev/null

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

# Detect project type (Workers vs 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'

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

# Detect Durable Objects
cat wrangler.toml 2>/dev/null | grep -i 'durable_objects'

# Detect D1 databases
cat wrangler.toml 2>/dev/null | grep -i 'd1_databases'

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

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

# Detect Scheduled handlers (cron 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'

# Detect AI/LLM libraries
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"'

# 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:

QuestionImpact
Workers or Pages?Determines wrapper: withSentry vs sentryPagesPlugin
Hono framework?Recommend standalone @sentry/hono package (v10.55.0+) for cleaner integration
@sentry/cloudflare already installed?Skip install, go to feature config
Durable Objects configured?Recommend instrumentDurableObjectWithSentry
D1 databases bound?withSentry auto-instruments D1 bindings (v10.57.0+); no manual wrapping needed
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

Phase 2: Recommend

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?"


Phase 3: Guide

Option 1: Source Maps Wizard

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.


Option 2: Manual Setup

Prerequisites: Compatibility Flags

The SDK requires AsyncLocalStorage. Add one of these flags to your Wrangler config:

wrangler.toml:

compatibility_flags = ["nodejs_als"]
# or: compatibility_flags = ["nodejs_compat"]

wrangler.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.

Install

npm install @sentry/cloudflare

Workers Setup

Wrap your handler with withSentry. This automatically instruments fetch, scheduled, queue, email, and tail handlers:

import * as Sentry from "@sentry/cloudflare";

export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
    enableLogs: true,
    dataCollection: {
      // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
      // https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#dataCollection
      // userInfo: false,
      // httpBodies: [],
    },
  }),
  {
    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.

Pages Setup

Use sentryPagesPlugin as middleware:

// functions/_middleware.ts
import * as Sentry from "@sentry/cloudflare";

export const onRequest = Sentry.sentryPagesPlugin((context) => ({
  dsn: context.env.SENTRY_DSN,
  tracesSampleRate: 1.0,
  enableLogs: true,
  dataCollection: {
    // To disable sending user data and HTTP bodies, uncomment the lines below. For more info visit:
    // https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#dataCollection
    // userInfo: false,
    // httpBodies: [],
  },
}));

Chaining multiple middlewares:

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):

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

Recommended (v10.55.0+): Use the standalone @sentry/hono package for Hono apps:

npm install @sentry/hono @sentry/cloudflare

The @sentry/cloudflare package is a peer dependency and must stay in sync with @sentry/hono.

import { Hono } from "hono";
import { sentry } from "@sentry/hono/cloudflare";

type Bindings = { SENTRY_DSN: string };

const app = new Hono<{ Bindings: Bindings }>();

// Initialize Sentry middleware as early as possible
app.use(
  sentry(app, (env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  })),
);

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

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

export default app;

The sentry() middleware automatically captures errors and creates transaction spans with route patterns.

Legacy approach (deprecated): Using @sentry/cloudflare with withSentry still works, but honoIntegration is deprecated:

import { Hono } from "hono";
import * as Sentry from "@sentry/cloudflare";

const app = new Hono();

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

export default Sentry.withSentry(
  (env: Env) => ({
    dsn: env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  }),
  app,
);

Set Up the SENTRY_DSN Secret

Store your DSN as a Cloudflare secret โ€” do not hardcode it:

# Local development: add to .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:

interface Env {
  SENTRY_DSN: string;
  // ... other bindings
}

Source Maps Setup

Source maps make production stack traces readable. Most Cloudflare projects build with Vite via Wrangler โ€” wire the Sentry Vite plugin so maps upload on build:

npm install @sentry/vite-plugin --save-dev
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,
    }),
  ],
});

SENTRY_AUTH_TOKEN is a build-time secret. For creating the token and wiring it into CI, see sentry-source-maps. The npx @sentry/wizard@latest -i sourcemaps shortcut noted above automates this setup.


Automatic Release Detection

The SDK can automatically detect the release version via Cloudflare's version metadata binding:

wrangler.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

For Each Agreed Feature

Load the corresponding reference file and follow its steps:

FeatureReference fileLoad when...
Error Monitoringreferences/error-monitoring.mdAlways (baseline) โ€” unhandled exceptions, manual capture, scopes, enrichment
Tracingreferences/tracing.mdHTTP request tracing, outbound fetch spans, D1 query spans, distributed tracing
Loggingreferences/logging.mdStructured logs via Sentry.logger.*, log-to-trace correlation
Cronsreferences/crons.mdScheduled handler monitoring, withMonitor, check-in API
Durable Objectsreferences/durable-objects.mdInstrument Durable Object classes for error capture and spans

For each feature: read the reference file, follow its steps exactly, and verify before moving on.


Verification

After setup, verify Sentry is working:

// 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

After completing Cloudflare setup, check for companion services:

# 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"'

# 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 detectedSuggest skill
Reactsentry-react-sdk
Next.jssentry-nextjs-sdk
Svelte/SvelteKitsentry-svelte-sdk
Vue/NuxtSee docs.sentry.io/platforms/javascript/guides/vue/

If a backend is found in a different directory:

Backend detectedSuggest 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.