Hono on Cloudflare
Learn how to instrument your Hono app on Cloudflare Workers and capture your first errors with Sentry.
Choose the features you want to configure, and this guide will show you how:
Run the command for your preferred package manager to add the Sentry SDK to your application:
npm install @sentry/cloudflare --save
The main Sentry configuration should happen as early as possible in your app's lifecycle.
Since the SDK needs access to the AsyncLocalStorage
API, you need to set either the nodejs_compat
or nodejs_als
compatibility flags in your wrangler.(jsonc|toml)
configuration file:
wrangler.jsonc
{
"compatibility_flags": [
"nodejs_als",
// "nodejs_compat"
],
}
Additionally, add the CF_VERSION_METADATA
binding in the same file:
wrangler.jsonc
{
// ...
"version_metadata": {
"binding": "CF_VERSION_METADATA",
},
}
Wrap your worker handler with the withSentry
function, for example, in your index.ts
file, to initialize the Sentry SDK and hook into the environment:
index.ts
import { Hono, HTTPException } from "hono";
import * as Sentry from "@sentry/cloudflare";
export default Sentry.withSentry(
(env: Env) => {
const { id: versionId } = env.CF_VERSION_METADATA;
return {
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0example-org / example-project",
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,
// logs
// Enable logs to be sent to Sentry
enableLogs: true,
// logs
// 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,
// performance
};
},
// your existing worker export
app,
);
Next, bind an onError
hook to report unhandled exceptions to Sentry:
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("/", () => {
// ...
});
The stack traces in your Sentry errors probably won't look like your actual code. To fix this, upload your source maps to Sentry. The easiest way to do this is by using the Sentry Wizard:
npx @sentry/wizard@latest -i sourcemaps
First, let's verify that Sentry captures errors and creates issues in your Sentry project. Add the following code snippet to your main application file, adding a route that triggers an error that Sentry will capture:
app.get("/debug-sentry", () => {
throw new Error("My first Sentry error!");
});
To test your tracing configuration, update the previous code snippet by starting a trace to measure the time it takes for the execution of your code:
app.get("/debug-sentry", async () => {
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!");
},
);
});
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:
- Learn how to manually capture errors
- Continue to customize your configuration
- Make use of Cloudflare-specific features
- Get familiar with Sentry's product features like tracing, insights, and alerts
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").