Sentry for Cloudflare
Learn how to manually set up Sentry for Cloudflare Workers and capture your first events.
This guide covers Cloudflare Workers. If you're deploying a Cloudflare Pages application, see Cloudflare Pages instead, which is set up with middleware rather than a wrapper.
If you're using a framework, select it to open its setup instructions:
Cloudflare Workers limitations
The Cloudflare Workers runtime has some platform-specific limitations that affect tracing. See Known Limitations for details.
You need:
Run the command for your preferred package manager to add the Sentry SDK to your application:
npm install @sentry/cloudflare --save
npm install @sentry/cloudflare --save
yarn add @sentry/cloudflare
pnpm add @sentry/cloudflare
Error Monitoring starts working as soon as you configure Sentry. Logs and Application Metrics need no extra configuration, and you'll learn how to send them in steps #3 and #4. This guide also enables Tracing.
This guide sets Sentry up through Vite, which is what we recommend for Cloudflare Workers. The plugin does the wiring at build time, so your Worker code stays untouched.
Not using Vite? See the Wrangler setup for the manual instrumentation.
Add the Sentry plugin to your existing vite.config.ts, next to cloudflare(). Both of its behaviors are on by default.
autoInstrumentation wraps your Worker entry, and any Durable Object, Workflow or Agents SDK class in your wrangler config, at build time, so you don't have to call Sentry.withSentry() yourself. buildTimeInstrumentation instruments bundled dependencies such as database clients, which is the only way to trace them in the Workers runtime, where the SDK can't patch them at runtime.
To see its options, which packages it instruments, and how to opt out of either behavior, see Vite Plugin.
vite.config.ts import { cloudflare } from "@cloudflare/vite-plugin";
+import { sentryCloudflareVitePlugin } from "@sentry/cloudflare/vite";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
cloudflare(),
+ sentryCloudflareVitePlugin(),
],
});
import { cloudflare } from "@cloudflare/vite-plugin";
+import { sentryCloudflareVitePlugin } from "@sentry/cloudflare/vite";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
cloudflare(),
+ sentryCloudflareVitePlugin(),
],
});
Run vite build before wrangler deploy, and use vite dev in place of wrangler dev for local development.
Since the SDK needs access to the AsyncLocalStorage API, you need to set the nodejs_compat compatibility flag and a compatibility_date of 2024-09-23 or later in your wrangler.(jsonc|toml) configuration file. We recommend the latest compatibility date, as some integrations depend on newer Cloudflare runtime features:
wrangler.jsonc{
// Set this to today's date
"compatibility_date": "2026-11-20",
"compatibility_flags": ["nodejs_compat"],
}
{
// Set this to today's date
"compatibility_date": "2026-11-20",
"compatibility_flags": ["nodejs_compat"],
}
# Set this to today's date
compatibility_date = "2026-11-20"
compatibility_flags = ["nodejs_compat"]
If you don't set the release option manually, the SDK automatically detects it from these sources (in order of priority):
- The
SENTRY_RELEASEenvironment variable - The
CF_VERSION_METADATA.idbinding (if configured)
To enable automatic release detection via Cloudflare's version metadata, add the CF_VERSION_METADATA binding in your wrangler configuration. This provides access to the Cloudflare version metadata.
wrangler.jsonc{
// ...
"version_metadata": {
"binding": "CF_VERSION_METADATA",
},
}
{
// ...
"version_metadata": {
"binding": "CF_VERSION_METADATA",
},
}
[version_metadata]
binding = "CF_VERSION_METADATA"
Create an instrument.server.ts file next to your Worker entry, the file that main points at in your wrangler config. If main is src/index.ts, the file belongs at src/instrument.server.ts, not at the project root.
The name is fixed. The plugin looks for instrument.server with a .ts, .mts, .js, .mjs or .cjs extension, and passes its default export to withSentry. Use defineCloudflareOptions to get the options type-checked.
The snippet also turns on:
- Tracing: via
tracesSampleRate
Don't need a feature? Remove its integration and options from the snippet.
src/instrument.server.tsimport { defineCloudflareOptions } from "@sentry/cloudflare";
export default defineCloudflareOptions((env) => ({
dsn: "___PUBLIC_DSN___",
// Enables Tracing.
// Set to 1.0 to capture 100% of spans for tracing.
// We recommend reducing this value in production.
tracesSampleRate: 1.0,
}));
import { defineCloudflareOptions } from "@sentry/cloudflare";
export default defineCloudflareOptions((env) => ({
dsn: "___PUBLIC_DSN___",
// Enables Tracing.
// Set to 1.0 to capture 100% of spans for tracing.
// We recommend reducing this value in production.
tracesSampleRate: 1.0,
}));
The stack traces in your Sentry errors probably won't look like your actual code without unminifying them. To fix this, upload your source maps to Sentry.
First, set the upload_source_maps option to true in your wrangler.(jsonc|toml) config file to enable source map uploading:
wrangler.jsonc{
"upload_source_maps": true,
}
{
"upload_source_maps": true,
}
upload_source_maps = true
Next, run the Sentry Wizard to finish your setup:
npx @sentry/wizard@latest -i sourcemaps
npx @sentry/wizard@latest -i sourcemaps
By default, the SDK sends user identity data (IP address, ID, and similar) and other data like HTTP bodies and URL query parameters. This will give you rich debugging context.
The SDK always filters sensitive values whose keys match a built-in denylist, such as auth or password, and sends [Filtered] instead.
To send less data, turn off the categories you don't need in the dataCollection option. For the full list of categories and their defaults, see the dataCollection options.
src/instrument.server.tsimport { defineCloudflareOptions } from "@sentry/cloudflare";
export default defineCloudflareOptions((env) => ({
dsn: "___PUBLIC_DSN___",
dataCollection: {
userInfo: false,
// other categories
},
}));
import { defineCloudflareOptions } from "@sentry/cloudflare";
export default defineCloudflareOptions((env) => ({
dsn: "___PUBLIC_DSN___",
dataCollection: {
userInfo: false,
// other categories
},
}));
Server-side spans will display 0ms for their durations. In the Cloudflare Workers runtime, performance.now() and Date.now() only advance after I/O occurs. CPU-bound operations will show zero duration. This is a security measure Cloudflare implements to mitigate against timing attacks.
This is expected behavior in the Cloudflare Workers environment and affects all frameworks deployed to Cloudflare Workers, including Next.js, Astro, Remix, and others.
Use Sentry.logger to send logs at different levels, such as info, warn, or error. You can pass any attributes you want and search or filter by them later. See Set Up Logs for all available logging methods and the syntax for formatting messages.
Sentry.logger.info("User example action completed");
Sentry.logger.warn("Slow operation detected", {
operation: "data_fetch",
duration: 3500,
});
Sentry.logger.error("Validation failed", {
form_field: "email",
reason: "Invalid email",
});
Sentry.logger.info("User example action completed");
Sentry.logger.warn("Slow operation detected", {
operation: "data_fetch",
duration: 3500,
});
Sentry.logger.error("Validation failed", {
form_field: "email",
reason: "Invalid email",
});
If you're already logging with console or Consola, you can capture those logs with our console integrations.
Use Sentry.metrics to send counters, gauges, and distributions from your app to Sentry. You can pass any attributes you want and search or filter by them later. See Set Up Metrics for all available metric types and configuration options.
Sentry.metrics.count("checkout.failed", 1);
Sentry.metrics.gauge("time_since_refresh", 4, { unit: "hour" });
Sentry.metrics.distribution("api_latency", 187, {
unit: "millisecond",
attributes: { endpoint: "/api/orders" },
});
Sentry.metrics.count("checkout.failed", 1);
Sentry.metrics.gauge("time_since_refresh", 4, { unit: "hour" });
Sentry.metrics.distribution("api_latency", 187, {
unit: "millisecond",
attributes: { endpoint: "/api/orders" },
});
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
Add a route to your Worker that throws an error:
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/debug-sentry") {
throw new Error("Sentry Test Error");
}
return new Response("...");
},
};
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/debug-sentry") {
throw new Error("Sentry Test Error");
}
return new Response("...");
},
};
Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).
At this point, you should have integrated Sentry into your Cloudflare Worker. Here's what to explore next:
- Explore practical guides on what to monitor, log, track, and investigate after setup
- Set up Agent Tracing to follow agent runs from system prompt to final output, capturing every model call, tool execution, and handoff as a span
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").