# Cloudflare Worker with Wrangler

Reference: the Maple setup for a Worker deployed with Wrangler. OpenTelemetry SDK code, the release variable, and the source map upload step for CI.

This guide covers a Worker written without Effect and deployed with `wrangler deploy`. By the end:

- each request is a trace in Maple, and a thrown error becomes an issue with its stack trace, and
- the Worker's source maps are uploaded on each deploy, so the issue page shows your original file, function and line instead of the bundled `index.js`.

If you deploy with Alchemy and Effect, follow [Cloudflare Worker with Alchemy and Effect](/docs/guides/cloudflare-workers-alchemy) instead.

## Why an SDK, and not only the native export

[Workers Observability OTLP export](/docs/guides/instrumentation-cloudflare-workers) sends the runtime's own spans and logs with no code changes. Source maps need two things on each error:

- An `exception` event with `exception.stacktrace`, recorded on the span that failed.
- A `service.version` equal to the release the maps are uploaded under.

We have not verified that the native export carries the stack trace or lets you set `service.version`. So this guide records spans with the OpenTelemetry JavaScript SDK, where you set both in code. You can keep the native export on as well for binding and subrequest spans.

Cloudflare's own source map support (`upload_source_maps`) remaps stacks only in Cloudflare's real-time logs and Tail Workers. Inside the running Worker, `error.stack` still points at the bundled file, and that is the stack your telemetry sends. Maple maps it with the maps you upload to Maple.

## Prerequisites

- Wrangler 3.91.0 or later, the first release that reads `wrangler.jsonc`.
- An ingest key from **Settings → Ingestion**.
- An API key from **Settings → Keys** with the **Source maps** write scope (`source_maps:write`), created by an engineer or admin, for the upload.
- The [Maple CLI](/docs/reference/cli) 0.6.0 or later in CI.
- Your organization's endpoints. Ingest is `https://ingest.maple.dev` and the API is `https://api.maple.dev`. EU organizations use `https://ingest.eu.maple.dev` and `https://api.eu.maple.dev`.

## 1. Trace the Worker

Install the SDK packages:

```bash
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
```

The versions are pinned. On November 29, 2026, installing these packages without versions fails with npm's `ERESOLVE`, because the 2.x line of `@opentelemetry/sdk-trace-base` (2.12.x) needs `@opentelemetry/api` below 1.10.0. The 3.x SDK line uses a different package and class names. The code below ran under `wrangler dev` with Wrangler 4.169.0 at these versions.

Turn on `nodejs_compat` and source maps in the Wrangler config. The context manager below needs `nodejs_compat`: without it the build fails on a Node.js import. 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` turns the upload on.

```jsonc
// wrangler.jsonc
{
	"name": "my-worker",
	"main": "src/index.ts",
	"compatibility_date": "2025-09-01",
	"compatibility_flags": ["nodejs_compat"],
	"upload_source_maps": true,
}
```

Store the ingest key as a secret:

```bash
npx wrangler secret put MAPLE_INGEST_KEY
```

Create the tracer provider and register a context manager, once per isolate, from the `env` of the first request. The resource carries `service.name` and `service.version`. The context manager tracks the active span. Without it, a span opened inside the handler has no parent and shows up as its own trace:

```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 })
}
```

Wrap the handler in a server span, record errors on it, and flush after the response with `ctx.waitUntil`. `handle` opens a second span, which becomes a child of the first:

```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` (the error's `stack`) on an `exception` event. Maple reads that event to open an issue.

`Env` is declared by hand here because `wrangler types` does not know a variable passed with `--var` or a secret set with `wrangler secret put`. If your project already has an `Env` type, add the two fields to it.

## 2. Report the release as `service.version`

Maple matches a Worker's maps by service, release and path, so the `service.version` on its spans must equal the release you upload under. The tracer provider above reads it from the `COMMIT_SHA` variable. Set it on every deploy with `--var`. A deploy without the flag removes the variable:

```bash
npx wrangler deploy --var COMMIT_SHA:$GITHUB_SHA
```

Use the same value for `--release` in the upload below. If you use your own release ids instead of commits, pass that value in both places.

## 3. Build to a directory and upload the maps

Add `--outdir` to the deploy. Wrangler then writes the bundle it uploads with its map beside it. The bundle is named after your entry file, so `src/index.ts` gives `index.js` and `index.js.map`:

```bash
npx wrangler deploy --outdir dist --var COMMIT_SHA:$GITHUB_SHA
maple sourcemaps upload dist --service my-worker --release $GITHUB_SHA
```

- `--service` is the `service.name` on the tracer provider's resource.
- `--release` is the value you passed as `COMMIT_SHA`. Without it, the CLI uses `git rev-parse HEAD` in `dist`, which equals `GITHUB_SHA` only when CI builds that same commit.
- No `--url-prefix`. The map uploads under the path `index.js`, and Maple matches a frame whose path is `index.js` or ends with `/index.js`. We expect a deployed Worker's frames to read `index.js` or `file:///bundle/index.js`, and both match. If your frames stay unmapped, check the path in the issue's **Raw** stack.
- Skip `maple sourcemaps inject`. Worker errors carry no debug ids, so the maps are matched by release.

`upload` needs `MAPLE_API_URL` and `MAPLE_API_TOKEN` in CI. The token is the API key with `source_maps:write`. GitHub Actions sets `GITHUB_SHA` itself. A full GitHub Actions step:

```yaml
- 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 }}
```

The upload exits non-zero when nothing uploads or an upload fails, so CI stops there.

### Without the CLI

`POST /v2/source_maps` takes the map as the request body. Set `MAPLE_API_URL` to your region's API, `https://api.maple.dev` or `https://api.eu.maple.dev`; `--fail-with-body` makes CI fail on a rejected upload:

```bash
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
```

See [Upload with the API](/docs/errors/source-maps#upload-with-the-api).

### Keep the map under 10 MiB

Maple refuses a map over 10 MiB, and the CLI skips it with a warning. Most of a large map is `sourcesContent`, the copy of every source file inside it. Removing it before the upload keeps the mapping:

```bash
jq -c 'del(.sourcesContent)' dist/index.js.map > dist/index.js.map.tmp && mv dist/index.js.map.tmp dist/index.js.map
```

Frames still map to your file, function and line. The issue page then shows no code around the line.

## Verify

1. After the deploy, the upload prints `uploaded index.js (…)`.
2. Send a request that throws inside `handle`.
3. In **Traces**, the request's span has an `exception` event, and its resource has `service.version` equal to the commit.
4. Open the issue in **Errors**. The **Stack trace** shows **Source mapped**, with frames in your `src/` files. **Raw** shows the stack the Worker sent, in `index.js`.

## Troubleshooting

- **`skipped index.js: map is over 10 MiB`.** Remove `sourcesContent` before the upload, as above.
- **`no source maps with a matching JS file found under dist`.** `upload_source_maps` is `false`, so Wrangler wrote no map, or `--outdir` points somewhere else.
- **`skipped index.js: no debug id; …`.** `--service` is missing, or no `--release` was given and none could be read from git. Pass both.
- **Frames stay minified.** The error's `service.version` does not equal the uploaded release, or its `service.name` does not equal `--service`. Compare the span's resource attributes with `GET /v2/source_maps?service=my-worker`. A deploy without `--var COMMIT_SHA:…` reports no `service.version`. If both match, check the frame path in the **Raw** stack against the uploaded path.
- **No mapped frames because there is no issue.** Maps apply to stacks on the issue page. An error you caught and answered with a 4xx, without `recordException`, never becomes an issue. Call `recordError` on the span for failures you want to see.
- **Every span is its own trace.** The context manager is not registered, or `nodejs_compat` is off.
- **No traces at all.** `MAPLE_INGEST_KEY` is not set (`npx wrangler secret list`), or `ctx.waitUntil(provider.forceFlush())` is not reached.

## Next steps

- [Source maps](/docs/errors/source-maps): how frames find maps, limits and retention.
- [Cloudflare Workers instrumentation](/docs/guides/instrumentation-cloudflare-workers): runtime spans and logs with no code changes.
- Guide: [Cloudflare Workers tracing with OpenTelemetry](/guides/cloudflare-workers-tracing), with the native export set up step by step. For Effect, see [Effect and Alchemy on Cloudflare Workers](/guides/effect-alchemy-cloudflare-workers-tracing).
- [Errors and issues](/docs/errors/overview)
- [CLI reference](/docs/reference/cli#maple-sourcemaps-upload-dir)
