
# Cloudflare Workers

`--platform cloudflare` writes `build/cloudflare/` with `worker.mjs`, `main.js` and `prelude.js`, and `wrangler.toml` in the application's directory (once). Deploy it with `npx wrangler deploy`. See [Building](building.md).

- The Worker's `env` arrives with a request, so the context starts with the first one. Its string values (`[vars]`, secrets) are the application's environment; bindings that are objects (KV, D1) are not properties; see Bindings below.
- The address of the client is `CF-Connecting-IP`, which Cloudflare's network sets itself and replaces when a client sends it.
- `wrangler.toml` is written once into the application's directory, with the name, the built `worker.mjs` as `main` and today's compatibility date; after that it is yours (bindings, routes, cron triggers).

## Bindings

The bean `cloudflareBindings` (`CloudflareBindings`) gives the Worker's KV namespaces (`KvNamespace`) and D1 databases (`D1Database`) by the names of their bindings in `wrangler.toml`:

```toml
[[kv_namespaces]]
binding = "SETTINGS"
id = "..."

[[d1_databases]]
binding = "DB"
database_name = "shop"
database_id = "..."
```

```dart
@Service()
class Settings {
  Settings(this.bindings);
  final CloudflareBindings bindings;

  Future<String?> theme() => bindings.kv('SETTINGS').get('theme');

  Future<List<Map<String, Object?>>> orders(String user) => bindings
      .d1('DB')
      .query('select id, total from orders where user = ?1', [user]);
}
```

They arrive with a request: use them while a request (or a scheduled event) is handled, not in a constructor. Other kinds of bindings (queues, R2, Durable Objects) have no API here yet.

## The rate limiter in D1

With `spring.edge.cloudflare.rate-limit.database: DB` (the binding of a D1 database) the rate limiter's counters are in that database (`D1RateLimitStore`, the store `d1`: one atomic statement, the table created when it is missing), shared by every instance of the Worker. `spring.edge.cloudflare.rate-limit.table` names the table (`rate_limit` by default). KV is no place for counters: its writes are not atomic.

## Cron triggers

A cron trigger (`[triggers] crons` of `wrangler.toml`) runs the application's `EdgeScheduledHandler` beans; `event.schedule` is the trigger's expression. See [Work by a schedule](differences.md#work-by-a-schedule).

## See also

- [Deploying a function](deploying.md#cloudflare-workers): the steps to deploy, by hand and from GitHub Actions
- [What a function does differently](differences.md)
- [All properties](properties.md)
