Cloudflare
Learn how to manually set up Sentry for Cloudflare Workers and Cloudflare Pages and capture your first errors.
Use this guide for general instructions on using the Sentry SDK with Cloudflare. If you're using any of the listed frameworks, follow their specific setup instructions:
The Cloudflare Workers runtime has some platform-specific limitations that affect tracing. SeeKnown Limitations for details.
You need:
Choose the features you want to configure, and this guide will show you how:
Want to learn more about these features?
- Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and unhandled rejections. If you have something that looks like an exception, Sentry can capture it.
- Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back.
- Logs: Centralize and analyze your application logs to correlate them with errors and performance issues. Search, filter, and visualize log data to understand what's happening in your applications.
Run the command for your preferred package manager to add the Sentry SDK to your application:
npminstall @sentry/cloudflare--saveThe main Sentry configuration should happen as early as possible in your app's lifecycle.
Since the SDK needs access to theAsyncLocalStorage API, you need to set thenodejs_compat compatibility flag in yourwrangler.(jsonc|toml) configuration file:
wrangler.jsonc{ "compatibility_flags": ["nodejs_compat"],}If you don't set therelease 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 theCF_VERSION_METADATA binding in your wrangler configuration. This provides access to theCloudflare version metadata:
Using an SDK version before 10.35.0?
In earlier versions, you need to manually extractCF_VERSION_METADATA.id and pass it as therelease option:
Sentry.withSentry((env)=>({dsn:"___PUBLIC_DSN___",release: env.CF_VERSION_METADATA?.id,}),// ...);wrangler.jsonc{ // ... "version_metadata": { "binding": "CF_VERSION_METADATA" }}Wrap your worker handler with thewithSentry function, for example, in yourindex.ts file, to initialize the Sentry SDK and hook into the environment:
index.tsimport*as Sentryfrom"@sentry/cloudflare";exportdefault Sentry.withSentry((env: Env)=>({ dsn:"___PUBLIC_DSN___",// Adds request headers and IP for users, for more info visit:// https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#sendDefaultPii sendDefaultPii:true,// ___PRODUCT_OPTION_START___ logs// Enable logs to be sent to Sentry enableLogs:true,// ___PRODUCT_OPTION_END___ logs// ___PRODUCT_OPTION_START___ performance// Set tracesSampleRate to 1.0 to capture 100% of spans for tracing.// Learn more at// https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#tracesSampleRate tracesSampleRate:1.0,// ___PRODUCT_OPTION_END___ performance}),{asyncfetch(request, env, ctx){// Your worker logic herereturnnewResponse("Hello World!");},},);To use the Sentry SDK, add thesentryPagesPlugin asmiddleware to your Cloudflare Pages application.
Create a_middleware.js file in yourfunctions directory (Cloudflare Pagesmiddleware). Create the directory in the root of your project if it doesn't already exist, then create the file and import and initialize the Sentry Cloudflare SDK:
functions/_middleware.jsimport*asSentryfrom"@sentry/cloudflare";exportconst onRequest=[// Make sure Sentry is the first middlewareSentry.sentryPagesPlugin((context)=>({dsn:"___PUBLIC_DSN___",// Adds request headers and IP for users, for more info visit:// https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#sendDefaultPiisendDefaultPii:true,// ___PRODUCT_OPTION_START___ logs// Enable logs to be sent to SentryenableLogs:true,// ___PRODUCT_OPTION_END___ logs// ___PRODUCT_OPTION_START___ performance// Set tracesSampleRate to 1.0 to capture 100% of spans for tracing.// Learn more at// https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#tracesSampleRatetracesSampleRate:1.0,// ___PRODUCT_OPTION_END___ performance})),// Add more middlewares here];Don't have access to onRequest?
If you don't have access to theonRequest middleware API, you can use thewrapRequestHandler API instead. For example:
// hooks.server.jsimport*asSentryfrom"@sentry/cloudflare";exportconsthandle=({ event, resolve})=>{const requestHandlerOptions={options:{dsn: event.platform.env.SENTRY_DSN,tracesSampleRate:1.0,},request: event.request,context: event.platform.ctx,};returnSentry.wrapRequestHandler(requestHandlerOptions,()=>resolve(event),);};The stack traces in your Sentry errors probably won't look like your actual code without unminifying them. To fix this, upload yoursource maps to Sentry.
First, set theupload_source_maps option totrue in yourwrangler.(jsonc|toml) config file to enable source map uploading:
wrangler.jsonc{ "upload_source_maps": true,}Next, run the Sentry Wizard to finish your setup:
npx @sentry/wizard@latest-i sourcemapsLet's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
First, let's make sure Sentry is correctly capturing errors and creating issues in your project.
Add the following code snippet to your main worker file to create a/debug-sentry route that triggers an error when called:
index.jsexportdefault{asyncfetch(request){const url=newURL(request.url);if(url.pathname==="/debug-sentry"){thrownewError("My first Sentry error!");}// Your existing routes and logic here...returnnewResponse("...");},};Create a new route that throws an error when called by adding the following code snippet to a file in yourfunctions directory, such asfunctions/debug-sentry.js:
debug-sentry.jsexportasyncfunctiononRequest(context){thrownewError("My first Sentry error!");}To test your tracing configuration, update the previous code snippet by starting a trace to measure the time it takes to run your code.
index.jsexportdefault{asyncfetch(request){const url=newURL(request.url);if(url.pathname==="/debug-sentry"){awaitSentry.startSpan({op:"test",name:"My First Test Transaction",},async()=>{awaitnewPromise((resolve)=>setTimeout(resolve,100));// Wait for 100msthrownewError("My first Sentry error!");},);}// Your existing routes and logic here...returnnewResponse("...");},};debug-sentry.jsexportasyncfunctiononRequest(context){awaitSentry.startSpan({op:"test",name:"My First Test Transaction",},async()=>{awaitnewPromise((resolve)=>setTimeout(resolve,100));// Wait for 100msthrownewError("My first Sentry error!");},);}Now, head over to your project onSentry.io to view the collected data (it takes a couple of moments for the data to appear).
Need help locating the captured errors in your Sentry project?
- Open theIssues page and select an error from the issues list to view the full details and context of this error. For more details, see thisinteractive walkthrough.
- Open theTraces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, clickhere.
- Open theLogs page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, clickhere.
Server-side spans will display0ms for their durations. In the Cloudflare Workers runtime,performance.now() andDate.now() only advance after I/O occurs. CPU-bound operations will show zero duration. This is a security measure Cloudflare implements tomitigate 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.
At this point, you should have integrated Sentry and should already be sending data to your Sentry project.
Now's a good time to customize your setup and look into more advanced topics. Our next recommended steps for you are:
- Explorepractical guides on what to monitor, log, track, and investigate after setup
- Learn how tomanually capture errors
- Continue tocustomize your configuration
- Make use ofCloudflare-specific features
- Get familiar withSentry's product features like tracing, insights, and alerts
Are you having problems setting up the SDK?
- Check out setup instructions for popularframeworks on Cloudflare
- Find various support topics introubleshooting
- Get support
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").