# Cloudflare Workers

The build writes a Worker and `.output/wrangler.json`, with the assets binding for `public/`. Cloudflare serves a matching asset before the Worker runs, except on the paths of `run_worker_first` (below). The Worker has the `nodejs_compat` flag. Every storage driver runs there except `fs`, `sqlite`, `netlify-blobs`, `vercel-blob` and `vercel-runtime-cache`: `memory`, `redis`, `s3`, `cloudflare-kv`, `cloudflare-r2`, `cloudflare-cache`, `azure-blob`, `planetscale`, `github`, `http`, `overlay` and `null`, and the `db` driver over a `d1` connection. `scheduledTasks` become `triggers.crons` and the Worker's `scheduled` handler, and `tasks.queue` adds a queue producer and consumer; see [Tasks](/tasks#where-schedules-run). Deploy with Wrangler. The build ends by printing the command: `wrangler deploy --config .output/wrangler.json`. Run it from the project root, or set it as the deploy command in Workers Builds. A bare `wrangler deploy` from the app root works too, through the file described under [Deploy from the app root](/deploy/presets/cloudflare#deploy-from-the-app-root).

## Reference

|                      |                      |
| -------------------- | -------------------- |
| Preset               | `cloudflare`         |
| Runs on              | Cloudflare Workers   |
| `event.runtime.name` | `cloudflare`         |
| Server target        | `browser`            |
| Lifetime, startup    | `request`, `request` |

### Output

```text
.output/
  hamur.json
  wrangler.json              your wrangler config merged with the preset's keys
  server/index.mjs           the Worker module: fetch, scheduled, queue, email, tail
  public/                    served by the assets binding
.wrangler/deploy/config.json  points a plain `wrangler deploy` at .output/wrangler.json
```

### Config keys

| Key                             | Default                  | What it does                                                                                                                       |
| ------------------------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| `cloudflare.websocket`          | `"durable"`              | where WebSockets run: the generated `HamurWebSocket` Durable Object, or `"worker"`                                                 |
| `cloudflare.devBindings`        | `true`                   | `hamur dev` loads `wrangler` and gives events the local bindings; see [Dev bindings and typed env](/deploy/platforms/dev-bindings) |
| `cloudflare.runWorkerFirst`     | `[]`                     | extra `assets.run_worker_first` patterns; `true` runs the Worker for every request                                                 |
| `cloudflare.observability`      | `false`                  | `true` writes `observability: { enabled: true }`                                                                                   |
| `cloudflare.env`                | unset                    | the `env` block of your wrangler config copied over the top level                                                                  |
| `cloudflare.bindings.<NAME>.id` | env `HAMUR_CF_<NAME>_ID` | the id Hamur writes for a D1, R2 or KV binding                                                                                     |
| `tasks.queue`                   | unset                    | `{ name, binding? }`: the Cloudflare queue `enqueue` sends to and the Worker consumes; `binding` defaults to `TASKS_QUEUE`         |

### Detection

