boltZharp Docs
cloudSDKs

Cloudflare Workers

@zharp/cloudflare traces every request your Worker, Hono app, Durable Object or Pages Function handles, carries the trace on to your API, and sends its errors and failed D1 queries with readable stacks.

info
@zharp/cloudflare 0.1.0

This SDK is new, and its API may still change before 1.0. Requires the nodejs_compat flag, which is on by default for compatibility dates from 2026-08-01.

One wrapper around what your Worker exports. Each fetch, cron trigger, queue batch, Durable Object alarm and RPC call is one span (SERVER, or CONSUMER for a queue batch). A traceparent that comes in is continued and one is added to every outgoing fetch, so browser → Worker → your origin API reads as one trace; service bindings and Durable Object stubs carry it on to the next Worker. What it captures:

  • Errors, each counted once — including work you handed to ctx.waitUntil that failed after the response went out.
  • Request and response headers, with secrets recorded as [Filtered].
  • Cloudflare's own details on the request's span: cf-ray, the client's IP and country, and the colo that served it.
  • D1 queries as spans; a failed query is reported with its SQL and the line of your code that ran it.
  • KV, R2 and Queue sends as spans.
  • Logs: off by default, since Cloudflare's Workers Logs keeps them already — see Logs.

Quickest setup

In your project, run the setup. It opens a page to pick the Zharp app, installs the package, wraps your Worker's default export (or adds the Pages middleware), adds what's missing to your Wrangler config, puts the key in .dev.vars and changes the deploy script to upload source maps. It shows every change before making it, and prints the one command that puts the key in production.

npm init zharp@latest

The rest of this page is what it sets up, by hand.

Install

npm i @zharp/cloudflare

Workers

Wrap the default export:

// src/index.ts
import { withZharp } from '@zharp/cloudflare';

export default withZharp({
  async fetch(request, env, ctx) {
    return new Response('Hello');
  },
} satisfies ExportedHandler<Env>);

scheduled, queue and the other handlers on the same object are wrapped too. Then add your key as a secret, from the app's settings in Zharp:

npx wrangler secret put ZHARP_KEY   # paste the app's key (zpk_…)
# .dev.vars, for wrangler dev (keep it out of git)
ZHARP_KEY=zpk_…

and these to your Wrangler config:

// wrangler.jsonc
{
  "compatibility_flags": ["nodejs_compat"],
  "upload_source_maps": true,
  "version_metadata": { "binding": "CF_VERSION_METADATA" },
  "vars": { "ZHARP_SERVICE": "checkout-worker" }
}
  • nodejs_compat gives the SDK AsyncLocalStorage. It's on by default for compatibility dates from 2026-08-01; add the flag for older ones.
  • upload_source_maps makes Wrangler write source maps — see Readable stack traces.
  • The version binding gives each deploy a release when you don't set ZHARP_RELEASE.

Without a key the Worker runs as before and nothing is sent. The app's setup page in Zharp shows these steps with the key, service and environment filled in.

Hono

import { Hono } from 'hono';
import { withZharp } from '@zharp/cloudflare';

const app = new Hono();

app.get('/users/:id', async (c) => c.json(await getUser(c.env.DB, c.req.param('id'))));

export default withZharp(app);

Spans are named by the matched route (GET /users/:id), not the URL. Errors Hono turns into a 500 are reported; HTTPExceptions under 500 are answers you chose, so they aren't. The key and config are as for Workers.

Durable Objects

Export the wrapped class under the name your Wrangler config uses:

import { DurableObject } from 'cloudflare:workers';
import { instrumentDurableObject, withZharp } from '@zharp/cloudflare';

export class CartObject extends DurableObject {
  async add(item: string) {
    // …
  }
}

export const Cart = instrumentDurableObject(CartObject);

export default withZharp({ async fetch(request, env) { /* … */ } } satisfies ExportedHandler<Env>);
// wrangler.jsonc: class_name stays the exported name
"durable_objects": {
  "bindings": [{ "name": "CART", "class_name": "Cart" }]
}

Each fetch, RPC method, alarm and WebSocket message is a span, in the trace of the Worker that called it, and its errors are reported.

Pages Functions

// functions/_middleware.ts
import { zharpPagesPlugin } from '@zharp/cloudflare';

export const onRequest = zharpPagesPlugin();

// with a middleware of your own: Zharp first
// export const onRequest = [zharpPagesPlugin(), yourMiddleware];

Every request through your Functions is a span, with errors reported and D1, KV and R2 calls traced. The key is a Pages secret:

npx wrangler pages secret put ZHARP_KEY

Its service name defaults to pages; set ZHARP_SERVICE in the project's variables to name it.

Logs

Off by default: Cloudflare's Workers Logs already keeps your console output. To have Zharp keep it too, each line linked to its request's trace:

// wrangler.jsonc
"vars": { "ZHARP_LOGS": "true" }

Zharp.log is always sent.

Logs only

If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests. A request from a Zharp front end is still read, so its logs keep the caller's user, session and trace ID.

import { withZharp } from "@zharp/cloudflare";

export default withZharp((env) => ({ key: env.ZHARP_KEY, tracing: false, logs: true }), handler);

Or leave the code as it is and set ZHARP_TRACING=false ZHARP_LOGS=true in the environment.

The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.

Errors

What a handler throws is reported once, on its span, with its type, message and stack — not again by a framework's error hook or by console.error(err). A promise you passed to ctx.waitUntil that rejects is reported too. Report one yourself:

import { Zharp } from '@zharp/cloudflare';

