npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sentry/cloudflare

v8.47.0

Published

Official Sentry SDK for Cloudflare Workers and Pages

Downloads

35,900

Readme

Official Sentry SDK for Cloudflare

npm version npm dm npm dt

Links

Install

To get started, first install the @sentry/cloudflare package:

npm install @sentry/cloudflare

Then set either the nodejs_compat or nodejs_als compatibility flags in your wrangler.toml. This is because the SDK needs access to the AsyncLocalStorage API to work correctly.

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

Then you can either setup up the SDK for Cloudflare Pages or Cloudflare Workers.

Setup (Cloudflare Pages)

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

We recommend adding a functions/_middleware.js for the middleware setup so that Sentry is initialized for your entire app.

// functions/_middleware.js
import * as Sentry from '@sentry/cloudflare';

export const onRequest = Sentry.sentryPagesPlugin({
  dsn: process.env.SENTRY_DSN,
  // Set tracesSampleRate to 1.0 to capture 100% of spans for tracing.
  tracesSampleRate: 1.0,
});

If you need to to chain multiple middlewares, you can do so by exporting an array of middlewares. Make sure the Sentry middleware is the first one in the array.

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

export const onRequest = [
  // Make sure Sentry is the first middleware
  Sentry.sentryPagesPlugin({
    dsn: process.env.SENTRY_DSN,
    tracesSampleRate: 1.0,
  }),
  // Add more middlewares here
];

If you need to access the context object (for example to grab environmental variables), you can pass a function to sentryPagesPlugin that takes the context object as an argument and returns init options:

export const onRequest = Sentry.sentryPagesPlugin(context => ({
  dsn: context.env.SENTRY_DSN,
  tracesSampleRate: 1.0,
}));

If you do not have access to the onRequest middleware API, you can use the wrapRequestHandler API instead.

Here is an example with SvelteKit:

// 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));
};

Setup (Cloudflare Workers)

To use this SDK, wrap your handler with the withSentry function. This will initialize the SDK and hook into the environment. Note that you can turn off almost all side effects using the respective options.

Currently only ESM handlers are supported.

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

export default withSentry(
  env => ({
    dsn: env.SENTRY_DSN,
    // Set tracesSampleRate to 1.0 to capture 100% of spans for tracing.
    tracesSampleRate: 1.0,
  }),
  {
    async fetch(request, env, ctx) {
      return new Response('Hello World!');
    },
  } satisfies ExportedHandler<Env>,
);

Sourcemaps

Configure uploading sourcemaps via the Sentry Wizard:

npx @sentry/wizard@latest -i sourcemaps

See more details in our docs.

Usage

To set context information or send manual events, use the exported functions of @sentry/cloudflare. Note that these functions will require the usage of the Sentry helpers, either withSentry function for Cloudflare Workers or the sentryPagesPlugin middleware for Cloudflare Pages.

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

// Set user information, as well as tags and further extras
Sentry.setExtra('battery', 0.7);
Sentry.setTag('user_mode', 'admin');
Sentry.setUser({ id: '4711' });

// Add a breadcrumb for future events
Sentry.addBreadcrumb({
  message: 'My Breadcrumb',
  // ...
});

// Capture exceptions, messages or manual events
Sentry.captureMessage('Hello, world!');
Sentry.captureException(new Error('Good bye'));
Sentry.captureEvent({
  message: 'Manual',
  stacktrace: [
    // ...
  ],
});

Cloudflare D1 Instrumentation

You can use the instrumentD1WithSentry method to instrument Cloudflare D1, Cloudflare's serverless SQL database with Sentry.

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

// env.DB is the D1 DB binding configured in your `wrangler.toml`
const db = Sentry.instrumentD1WithSentry(env.DB);
// Now you can use the database as usual
await db.prepare('SELECT * FROM table WHERE id = ?').bind(1).run();

Cron Monitoring (Cloudflare Workers)

Sentry Crons allows you to monitor the uptime and performance of any scheduled, recurring job in your application.

To instrument your cron triggers, use the Sentry.withMonitor API in your Scheduled handler.

export default {
  async scheduled(event, env, ctx) {
    ctx.waitUntil(
      Sentry.withMonitor('your-cron-name', () => {
        return doSomeTaskOnASchedule();
      }),
    );
  },
};

You can also use supply a monitor config to upsert cron monitors with additional metadata:

const monitorConfig = {
  schedule: {
    type: 'crontab',
    value: '* * * * *',
  },
  checkinMargin: 2, // In minutes. Optional.
  maxRuntime: 10, // In minutes. Optional.
  timezone: 'America/Los_Angeles', // Optional.
};

export default {
  async scheduled(event, env, ctx) {
    Sentry.withMonitor('your-cron-name', () => doSomeTaskOnASchedule(), monitorConfig);
  },
};