Cloudflare Workers

BugSnag can automatically report unhandled errors and capture useful metadata in Cloudflare Workers.

Installation

Install and configure @bugsnag/js, then install the Cloudflare Workers plugin using npm or yarn:

npm install --save @bugsnag/plugin-cloudflare-workers
# or
yarn add @bugsnag/plugin-cloudflare-workers

Wrangler Configuration

Add the nodejs_compat compatibility flag to your wrangler.jsonc or wrangler.toml configuration file:

{
  "compatibility_flags": ["nodejs_compat"]
}
compatibility_flags = [ "nodejs_compat" ]

Usage

To start BugSnag with the Cloudflare Workers integration, pass the plugin to Bugsnag.start along with the Hono plugin:

import Bugsnag from '@bugsnag/js'
import BugsnagPluginCloudflareWorkers from '@bugsnag/plugin-cloudflare-workers'
import BugsnagPluginHono from '@bugsnag/plugin-hono'

Bugsnag.start({
  apiKey: 'YOUR_API_KEY',
  plugins: [BugsnagPluginCloudflareWorkers, BugsnagPluginHono],
  otherOptions: value
})

In the part of your application where the Hono app is configured, obtain and use the Hono middleware:

const app = new Hono()
const middleware = Bugsnag.getPlugin('hono')

// This must be the first piece of middleware in the stack.
// It can only capture errors in downstream middleware

app.use(middleware.requestHandler)

// This handles any errors that Hono catches
app.use(middleware.errorHandler)

/* all other middleware and application routes go here */

Finally, start handling errors in your Hono app by wrapping app.fetch with BugSnag’s Cloudflare Workers handler:

const bugsnagHandler =  Bugsnag.getPlugin('cloudflareWorkers')!.createHandler()

export default {
  fetch: bugsnagHandler(app.fetch)
}

Session tracking

A session will be reported automatically each time your fetch handler is called.

This behavior can be disabled using the autoTrackSessions configuration option.

Configuration

The BugSnag Cloudflare Workers plugin can be configured by passing options to createHandler.

flushTimeoutMs

BugSnag will wait for events and sessions to be delivered before allowing the handler function to exit. This option can be used to control the maximum amount of time to wait before timing out.

By default, BugSnag will timeout after 2000 milliseconds.

const bugsnagHandler = Bugsnag.getPlugin('cloudflareWorkers')!.createHandler({
  flushTimeoutMs: 5000
})

If a timeout does occur, BugSnag will log a warning and events & sessions may not be delivered.