agentleFS
louisbrulenaudetlouisbrulenaudet/monorepo-template/.cursor/rules/backend/workers-config.mdc

monorepo-template / backend

Cursor rule18 starsChanged 59 days agoApache-2.0View on GitHub

Worker config rules - cloudflare.config.ts shape and fail-closed modes, Preview branch, secrets vs vars, generated types.

  • Reads credentials

The file

We split this workers-config.mdc into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every app has one, valid only under --mode production, returning the same env keys pointed at Preview-safe values: worker-api is production …

    line 39

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
workers-config.mdc
---
description: "Worker config rules - cloudflare.config.ts shape and fail-closed modes, Preview branch, secrets vs vars, generated types."
alwaysApply: false
globs: **/cloudflare.config.ts,apps/worker-*/vite.config.ts,apps/worker-*/package.json
---

# Worker Config (`cloudflare.config.ts`)

`cloudflare.config.ts` is the source of truth for each app's Worker name, bindings, vars, and exports in every mode; `cf`, the Cloudflare Vite plugin, and `@cloudflare/vitest-plugin` all evaluate it. Build and dev settings (minify, source maps, dev port, inspector port) live in the app's `vite.config.ts`, never here. RPC bindings: [service-bindings.mdc](service-bindings.mdc); cache: [workers-cache.mdc](workers-cache.mdc).

## Shape