The build selects it when `WORKERS_CI` is set, unless `--preset`, `preset` or `HAMUR_PRESET` names another. It is a row of the one table of markers in [Choosing a preset](/deploy#choosing-a-preset).

### Deploy command

`hamur deploy` builds, then runs `wrangler deploy --config .output/wrangler.json`; with `--preview` it runs `wrangler versions upload --config .output/wrangler.json`. See [`hamur deploy`](/deploy/platforms/hamur-deploy). The preview command of the preset, which `hamur preview` runs or prints, is `bunx wrangler dev --config .output/wrangler.json`.

### Limits

- Runs: WebSockets and `server.syncedState`, streamed answers, private `app/env.ts` entries read at run time, Durable Object classes.
- Does not run: `server.pubsub`, `server.metrics`, image transforms at run time.
- `scheduledTasks` become `triggers.crons`; `tasks.queue` uses Cloudflare Queues; `tasks.runOnStart` does not run. The request body limit is Cloudflare's: 100 MB (Free, Pro) to 5 GB (Enterprise).
- `fs`, `sqlite`, `netlify-blobs`, `vercel-blob` and `vercel-runtime-cache` storage fail the build.

The levels are the `features` of the preset: `hamur build` warns or fails when the app uses a feature the preset does not run (see [Preset features](/deploy#preset-features)).

Your own Worker settings go in a `wrangler.json`, `wrangler.jsonc` or `wrangler.toml` in the app root (first found in that order): `kv_namespaces`, `vars`, `d1_databases`, `routes` and the rest. The build merges that file into `.output/wrangler.json`. Never edit `.output/wrangler.json`: every build rewrites it. The preset owns `main`, `no_bundle`, `assets.directory`, `assets.binding` and `assets.not_found_handling`, and sets them over your file. `compatibility_flags` is the union of your flags and `nodejs_compat`; `name` is yours, or the project's name when you give none.

````jsonc [wrangler.jsonc]
{
  "name": "my-app",
  "kv_namespaces": [{ "binding": "CACHE", "id": "<namespace id>" }],
  "vars": { "ENVIRONMENT": "production" },
}
````

## Run worker first

A file in `public/` and a prerendered page are answered by the assets binding before the Worker runs, so a rule that needs the Worker would never see them. The build writes `assets.run_worker_first` with the paths of every route rule that sets `cors`, `proxy`, `basicAuth` or `ipRestriction`, in Cloudflare's pattern syntax in which `*` matches any characters, `/` included: `/api/**` becomes `/api` and `/api/*`. A `headers` or `redirect` rule joins them only when `_headers` or `_redirects` cannot carry it: the file is past Cloudflare's limits, or a header is `false` for a name `_headers` has no `! name` for.

`cloudflare.runWorkerFirst` adds patterns of your own, after the computed ones, and `true` runs the Worker for every request. A `run_worker_first` in your own wrangler config is kept in the list. Cloudflare takes at most 100 entries, so a longer list becomes `true` and the build warns: `run_worker_first needs 143 patterns, past Cloudflare's 100; using true: every request runs the worker`.

`assets.not_found_handling` is always `"none"`, so a miss reaches the Worker's own 404 page. Another value in your wrangler config is replaced, and the build warns: `assets.not_found_handling "single-page-application" is replaced by "none": Hamur answers a miss itself`. With a non-empty `run_worker_first` the Worker serves a public file through `env.ASSETS.fetch`, with the rule's `cors` and `headers` on the answer; a file under no rule never reaches the Worker.

## Trailing slash

The build writes `assets.html_handling` from `app.trailingSlash`:

| `app.trailingSlash`                  | `assets.html_handling`   |
| ------------------------------------ | ------------------------ |
| `"ignore"`, `"redirect"`, `"strict"` | `"drop-trailing-slash"`  |
| `"always"`                           | `"force-trailing-slash"` |

A prerendered `about/index.html` is then answered at the form the app links to, with the other form redirecting to it (307), instead of Cloudflare's default `"auto-trailing-slash"`, which redirects `/about` to `/about/`. A key in your own wrangler config wins. `"strict"` differs from the server presets: `/about/` of a prerendered page redirects to `/about` instead of answering 404, since the assets layer serves the file before Hamur sees the request. An app with no server code uses [`cloudflare-static`](/deploy/presets/cloudflare-static), which writes the same key, with the table.

## Observability

`cloudflare.observability: true` writes `observability: { enabled: true }` into `.output/wrangler.json`, so Cloudflare keeps Workers Logs and traces for the Worker. An `observability` key in your own wrangler config wins, with its sampling and logging settings. With `server.tracing` on, the request span carries `cloud.provider: "cloudflare"` and `cloudflare.ray`, the value of `cf-ray`, so a span finds its request in the Cloudflare dashboard; Hamur adds no exporter. `cloudflare-pages` does not take the key: Pages Functions have no `observability` setting, and its logs are read with `wrangler pages deployment tail`. The span attributes apply on Pages as well.

## Compatibility date

Your own `compatibility_date` is kept when it is `2026-09-01` or later, Hamur's minimum, so an app can ask for a newer runtime behaviour. An older date is raised to `2026-09-01` and the build warns: `compatibility_date 2020-01-01 is older than Hamur's minimum 2026-09-01; using 2026-09-01`. Without one the build writes `2026-09-01`. A value that is not a `YYYY-MM-DD` date fails the build.

## Environments

Set `cloudflare.env` to the name of an entry of `env` in your `wrangler.json`. The build copies that block's keys over the top level of `.output/wrangler.json` and drops `env`, so `vars`, bindings and the compatibility date of that environment are the ones deployed. A name that is not in the file fails the build and lists the names that are (`cloudflare.env "qa" is not in wrangler.json (envs: production, staging)`). Without `cloudflare.env`, `env` is copied as written.

````jsonc [wrangler-env.jsonc]
{
  "name": "my-app",
  "compatibility_date": "2026-10-01",
  "vars": { "ENVIRONMENT": "production" },
  "env": {
    "staging": {
      "vars": { "ENVIRONMENT": "staging" },
      "kv_namespaces": [{ "binding": "CACHE", "id": "<staging namespace id>" }],
    },
  },
}
````

## Bound resources

A D1 database of `@hamur/db`, the R2 bucket of `@hamur/blob` and the namespaces and buckets of `cloudflare-kv` and `cloudflare-r2` storage mounts are bindings. Hamur writes their `d1_databases`, `r2_buckets` and `kv_namespaces` entries into `.output/wrangler.json` when it knows the id: `cloudflare.bindings.<NAME>.id` in the config, else the environment variable `HAMUR_CF_<NAME>_ID` (the name upper-cased, each character outside `A-Z0-9_` turned into `_`, so `my-kv` reads `HAMUR_CF_MY_KV_ID`; an R2 id is the bucket name). A D1 entry also gets the `migrations_dir` of your migrations. An entry in your own `wrangler.json` for the same binding is kept as written and no id is read. A name that another kind of binding, a `vars` key or a durable object already uses fails the build for D1 and `blob`.

With no id and no entry of your own, a D1 or `blob` binding fails the build (`db.connections.default uses the d1 binding "DB", which the app's wrangler config does not declare; add a d1_databases entry with binding "DB"`), and a storage mount warns once per binding: `storage mount "cache" uses the cloudflare-kv binding "CACHE", which has no id and is not in the app's wrangler config; set cloudflare.bindings.CACHE.id or env HAMUR_CF_CACHE_ID, or add a kv_namespaces entry with binding "CACHE"`.

## Durable Objects

A Worker's Durable Object classes must be named exports of its main module. Export each through `defineServer`:

```ts
// server/counter.ts
import { DurableObject } from "cloudflare:workers"

export class Counter extends DurableObject {
  async fetch() {
    const count = ((await this.ctx.storage.get<number>("count")) ?? 0) + 1
    await this.ctx.storage.put("count", count)
    return new Response(String(count))
  }
}
```

```ts
// server/index.ts
import { defineServer } from "hamur/server"
import { Counter } from "./counter.ts"

export default defineServer({ exports: { Counter } })
```

The build reads the class without running it. When it finds `class Counter extends DurableObject`, with `DurableObject` imported from `"cloudflare:workers"`, in the file the import leads to, `.output/wrangler.json` gets the binding `{ "name": "COUNTER", "class_name": "Counter" }` after your own `durable_objects.bindings`. The binding is the class name in upper snake case: `ChatRoom` is `CHAT_ROOM`, `HTTPCache` is `HTTP_CACHE`. A handler reaches it on `event.runtime.env.COUNTER`. If your `wrangler.json` already binds the class, nothing is added. If another binding already uses the name, the build fails: `defineServer exports "Counter" needs the binding COUNTER, which the app's wrangler config uses for another binding; bind the class in durable_objects yourself`.

Hamur writes no migration for your classes. Cloudflare applies migrations in list order after the last tag it applied, so an entry Hamur inserted could leave one of yours unapplied. Add one yourself, or the build fails: `defineServer exports "Counter" is a Durable Object with no migration in the app's wrangler config; add { "tag": "<tag>", "new_sqlite_classes": ["Counter"] } to migrations`. A `new_classes`, `renamed_classes` or `transferred_classes` entry for the class counts too.

A class the build cannot read, such as one re-exported from a package or made by a call, is still exported but gets no binding: bind it and migrate it in your own `wrangler.json`. On any other preset a Durable Object fails the build: `defineServer exports "Counter" is a Durable Object, which the "node" preset cannot run (it runs on: cloudflare)`.

## WebSockets

A [WebSocket](/server#websockets) route runs on Cloudflare too; [Realtime](/realtime) has the table of what each preset does. `cloudflare.websocket` says where its sockets live:

- `"durable"` (the default): in a Durable Object Hamur generates. The Worker runs the route's middleware, the 426 for a request that is not an upgrade and the origin check, then hands the upgrade to the object `HamurWebSocket`, which runs the hooks. The object accepts with Cloudflare's hibernation API, so an idle socket costs nothing and survives the object being evicted. All sockets go to one object named `hamur`; `websocket.durableName(event)` returns another name, and the sockets of one name share one object. `peer.context` in the object is the JSON copy of `event.context` after middleware: functions and `undefined` drop and a `Date` becomes its string. A context `JSON.stringify` cannot write (a cycle, a `BigInt`) refuses the upgrade with 500 and logs `websocket context of /ws/chat cannot be sent to the HamurWebSocket object: <message>`; so does a `durableName` that returns no non-empty string. The object's RPC method `publish(topic, data)` sends to its subscribers: `env.HAMUR_WS.get(env.HAMUR_WS.idFromName("room-1")).publish("room", text)`. `publish(topic, data)` from `hamur/server` calls it on the object named `hamur`.

  Cloudflare evicts an idle object and keeps its sockets open. Each socket carries the peer's `id`, `params`, route, `remoteAddress`, topics and `context` in its attachment, rewritten at `open` and on every `subscribe` and `unsubscribe`; on the next event after an eviction the object rebuilds every peer and its topics from it, `open` does not run again, and `publish` reaches every subscriber. After a wake `peer.request` holds the upgrade URL without its query and no headers; copy a header you need into `event.context` in middleware or `upgrade`. An attachment is at most 2048 bytes: above it `context` is not kept, with the warning `peer context of /ws/chat is above Cloudflare's 2048-byte socket attachment; it is not kept across hibernation` once per route, and when it is still too large `subscribe` throws `RangeError: WebSocket peer state of /ws/chat is above Cloudflare's 2048-byte socket attachment; subscribe to fewer topics` and keeps the topics it had. A protocol ping gets its pong from Cloudflare and calls no hook; an app's own `"ping"` text message reaches `message` as any other.

- `"worker"`: in the Worker that took the upgrade, with `new WebSocketPair()`. Nothing is added to `wrangler.json`, but a socket ends when Cloudflare recycles the Worker, and topics throw (`WebSocket topics need cloudflare.websocket: "durable": a Worker cannot send to a socket that another request accepted`), since a Worker can send only on the sockets of its own request.

In `"durable"` mode `.output/wrangler.json` gets the binding `{ "name": "HAMUR_WS", "class_name": "HamurWebSocket" }` after your own `durable_objects.bindings`. When your `wrangler.json` has no `migrations`, the build writes `[{ "tag": "hamur-ws-v1", "new_sqlite_classes": ["HamurWebSocket"] }]`. When it has its own, add that entry yourself where it belongs in your deploy order, or the build fails: `the HamurWebSocket object has no migration in the app's wrangler config, which declares its own; add { "tag": "hamur-ws-v1", "new_sqlite_classes": ["HamurWebSocket"] } to migrations in its deploy order`. If your config uses the name `HAMUR_WS` for anything else, the build fails: `the binding HAMUR_WS of the HamurWebSocket object is taken by the app's wrangler config; rename the app's binding`.

## Deploy from the app root

Every cloudflare build writes `.wrangler/deploy/config.json` in the app root. It holds `{ "configPath": "../../.output/wrangler.json" }` (the path from that file to the built config), and Wrangler reads such a file when it finds no config of its own. So a plain `wrangler deploy` from the app root deploys the built Worker, without `--config`. Do not edit the file: every cloudflare build rewrites it.

````sh [deploy-cloudflare-root.sh]
hamur build --preset cloudflare
bunx wrangler deploy
````

The build writes `_headers` and `_redirects` into `.output/public/` from your route rules. Cloudflare reads at most 100 `_headers` rules and 2,000 static plus 100 dynamic `_redirects` rules (a source with `*`, `:splat` or `:pN`), and a `_headers` line is at most 2,000 characters, a `_redirects` line at most 1,000. Past a limit it ignores the rest without a message, so the build warns, for example `[hamur] _redirects has 2101 static rules; Cloudflare reads the first 2000 and ignores the rest`. The same check runs for the `static` preset; Netlify documents no such limit.

````sh [deploy-cloudflare.sh]
hamur build --preset cloudflare
bunx wrangler deploy --config .output/wrangler.json
````