try {
  await charge(order);
} catch (err) {
  Zharp.captureError(err, { 'order.id': order.id });   // reported as handled, in this request's trace
  return new Response('Payment failed', { status: 402 });
}

Readable stack traces

Wrangler bundles and minifies your Worker, so a stack points into index.js. Keep the build, file it under the commit as the release, and upload its source maps; errors from that release then show your own files and lines, with the code around each frame:

// package.json
"scripts": {
  "deploy": "wrangler deploy --outdir .wrangler/zharp-dist --var ZHARP_RELEASE:$(git rev-parse --short HEAD) && npx @zharp/cli sourcemaps upload .wrangler/zharp-dist --release $(git rev-parse --short HEAD) --app 42"
}

42 is the app's ID, the number in its dashboard URL. Run it with ZHARP_AUTH_TOKEN in the environment: a workspace key with the artifacts:write scope — see The upload key. Maps are matched by release, so the ZHARP_RELEASE the Worker reports has to be the one you uploaded under, as here. Projects built with Cloudflare's Vite plugin can use @zharp/vite-plugin instead.

Tracing

Built on @opentelemetry/api, so spans other libraries make with OpenTelemetry join the trace. Add your own with Zharp.startSpan. ZHARP_SAMPLE_RATE keeps a share of traces; a request that arrives with a traceparent keeps its caller's decision, and errors are always sent.

Request and response headers

Every request and response header is recorded on the request's span. Secret ones — authorization, cookies, API keys, tokens, sessions — are recorded as [Filtered]. Name more to hide, or turn it off:

withZharp((env) => ({ captureHeaders: { redact: ['x-tenant'] } }), handler);   // filter more names
// or ZHARP_CAPTURE_HEADERS=false to turn them off

D1, KV, R2 and Queues

Each D1 query (run, all, first, raw, batch) is a span with its statement. A query that fails is reported once, with the SQL and the line of your code that ran it. KV reads and writes, R2 calls and Queue sends are spans too.

User context

Requests from the Zharp browser and mobile SDKs carry the user and session in baggage, and every span, log and error of the request gets them with no code. When the Worker knows the user better:

Zharp.setUser({ id: user.id, email: user.email, name: user.name });

The API

import { Zharp } from '@zharp/cloudflare';

Zharp.captureError(err, { 'order.id': 42 });        // an error you caught, as a handled error
Zharp.setUser({ id: user.id, email: user.email });  // on the request's spans, logs and errors
Zharp.setTag('tenant', 'acme');                     // on the request's spans, logs and errors
Zharp.log.info('order paid', { 'order.id': 42 });   // also warn, error…: sent whatever ZHARP_LOGS says
await Zharp.startSpan('render invoice', () => render(order));  // a span around some work
await Zharp.flush();                                // send now (the wrappers do this per request)
Zharp.traceId;                                      // the active trace, e.g. for an error page

Inside a request, tags and the user belong to that request only.

Options

Every setting can be a Worker variable or secret, which is where they usually live. To set them in code, pass a function of env before the handler; what you pass wins:

export default withZharp(
  (env) => ({ key: env.ZHARP_KEY, environment: 'production' }),
  handler,
);
In codeVariableDefault
keyZHARP_KEY— nothing is sent without one
serviceZHARP_SERVICEworker (Pages Functions: pages)
environmentZHARP_ENVIRONMENT—
releaseZHARP_RELEASEthe deployed version's ID, from CF_VERSION_METADATA
logsZHARP_LOGSfalse. See Logs.
sampleRateZHARP_SAMPLE_RATE1 (errors are always sent)
tracingZHARP_TRACINGtrue; false sends errors and logs only
captureHeadersZHARP_CAPTURE_HEADERSon; { redact: [...] } filters more names
endpointZHARP_ENDPOINThttps://api.zharp.io/api/v1/otlp
captureQueryErrors—true: failed D1 queries reported with their SQL
ignoreUrls—outgoing requests left without a span or traceparent (a host, a URL prefix or a RegExp)
—ZHARP_DISABLED=trueturns everything off

Requirements

  • nodejs_compat, or a compatibility date of 2026-08-01 or later, where it's on by default.
  • About 30 KB minified, well inside a Worker's size limit.
  • Workers, Durable Objects, Hono and Pages Functions; Wrangler for deploys.

Frameworks on Workers

React Router, Astro, SvelteKit, Nuxt and Next.js (through OpenNext) each build a Cloudflare worker entry with their adapter. Wrap that entry's default export with withZharp:

// the worker entry your framework's Cloudflare adapter builds from
import { withZharp } from '@zharp/cloudflare';
import handler from './the-adapters-entry';

export default withZharp(handler);

Their browser halves have their own setup on the Browser page. We're checking these frameworks one by one; where an adapter needs more than this, it will be listed here.

Cloudflare's own export

Cloudflare can also send a Worker's traces and logs to Zharp by itself, with no code — but without errors as issues, readable stacks or a trace that crosses into your API. See Cloudflare's own export; both can run together.

Troubleshooting

Nothing arrives

On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:

  • Is init called, and before the code you expect to see? Without a key, the SDK starts nothing and says so once.
  • Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key, service decides the app — see Keys.
  • Data is sent in batches every few seconds. A process that exits straight away should call flush first.
  • Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
  • Is the key a secret of this Worker (npx wrangler secret list), and in .dev.vars for wrangler dev?
  • No such module "node:async_hooks": the Worker needs nodejs_compat in compatibility_flags, or a compatibility date of 2026-08-01 or later.
  • Stacks still point into index.js? The release the Worker reports must be the one the maps were uploaded under: deploy with --var ZHARP_RELEASE:… as above.

401 or 403

Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.