- `export default defineConfig({ worker: (ctx) => … })` from `cf/config`: the factory picks one entry from a `DEPLOYMENTS` table keyed `development` / `staging` / `production` and returns a single object built from it. Scaffold a new app by copying an existing app's `cloudflare.config.ts` + `vite.config.ts` and editing them by hand.
- **Modes fail closed**: an unknown `ctx.mode` throws instead of falling back to development values, and `ctx.isPreview` throws unless the mode is `production`. Never add a default branch. Missing required config fails predictably, never degrades - the application-level 503 guards (`CORS_ORIGINS`) stay too.
- **One env shape, one return.** `Env` is inferred (`InferEnv` over the default export) and the generated types declare `interface Env extends __Env`; an interface cannot extend a union, so branches returning differently shaped objects break type generation. Keep every mode on the same `env` keys, per-mode values in the `Deployment` table (a field may be a union such as `SecretBinding | TextBinding<"">`), and one `return`.
- **Every `@repo/*` import is type-only** (`import type { AppEnvironment } from "@repo/enums-common"`); modes use string literals typed by the enum (`environment: "dev"`), which tsc checks. The Vite plugin adds every module the config loads to `server.fs.deny`, so a value import denies that package to the Worker and SPA that also import it (`cf dev`: `Failed to load url /@fs/…/packages/enums-common/src/index.ts … Does the file exist?`), and Node loads the config natively without adding extensions, so a value import from an extensionless `@repo/*` package fails at load.
- **Names**: development keeps the bare package name (`worker-api`, `front-app`); deployed Workers are `<app>-staging` and `<app>-production`, and Previews live under `<app>-production`. CD, the Preview scripts, `wrangler tail`, and Worker-name bindings address these names - never rename them in passing.
- `compatibilityDate` 2026-08-04 or later, so Node.js compatibility is on by default; never add `nodejs_compat` / `nodejs_compat_v2` to `compatibilityFlags`.
- A Worker with code sets `entrypoint` from `import * as entrypoint from "./src/index.ts" with { type: "cf-worker" }` (the shared presets set `allowImportingTsExtensions`). The assets-only `front-app` has no `entrypoint` and sets `assets: { notFoundHandling: "single-page-application" }`.
- `previewUrls: true` in production only - Previews need it. It is applied by `cf workers triggers deploy` (or a full `cf deploy`), never by `cf workers versions create` / `cf workers deployments create`, which is all CD runs; it also exposes production Version URLs, and Preview URLs stay public until Cloudflare Access guards the `front-app` ones (never the gateway's) ([../ops/previews.mdc](../ops/previews.mdc)). `workersDev` defaults to `true`; set `false` only once custom domains serve the Worker.
- Observability per deployment: development samples logs and traces at 1; staging and production trace at `headSamplingRate: 0.01`; the `worker-api` Preview persists logs and traces at 1, the `front-app` Preview keeps production's. The Sentry sampler mirrors these ([hono-gateway.mdc](hono-gateway.mdc)).
- Porting a Wrangler config: env blocks → modes, `previews` block → the `ctx.isPreview` branch, `vars` → `bindings.text()`, `secrets.required` → `bindings.secret()`, `version_metadata` → `bindings.versionMetadata()`, `observability` / `assets` / `limits` keys → camelCase under `worker`; `minify`, `upload_source_maps`, `dev.port`, `inspector_port` → `vite.config.ts`.

## Modes

| Mode | Selected by | Worker | Purpose |
|------|-------------|--------|---------|
| `development` | `cf dev` (default) | `<app>` | Local development |
| `staging` | `--mode staging` | `<app>-staging` | Pre-production |
| `production` | `cf build` / `cf deploy` default; package scripts pass `--mode production` | `<app>-production` | Production |
| `test` (`worker-api`) | `@cloudflare/vitest-plugin` (`experimental.newConfig`) | `worker-api` | Vitest pool: development values, fake secrets as text bindings ([hono-workers.mdc](../tests/hono-workers.mdc)) |
| Preview (`ctx.isPreview`) | Preview build under `--mode production` | `<app>-production` | Branch / PR Previews (below) |

- Pass `--mode`, never `--env`: there are no Wrangler environments.
- The Build Output records its mode (`.cloudflare/output/v0/config.json`: `buildContext.mode`, `buildContext.isPreview`); every `--prebuilt` command (`cf deploy`, `cf workers versions create`, `cf previews deploy`) passes exactly that `--mode`.

## Preview branch (`ctx.isPreview`)

- Every app has one, valid only under `--mode production`, returning the same `env` keys pointed at Preview-safe values: `worker-api` is production with `ENVIRONMENT` `preview`, `SENTRY_DSN` as `bindings.text("")`, and persisted logs and traces at 1; `front-app` is production with `ENVIRONMENT` `preview`.
- `ENVIRONMENT` is `AppEnvironment.PREVIEW`: strict CORS, and the only environment that honors a `CORS_ORIGINS` wildcard ([hono-gateway.mdc](hono-gateway.mdc)). The echo route's `=== AppEnvironment.PRODUCTION` gate treats a Preview as non-production, one more reason to keep Previews behind Access.
- **Never in the Preview branch:** production data bindings, queue consumers, cron triggers, routes. Previews cannot consume queues or run `scheduled()`; routes and crons always target production.
- A Preview's service bindings call the bound Worker's **production** deployment, not its Preview: a PR changing both sides of a binding is not integration-tested by Previews - the `createTestHarness` suite covers that.
- Durable Objects and Containers are isolated per Preview automatically; KV, D1, R2, Queues, and Workflows are not. Adding one means a separate Preview resource in this branch and, for anything holding user data, a retention and deletion rule in the owning app's `AGENTS.md`.
- Testing a branch on a Preview (deploy hand-off, sandbox allowlist, logs): the agent loop in rule `ops/previews`.
- A Preview needing a real secret declares `bindings.secret()` in this branch and gets its value from `wrangler preview secret put` ([../ops/previews.mdc](../ops/previews.mdc)); never production secret values.

## Secrets vs vars

- Declare each secret with `bindings.secret()` in every mode that reads it: the config is the single list (no example file), and `env.<NAME>` is typed `string`. A secret never goes in a `bindings.text()` value, code, or logs. `test` and Preview use `bindings.text("")` instead, so tests and Previews never need a real value (an empty `SENTRY_DSN` disables Sentry).
- Local secret values come from a gitignored `.env` or the shell, never a `.dev.vars`, which would break the Vitest pool: it skips only an unreadable `.env` (root `AGENTS.md`, Environment).
- A Worker's `vite.config.ts` sets `envDir: process.env["SKIP_ENV_FILES"] ? false : "."` (root `turbo.json` `global.passThroughEnv` carries it): the agent sandbox cannot read the `.env`, the Vite plugin aborts on an unreadable env file, and only `.claude/settings.json` sets the variable. Wrangler's `CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV` is not an alternative: the plugin declares it but never reads it.
- Deployed secrets: `--secrets-file <path>` on `cf deploy` / `cf workers versions create` (a file outside the checkout, e.g. under `$TMPDIR`, deleted after use), or one value with `pnpm exec wrangler secret put <NAME> --name <app>-production`. Both fail (`The following required secrets have not been set`) when the Worker has no value for a declared `bindings.secret()`, which cf turns into Wrangler's `secrets.required`.
- Non-secret config (`ENVIRONMENT`, `CORS_ORIGINS`, `API_ORIGIN`, `*_BASE_URL`) is `bindings.text()`. `ENVIRONMENT` is the `AppEnvironment` wire value. `CORS_ORIGINS` is comma-separated browser origins per deployment: staging `https://front-app-staging.example.com`, production `https://app.example.com`, Preview `https://*-front-app-production.<subdomain>.workers.dev` (a wildcard needs three or more labels after its label and returns 503 outside `PREVIEW`). Empty is permissive in `dev` only; anywhere else `/api/*` returns 503.

## Types

- `pnpm types` runs `cf workers types` per app into `apps/<app>/.cloudflare/types/index.d.ts` (`cf dev` and the Vite plugin also write it): a global `Env` and `Cloudflare.Env` (which types `env` from `cloudflare:workers`), plus workerd runtime types for the compatibility date. Gitignored and cached by the `types` task that `check-types` depends on ([turborepo.mdc](../core/turborepo.mdc)).
- The Worker tsconfig includes `cloudflare.config.ts` and `.cloudflare/types` with `"types": []` ([typescript-config.mdc](../quality/typescript-config.mdc)).
- `front-app` sets `cloudflare({ types: { generate: false } })` and has no `types` script: an assets-only Worker has no code that reads `env`.

## Optional performance / DX options

- `limits.cpuMs`: CPU guard (default 30000, max 300000); lower for thin workers, raise for heavy routes.
- `placement`: `{ mode: "smart" }` or a targeted `region` / `host` / `hostname`, only for workers fronting a centralized backend (DB / Hyperdrive); on a pure edge gateway it only adds latency.
- `logpush: true` with an account Logpush destination, for long-term retention; `observability.logs.invocationLogs: false` trims per-request logs at high traffic.
- Assets-only `front-app`: performance comes from the generated `_headers` ([vite-config.mdc](../frontend/vite-config.mdc)); `assets.runWorkerFirst` and `bindings.assets()` apply only once the app has an `entrypoint`.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.