Skip to content

Latest commit

 

History

History
244 lines (176 loc) · 7.97 KB

File metadata and controls

244 lines (176 loc) · 7.97 KB
title Cloudflare
description Learn how to manually set up Sentry for Cloudflare Workers and Cloudflare Pages and capture your first errors.
sdk sentry.javascript.cloudflare
categories
javascript
server
server-edge
serverless

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. See [Known Limitations](#known-limitations) for details.

Step 1: Install

Choose the features you want to configure, and this guide will show you how:

<OnboardingOptionButtons options={["error-monitoring", "performance", "logs"]} />

Install the Sentry SDK

Run the command for your preferred package manager to add the Sentry SDK to your application:

Step 2: Configure

The main Sentry configuration should happen as early as possible in your app's lifecycle.

Wrangler Configuration

Setup for Cloudflare Workers

Setup for Cloudflare Pages

To use the Sentry SDK, add the sentryPagesPlugin as middleware to your Cloudflare Pages application.

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

export const onRequest = [
  // Make sure Sentry is the first middleware
  Sentry.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/#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
  })),
  // Add more middlewares here
];
If you don't have access to the `onRequest` middleware API, you can use the `wrapRequestHandler` API instead. For example:
// hooks.server.js
import * as Sentry from "@sentry/cloudflare";

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

Step 3: Add Readable Stack Traces With Source Maps (Optional)

Step 4: Verify Your Setup

Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.

Issues

First, let's make sure Sentry is correctly capturing errors and creating issues in your project.

Cloudflare Workers

Add the following code snippet to your main worker file to create a /debug-sentry route that triggers an error when called:

export default {
  async fetch(request) {
    const url = new URL(request.url);

    if (url.pathname === "/debug-sentry") {
      throw new Error("My first Sentry error!");
    }

    // Your existing routes and logic here...
    return new Response("...");
  },
};

Cloudflare Pages

Create a new route that throws an error when called by adding the following code snippet to a file in your functions directory, such as functions/debug-sentry.js:

export async function onRequest(context) {
  throw new Error("My first Sentry error!");
}
### Tracing To test your tracing configuration, update the previous code snippet by starting a trace to measure the time it takes to run your code.

Cloudflare Workers

export default {
  async fetch(request) {
    const url = new URL(request.url);

    if (url.pathname === "/debug-sentry") {
      await Sentry.startSpan(
        {
          op: "test",
          name: "My First Test Transaction",
        },
        async () => {
          await new Promise((resolve) => setTimeout(resolve, 100)); // Wait for 100ms
          throw new Error("My first Sentry error!");
        }
      );
    }

    // Your existing routes and logic here...
    return new Response("...");
  },
};

Cloudflare Pages

export async function onRequest(context) {
  await Sentry.startSpan(
    {
      op: "test",
      name: "My First Test Transaction",
    },
    async () => {
      await new Promise((resolve) => setTimeout(resolve, 100)); // Wait for 100ms
      throw new Error("My first Sentry error!");
    }
  );
}

View Captured Data in Sentry

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

Known Limitations

Span Durations

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.

Next Steps

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: