A Cloudflare Worker is harder to trace than a server process for two reasons. It has no long-lived process, so nothing exports spans in the background unless you ask the runtime to wait. And it ships as one bundled file, so an error's stack trace names a position in index.js, not the file you wrote.
This guide is for a Worker written in plain TypeScript or JavaScript and deployed with wrangler deploy. It covers the native OTLP export, the OpenTelemetry JS SDK, and source maps. The examples send to Maple, but the tracing code is plain OpenTelemetry and works with any OTLP endpoint.
Using Effect and Alchemy?
A Worker written with Effect and deployed with Alchemy needs less code than this. See Effect and Alchemy on Cloudflare Workers: OpenTelemetry tracing.
Key takeaways
- Spans leave a Worker in one of two ways: Cloudflare's native OTLP export, or an SDK in your code that you flush with
ctx.waitUntil. - The native export is configured in two places: destinations in the Cloudflare dashboard, and an
observabilityblock in the Wrangler config. - With an SDK, register a context manager, or child spans become separate traces.
- Cloudflare's
upload_source_mapsonly remaps stacks in Cloudflare's own logs. The stack your telemetry sends still points at the bundle. - Your tracing backend needs its own copy of the map. Maple finds it by service, release and file path.
- Set
service.versionon the Worker to the release you upload the maps under. The git commit works for both. - Keep each map under 10 MiB. Removing
sourcesContentis usually enough.
Two ways to trace a Cloudflare Worker
A trace needs spans, and something has to record them and send them. On Workers there are two sources. The runtime can record spans itself, or your code can record them with an OpenTelemetry SDK. Both send OTLP over HTTP, and one Worker can use both.
| Native OTLP export | OpenTelemetry JS SDK | |
|---|---|---|
| Code changes | None | A tracer provider and a wrapped handler |
| Spans you get | Handler, outbound fetch, binding calls and RPC, plus custom spans through Cloudflare's tracing API | The ones your code opens |
| Logs | console output and invocation logs | Not covered in this guide |
| Flush | Handled by the runtime | ctx.waitUntil(provider.forceFlush()) |
service.version you control | Not verified | Yes, on the resource |
| Error stack on the span | Not verified | Yes, with recordException |
Start with the native export if you want to see requests and subrequests today. It can carry your own spans too. Add the SDK when you need a service.version you set yourself and errors recorded with their stack, which is what source maps need. The next two sections set up each one.
Set up Cloudflare's native OTLP export
Workers Observability can export a Worker's traces and logs to any OTLP endpoint. The runtime records the spans, so there is no SDK to install and no flush to get right. You get a span for each fetch, scheduled and queue invocation, for each outbound fetch call and for each binding call such as KV, R2 and Durable Objects, plus console output as logs. Metrics are not exported this way.
You need:
- Wrangler 4.35.0 or later. That is the first release whose config schema has
observability.tracesanddestinations. We found it by checking the schema of each published release, not from Cloudflare's docs. - A private ingest key, which starts with
maple_sk_, from Settings → Ingestion in Maple.
Cloudflare's export docs name no plan requirement, as of November 29, 2026. What costs money is the copy Cloudflare keeps. From December 1, 2026, Workers logs and traces that Cloudflare stores count toward the account's Observability ingestion and storage usage, on Free and Paid plans. The allowances and rates are on Cloudflare's pricing page. Setting persist to false, shown below, exports without storing that copy.
Create the OTLP destinations in the Cloudflare dashboard
A destination is a named OTLP endpoint with its headers. It carries one signal, so you create two: one for traces and one for logs.
- In the Cloudflare dashboard, go to Observability → Destinations. This is at the account level, not inside a Worker.
- Select Add destination, fill in the traces column below, and select Save.
- Select Add destination again, fill in the logs column, and select Save.
| Field | Traces destination | Logs destination |
|---|---|---|
| Destination name | maple-traces | maple-logs |
| Destination type | Traces | Logs |
| OTLP endpoint | https://ingest.maple.dev/v1/traces | https://ingest.maple.dev/v1/logs |
| Custom headers | Authorization: Bearer YOUR_INGEST_KEY | |
Cloudflare sends a test export with those headers before it saves the destination. A wrong key or endpoint fails here, at save, not later.
An EU organization uses the EU host in both destinations: https://ingest.eu.maple.dev/v1/traces and https://ingest.eu.maple.dev/v1/logs. A key from one region is refused by the other.
Destinations belong to the Cloudflare account, not to one Worker. You create these two once, and every Worker in the account can reference them by name.
Reference them in wrangler.jsonc or wrangler.toml
Creating a destination sends nothing by itself. Each Worker opts in with an observability block in its Wrangler config. The names in destinations must match the destination names exactly.
wrangler.jsonc
// wrangler.jsonc
{
"observability": {
"traces": {
"enabled": true,
"destinations": ["maple-traces"]
},
"logs": {
"enabled": true,
"destinations": ["maple-logs"]
}
}
} The same in TOML:
wrangler.toml
# wrangler.toml
[observability.traces]
enabled = true
destinations = ["maple-traces"]
[observability.logs]
enabled = true
destinations = ["maple-logs"] Then redeploy. Cloudflare says events may take several minutes to reach the destination.
npx wrangler deploy
Both blocks also take head_sampling_rate, the share of invocations to record from 0 to 1, and persist. Setting persist to false sends the data only to your destination and not to Cloudflare's own dashboard.
"traces": {
"enabled": true,
"destinations": ["maple-traces"],
"head_sampling_rate": 0.1,
"persist": false
} To check it, send a few requests, wait a few minutes and open Explore → Traces in Maple. Cloudflare names the service after the Worker script. The native export docs list every span and attribute you get.
When nothing arrives
| Symptom | Cause |
|---|---|
| The destination's status is Never run | Cloudflare has delivered nothing yet. A name in destinations does not match the dashboard exactly, the Worker was not redeployed after the change, it has had no traffic, the sampling rate is too low, or Wrangler is older than 4.35.0 and does not know the traces and destinations keys |
| The destination's status is Error, or saving it fails | Cloudflare could not deliver. The endpoint is wrong, the key is wrong or belongs to the other region, or the header value is not Bearer followed by the key. Maple's ingest answers 401 for a bad key |
| Traces arrive but logs do not, or the reverse | A destination's type does not match its path: Traces goes with /v1/traces, Logs with /v1/logs |
Custom spans without an SDK
The native export is not limited to the spans the runtime records. Cloudflare documents a tracing API for your own spans: import { tracing } from "cloudflare:workers", or ctx.tracing in a handler. tracing.enterSpan(name, callback) opens a span that ends when the callback returns or its promise settles. startActiveSpan, startSpan and getActiveSpan cover manual cases. A custom span nests under the active span, and fetch and binding calls made inside it become its children. Spans take attributes, a status and recordException.
Custom spans need observability.traces.enabled set to true. Cloudflare's page names no compatibility date, but Alchemy's source treats 2026-07-28 as the earliest date that has tracing.startActiveSpan, and the config in this guide uses 2025-09-01. Use a recent compatibility_date before you try it.
Cloudflare documents that recordException with an Error records its name, message and stack on an event that appears in OpenTelemetry exports. Workers tracing is in open beta. We have not run custom spans against Maple, so the attribute names on arrival are not verified. If spans for your own logic are all you need, try it before adding an SDK.
What the native export does not do
Its limits, as of this writing:
- Traces stop at the Worker. Cloudflare says trace IDs are not propagated to services outside of Cloudflare, so a backend the Worker calls starts its own trace.
- Some spans show 0 ms. The runtime only advances the clock on I/O, as a Spectre mitigation, so pure CPU work between two I/O calls has no duration.
- Any non-2xx response is an error span. That includes a 404 from a bot. Maple opens no error issue for a 4xx span with no exception attached, so this stays out of the issue list.
- Names can change. Cloudflare's tracing is in beta and its span and attribute names are not final.
Not verified for source maps
A mapped stack needs two things on each error: an exception event with exception.stacktrace on the span, and a service.version that equals the release the maps were uploaded under. Cloudflare documents that recordException on a custom span exports the stack. We have not verified under which attribute names it reaches Maple, or that the native export lets you set service.version. We make no claim either way. With the SDK you set service.version in code and we have seen the stack arrive, which is why the source map setup below uses it.
When you run both, keep the native export for binding and subrequest spans and for console logs, and use the SDK for the release and for errors. Two things to know. Give the SDK the Worker script's name as service.name if you want one service in the list. And we have not verified that the runtime's spans and the SDK's spans share a trace ID, so check that on your own Worker before relying on it.
Trace a Worker with the OpenTelemetry JS SDK
The second source is an SDK in your own code. Its case here is narrow: the resource carries a service.version you set, and recordException puts the error's stack on the span (see What we ran, below). You build a tracer provider with an OTLP HTTP exporter, open a server span around the handler, and add child spans and attributes where you want them. Three things differ from a Node.js server:
- Flush per request. A batch processor's timer cannot be relied on after the response is sent. End the span, then pass the flush to
ctx.waitUntil, which keeps the invocation alive until the export finishes without delaying the response. - Build the provider lazily. Secrets and variables arrive in
envon the first request, not at module load. Create the provider on first use and keep it in a module variable, so one isolate reuses it. - Register a context manager. A bare tracer provider does not know which span is active. Without
AsyncLocalStorageContextManager, a span you open inside the handler has no parent and shows up as its own trace. It needs thenodejs_compatflag: without the flag the build fails on a Node.js import.
Install the packages at these versions and store the ingest key as a secret:
npm install @opentelemetry/api@1.9.1 @opentelemetry/sdk-trace-base@2.12.1 \
@opentelemetry/exporter-trace-otlp-http@0.223.2 @opentelemetry/resources@2.12.1 \
@opentelemetry/context-async-hooks@2.12.1
npx wrangler secret put MAPLE_INGEST_KEY
The versions are pinned on purpose. On November 29, 2026, installing these package names without versions fails with npm's ERESOLVE: the 2.x line of @opentelemetry/sdk-trace-base (2.12.x) needs @opentelemetry/api below 1.10.0, and the newest @opentelemetry/api is 1.10.0. The 3.x line moved the tracing SDK to a new package with renamed classes, and the code below is written for 2.x.
Turn on nodejs_compat and source maps. Wrangler writes a .map file next to the bundle unless upload_source_maps is false. From Wrangler 4.150.0 it also uploads the map to Cloudflare by default, and true only makes a map it cannot resolve fail the deploy. On earlier versions true is what turns the upload on.
wrangler.jsonc
// wrangler.jsonc
{
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2025-09-01",
"compatibility_flags": ["nodejs_compat"],
"upload_source_maps": true
}
The tracer provider and the context manager are set up once per isolate. The resource carries service.name and service.version:
src/telemetry.ts
// src/telemetry.ts
import { context, SpanStatusCode, type Span } from "@opentelemetry/api"
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"
import { resourceFromAttributes } from "@opentelemetry/resources"
import { BasicTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base"
export interface Env {
MAPLE_INGEST_KEY?: string
COMMIT_SHA?: string
}
export const SERVICE_NAME = "my-worker"
// Built once per isolate, from the env of the first request.
let provider: BasicTracerProvider | undefined
export const telemetry = (env: Env) => {
if (provider === undefined) {
// Carries the active span across awaits, so a span opened inside another becomes its child.
context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable())
provider = new BasicTracerProvider({
resource: resourceFromAttributes({
"service.name": SERVICE_NAME,
...(env.COMMIT_SHA ? { "service.version": env.COMMIT_SHA } : {}),
"deployment.environment.name": "production",
}),
// A missing key disables export. It never stops the Worker.
spanProcessors: env.MAPLE_INGEST_KEY
? [
new BatchSpanProcessor(
new OTLPTraceExporter({
url: "https://ingest.maple.dev/v1/traces", // EU: https://ingest.eu.maple.dev/v1/traces
headers: { authorization: `Bearer ${env.MAPLE_INGEST_KEY}` },
}),
),
]
: [],
})
}
return { provider, tracer: provider.getTracer(SERVICE_NAME) }
}
export const recordError = (span: Span, error: unknown) => {
const err = error instanceof Error ? error : new Error(String(error))
span.recordException(err)
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message })
}
The handler opens a server span, records errors on it, and flushes after the response. handle opens a second span, which becomes a child of the first:
src/index.ts
// src/index.ts
import { SpanKind } from "@opentelemetry/api"
import { recordError, telemetry, type Env } from "./telemetry"
export default {
async fetch(request, env, ctx) {
const { provider, tracer } = telemetry(env)
const url = new URL(request.url)
return tracer.startActiveSpan(
`${request.method} ${url.pathname}`,
{ kind: SpanKind.SERVER },
async (span) => {
try {
const response = await handle(request, env)
span.setAttribute("http.response.status_code", response.status)
return response
} catch (error) {
recordError(span, error)
span.setAttribute("http.response.status_code", 500)
return new Response("Internal Server Error", { status: 500 })
} finally {
span.end()
ctx.waitUntil(provider.forceFlush())
}
},
)
},
} satisfies ExportedHandler<Env>
async function handle(request: Request, env: Env): Promise<Response> {
const { tracer } = telemetry(env)
// A child of the request's span: the context manager knows which span is active.
return tracer.startActiveSpan("load plan", async (span) => {
try {
if (new URL(request.url).pathname === "/fail") throw new Error("plan not found")
return new Response("ok")
} finally {
span.end()
}
})
} span.recordException writes exception.type, exception.message and exception.stacktrace on an exception event. Maple reads that event to open an issue. The stack on it is the bundled one, which the rest of this guide fixes.
What we ran
We ran this code as printed under wrangler dev with Wrangler 4.169.0 and the package versions above, with only the exporter URL changed to a local HTTP listener. Each request produced one OTLP POST to /v1/traces with the Authorization header. The load plan span had the request span as its parent, in the same trace. A request to /fail produced an exception event with the stack on the request span. We have not run it as a deployed Worker against Maple's ingest.
Why a Worker's stack trace stays bundled
Wrangler deploys a Worker as a bundle. Your TypeScript files and their dependencies become one JavaScript file, index.js for an entry file src/index.ts. When code in that bundle throws, the engine builds error.stack from what it is running, which is the bundle:
Illustrative
Error: plan not found
at index.js:10925:60
at AsyncLocalStorageContextManager.with (index.js:9412:36)
The positions are correct and useless. Wrangler does not minify unless you set minify, so the frame points at a line deep inside index.js, here line 10925 of a bundle that is mostly the SDK. With "minify": true the bundle is one or two long lines and the column carries the position. Either way it is the bundle, not your file. The path in front of index.js depends on where the code runs, which is why the upload below matches on the end of the path. A source map is the file that says which original file, line and name a position came from.
Cloudflare has source map support of its own. Wrangler sends the map to Cloudflare with the deploy, by default from 4.150.0. Cloudflare uses it to remap stacks in its real-time logs and in Tail Workers. It does not change what your code sees.
That matters for tracing, because the stack your telemetry sends is the string your code read from the error. span.recordException(err) copies err.stack into exception.stacktrace as is. So a Worker with upload_source_maps on shows mapped stacks in Cloudflare's logs and bundled stacks everywhere else. The backend that receives the spans has to do the mapping itself, with a map you give it.
Source maps for a Worker deployed with Wrangler
The fix has two halves. Wrangler writes a map for the bundle, and the deploy step uploads that map to the backend. The map does not need to be public: it sits next to the bundle on the build machine and never ships to users.
How a frame finds its map
A backend holds many maps: one per file, per service, per deploy. For each stack frame it has to pick the right one. Browser bundles can carry a debug id that names the map directly. Worker telemetry reports no debug ids, so in Maple a Worker's map is matched on three values:
| Value | On the error | On the upload |
|---|---|---|
| Service | service.name on the span's resource | --service |
| Release | service.version on the span's resource | --release |
| Path | The file path in the stack frame | The JS file's path inside the --outdir directory |
The path match is by suffix on whole segments. A map uploaded as index.js matches a frame at file:///bundle/index.js, and assets/app.js matches https://cdn.example.com/static/assets/app.js, but app.js does not match assets/myapp.js.
The release is the part that goes wrong most often. The rule is short: service.version must equal the release the maps were uploaded under. A bundle changes on every deploy, so a map only fits the deploy it was built with. Use one value for both, and make it something both the Worker and the upload step can read. The git commit is the usual choice. A Worker that reports no service.version gets no mapped frames, whatever was uploaded.
Maple applies maps when an issue is shown. The stored error keeps the raw stack as the Worker sent it, and the issue page has a Raw view of it. More detail is in the source maps docs.
Set the release and upload on every deploy
The tracer provider above reads service.version from the COMMIT_SHA variable. Pass the commit to the Worker with --var, build to a directory with --outdir, then upload that directory under the same commit. A deploy without the --var flag removes the variable, so pass it every time.
GitHub Actions step
- name: Deploy and upload source maps
run: |
curl -fsSL https://maple.dev/cli/install | sh
npx wrangler deploy --outdir dist --var COMMIT_SHA:$GITHUB_SHA
maple sourcemaps upload dist --service my-worker --release $GITHUB_SHA
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
MAPLE_API_URL: https://api.maple.dev # EU: https://api.eu.maple.dev
MAPLE_API_TOKEN: ${{ secrets.MAPLE_API_TOKEN }} --outdir distmakes Wrangler write the bundle it uploads with its map beside it. The bundle is named after the entry file, sosrc/index.tsgivesindex.jsandindex.js.map.--serviceis theservice.nameon the resource.--releaseis the value passed asCOMMIT_SHA. Without--release, the CLI usesgit rev-parse HEADindist, which equalsGITHUB_SHAonly when CI builds that same commit.MAPLE_API_TOKENis an API key with thesource_maps:writescope, created by an engineer or admin under Settings → Keys. It is not the ingest key.- The upload needs the Maple CLI 0.6.0 or later. It exits non-zero when nothing uploads or an upload fails, so CI stops there.
Check the frame path
The map uploads under the path index.js, with no URL prefix. We expect a deployed Worker's frames to read index.js or file:///bundle/index.js, and both match. That is an assumption, not something we have measured on every Wrangler version. If frames stay unmapped, open the issue's Raw stack and compare the path there with the uploaded one.
This step deploys first. If the upload then fails, the Worker is live without maps for that release. Maple applies maps when an issue is shown, so running the upload again with the same release fixes the stacks that already arrived. To never have that gap, build without deploying, upload, then deploy:
npx wrangler deploy --dry-run --outdir dist --var COMMIT_SHA:$GITHUB_SHA
maple sourcemaps upload dist --service my-worker --release $GITHUB_SHA
npx wrangler deploy --var COMMIT_SHA:$GITHUB_SHA
This builds twice. With Wrangler 4.169.0, two builds of the same source gave a byte-identical index.js and identical mappings, so the map from the first build fits the second. Check that on your own project before relying on it.
Without the CLI, one request per map does the upload. MAPLE_API_URL is your region's API, https://api.maple.dev or https://api.eu.maple.dev, and --fail-with-body makes CI fail on a rejected upload:
curl --fail-with-body -X POST "$MAPLE_API_URL/v2/source_maps?minified_path=index.js&service=my-worker&version=$GITHUB_SHA" \
-H "Authorization: Bearer $MAPLE_API_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @dist/index.js.map The 10 MiB cap and sourcesContent
Maple refuses a map over 10 MiB, and the CLI skips such a map with a warning. A Worker that bundles many dependencies can pass that size. Most of the weight is sourcesContent, a copy of every original source file embedded in the map so a tool can show the code around a line.
The mappings themselves are small. Remove sourcesContent before the upload and frames still resolve to your file, function and line. What you lose is the code excerpt on the issue page.
jq -c 'del(.sourcesContent)' dist/index.js.map > dist/index.js.map.tmp && mv dist/index.js.map.tmp dist/index.js.map Verify and debug
- Deploy. The upload prints
uploaded index.jswith the map's size. - Request
/fail, the path where the sample'shandlethrows. It answers 500. - In Explore → Traces, open the request's trace. The
load planspan sits under the request span. The request span has anexceptionevent, and its resource hasservice.versionequal to the commit. - Open the issue in Errors. The stack trace should show Source mapped, with frames in your
src/files. Raw shows the bundled stack the Worker sent, inindex.js.
When a step fails, the cause is nearly always one of these:
| Symptom | Cause |
|---|---|
| Every span is its own trace | No context manager is registered, or nodejs_compat is missing |
| No traces at all | MAPLE_INGEST_KEY is not set on the deployed Worker (npx wrangler secret list), or ctx.waitUntil(provider.forceFlush()) is never reached |
| Frames stay bundled | service.version on the error differs from the uploaded release or is missing (a deploy without --var COMMIT_SHA:…), or service.name differs from --service |
| Service and release match, frames still bundled | The frame's path in the Raw stack does not end with the uploaded path |
| No issue to look at | The error was caught and answered without recordException, so there is no stack to map |
| Frames map but show no code | The map has no sourcesContent, which is expected after removing it |
To compare the two sides, list what was uploaded with GET /v2/source_maps?service=my-worker and read the span's resource attributes next to it. The CLI's own skip messages are explained in the Wrangler docs page.
Which to use
| Situation | Approach |
|---|---|
| You want request, subrequest and binding spans with no code changes | The native OTLP export, with two destinations |
| You also want spans for your own logic, and nothing else | The native export with Cloudflare's custom spans API (beta, not verified against Maple) |
| You want error stacks mapped to source, under a release you set | The OpenTelemetry JS SDK and maple sourcemaps upload |
| You want mapped errors and the runtime's binding spans | The SDK and the native export together |
| The Worker is written with Effect and deployed with Alchemy | The Effect and Alchemy guide |
Whichever you pick, two rules stay the same: flush before the invocation ends, and upload each deploy's maps under the release its Worker reports.
Maple
Set it up step by step
The docs have each path as a reference page, with prerequisites, EU endpoints and troubleshooting.
Sources and further reading
- Cloudflare docs: Export to OpenTelemetry destinations
- Cloudflare docs: OpenTelemetry export for Workers
- Cloudflare docs: Tracing known limitations
- Cloudflare docs: Custom spans
- Cloudflare docs: Observability pricing
- Cloudflare docs: Source maps and stack traces
- OpenTelemetry: Semantic conventions for exceptions on spans
- Guide: Effect and Alchemy on Cloudflare Workers
- Maple docs: Cloudflare Workers instrumentation (native export)
- Maple docs: Cloudflare Worker with Wrangler
- Maple docs: Source maps