Hono on Cloudflare

Learn how to add Cloudflare instrumentation to your Hono app.

This guide explains how to set up Sentry in your Hono application running on Cloudflare Workers.

Copied
npm install @sentry/cloudflare --save

Configuration should happen as early as possible in your application's lifecycle.

To use the SDK, you'll need to set either the nodejs_compat or nodejs_als compatibility flags in your wrangler.jsonc / wrangler.toml config. This is because the SDK needs access to the AsyncLocalStorage API to work correctly.

wrangler.jsonc
Copied
{
  "compatibility_flags": [
    "nodejs_als",
    // "nodejs_compat"
  ],
}

You will also want to add the CF_VERSION_METADATA binding:

wrangler.jsonc
Copied
{
  // ...
  "version_metadata": {
    "binding": "CF_VERSION_METADATA"
  },
}

Wrap your worker 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.

index.ts
Copied
import { Hono, HTTPException } from "hono";
import * as Sentry from "@sentry/cloudflare";

export default Sentry.withSentry(
  (env) => {
    const { id: versionId } = env.CF_VERSION_METADATA;

    return {
      dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

      release: versionId,

      // Adds request headers and IP for users, for more info visit:
      // https://docs.sentry.io/platforms/javascript/guides/cloudflare/configuration/options/#sendDefaultPii
      sendDefaultPii: true,

      //  performance
      // Set tracesSampleRate to 1.0 to capture 100% of spans for tracing.
      // Learn more at
      // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
      tracesSampleRate: 1.0,
      //  performance
    };
  },
  // your existing worker export
  app,
);

Now bind an onError hook to report unhandled exceptions to Sentry:

Copied
const app = new Hono()
  // Add an onError hook to report unhandled exceptions to Sentry.
  .onError((err, c) => {
    // Report _all_ unhandled errors.
    Sentry.captureException(err);
    if (err instanceof HTTPException) {
      return err.getResponse();
    }
    // Or just report errors which are not instances of HTTPException
    // Sentry.captureException(err);
    return c.json({ error: "Internal server error" }, 500);
  })

  // Bind global context via Hono middleware
  .use((c, next) => {
    Sentry.setUser({
      email: c.session.user.email,
    });

    Sentry.setTag("project_id", c.session.projectId);

    return next();
  })

  // Your routes...
  .get("/", () => {
    // ...
  });

This snippet includes an intentional error, so you can test that everything is working as soon as you set it up.

Copied
app.get("/debug-sentry", async (c) => {
  throw new Error("My first Sentry error!");
});

To view and resolve the recorded error, log into sentry.io and select your project. Clicking on the error's title will open a page where you can see detailed information and mark it as resolved.

Was this helpful?
Help improve this content
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").