# Deployment and rollback

GitHub Actions deploy isolated previews and the production Worker with reviewed migrations.

## Production [#production]

A push to `main` triggers `deploy-prod.yml`. Like every workflow it runs on the self-hosted VPS runner, never on a GitHub-hosted one ([CI and the runner](/docs/development/ci)). Its concurrency group serializes production deployment without cancelling an in-flight run. Its first step checks that the eight required secrets of the `production` environment are set (`CF_API_TOKEN`, `ACCOUNT_ID`, `DATABASE_URL`, `BETTER_AUTH_SECRET` and the four `STORAGE_*`) and stops with one error that names every missing one, before anything is checked out, migrated or uploaded. The step is handed only whether each secret is set, never its value. A later step, still before migrations and upload, refuses a `BETTER_AUTH_SECRET` that is shorter than 32 characters or an example value such as the one in `.dev.vars.example` (`scripts/check-auth-secret.mjs`): the Worker refuses to boot with one, and a deploy that only failed there would already have migrated the database. The rule is one module, `packages/env/src/auth-secret.mjs`, which the Worker's env schema, `pnpm run setup`, `pnpm doctor` and the preview's trusted deploy step all run. The workflow then checks out the revision, installs the frozen lockfile, applies pending database migrations, builds the Worker and deploys it with Wrangler.

Where production runs (Neon region, Worker placement, costs, a Node server or Google Cloud instead) and how its data is backed up are in the [production guide](/docs/production).

`pnpm deploy` is the explicit local deployment path. It uses configured credentials and can change production state. Routine development and bundle measurement should use a build and `wrangler deploy --dry-run` instead.

## Pull request previews [#pull-request-previews]

Only a pull request into `main` gets a preview: it rehearses the production deploy with the Neon parent branch and domain of `main`. A pull request into another branch (an integration branch, a stacked pull request) gets none, and its checks are `ci.yml` and `e2e.yml` alone. Cleanup runs when a pull request into `main` closes, also sweeps the previews of other closed pull requests (one retargeted away from `main`, one whose cleanup failed), and removing nothing is a success.

The preview workflow derives and validates an isolated Worker/database target in three jobs with different trust ([trust zones](/docs/development/ci#trust-zones)). `provision` runs code from `main` with the Neon and Cloudflare credentials: it ensures the preview branch and, when production uses Hyperdrive, a Hyperdrive of the PR's own (named after the preview Worker, query caching disabled, pointing at the PR's database branch) so the preview takes the production connection path, and it decides the preview Worker's name, bindings, variables and routes. `build` runs the pull request's code with the preview database URLs and no Cloudflare token: it applies migrations through the branch's direct URL and builds. `deploy` runs code from `main` again: it validates the build output as data and deploys it with its secrets in the same version (`wrangler deploy --secrets-file`), because the env schema validates when the Worker loads; then it checks the runtime and comments. A pull request changes the shape of its preview (entry point, compatibility date and flags, assets, placement), not its bindings. Closing the PR deletes the Worker, its Hyperdrive and its database branch from `main`'s code: cleanup asks GitHub whether the pull request is still closed and removes what was recorded at provision time (the PR's database branch by name), under the Worker's name today or a former one listed in the `PREVIEW_FORMER_WORKER_NAMES` variable. The CI token needs Hyperdrive edit permission.

Previews skip email verification: the generated configuration always sets `AUTH_SKIP_EMAIL_VERIFICATION` to `true`, whatever `apps/web/wrangler.jsonc` says, so a fresh account signs in right after sign-up and `scripts/rls-preview-proof.mjs` can create its own accounts on any preview. Production keeps the setting from `wrangler.jsonc` (`false` in this template). A preview mail transport (`PREVIEW_EMAIL_FROM` with Resend or a sender-restricted Cloudflare binding) is optional; without it, password reset and invitation mail cannot be sent from the preview.

Preview isolation is a correctness boundary: a preview must never silently reuse production auth, storage or database resources. No preview job receives the production database URL; the check compares the preview URL with the `PRODUCTION_DATABASE_TARGET` variable (`postgresql://<host>/<database>`, no user or password). Read the workflow and isolation tests before changing naming, credentials or teardown.

A preview Worker has no cron trigger: the generated configuration sets `triggers.crons` to an empty list, so only production runs the one-minute job tick. A tick queries the database, and a preview that ticked every minute kept its Neon compute awake around the clock; in October 2026 that spent the whole Free-plan compute quota and blocked production deploys for a week. For the same reason each preview database branch is created with a 14-day Neon `expires_at`, renewed on every push, so an abandoned PR that never closes still releases its branch. Only the preview job renews it: a PR idle for more than 14 days loses its branch and preview data, and the next push creates an empty one. Closing the PR remains the normal cleanup. To exercise the jobs on a preview, run one tick from a workstation against the branch's direct URL: `DATABASE_URL=<preview migration URL> PRODUCTION_DATABASE_URL=<production URL> pnpm jobs:run --once --preview`. The `--preview` flag lifts the command's local-only rule for that run and still refuses the production database. A Node deployment, which has no Cron Trigger, runs the same tick from a system timer with `--production` ([scheduled jobs on Node](/docs/production#scheduled-jobs-on-node)).

## Configuration and secrets [#configuration-and-secrets]

Cloudflare API credentials authorize the workflow; Worker runtime secrets are separate. Database access, Better Auth, R2/files and optional providers must be configured for the target environment. `VITE_SITE_URL` is a public build value, not a secret. GitHub Actions secrets live in environments limited to `main`, never at repository level, where a pull request's workflow could read them; `pnpm run setup --github-secrets` publishes each to its own ([CI](/docs/development/ci#trust-zones)). Setup and the deployment skill describe the concrete secret names and provider steps. A secret the production workflow starts to need is added to its first step in the same change; `scripts/deploy-secrets.test.mjs` fails when the step's list and the secrets the job uses differ.

The production workflow checks the existing Worker's bindings before it builds or migrates. For Pagar.me, set the Worker secret `PAGARME_WEBHOOK_SIGNATURE=required` after confirming signed deliveries, or explicitly choose `optional` if you accept unsigned deliveries. Cloudflare hides secret values, so a secret `BILLING_PROVIDERS` alongside all three required Pagar.me bindings triggers the check. If Pagar.me is disabled, remove the unused Pagar.me bindings to clear that requirement. [Payments](/docs/features/payments)

Hyperdrive points to Postgres with query caching disabled: cached reads are keyed by query text and parameters, not by the tenant role and settings row-level security uses. `pnpm run setup --hyperdrive-id <id>` disables it (`wrangler hyperdrive update <id> --caching-disabled`), and the production deploy refuses to publish when `node packages/project-setup-cli/src/hyperdrive.mjs check` finds caching on. The Worker runs next to the database through `placement` in `apps/web/wrangler.jsonc`, set per project with `pnpm run setup --placement <provider:region>` ([Worker placement](/docs/production#worker-placement)). R2 uses the environment’s intended bucket. The Worker owns fetch and scheduled entry points; cron runs the existing job program. Adding a feature does not require another Worker by default. With `"DATA_RESIDENCY": "eu"` in `vars`, the production deploy also refuses a placement hint, R2 endpoint or Neon database outside the EU ([host in Europe](/docs/production#host-in-europe)).

## Gradual deployments [#gradual-deployments]

By default `wrangler deploy` creates a Worker version and routes 100% of production traffic to it at once. For risky server, routing, auth or SSR changes where PR previews and feature flags do not cover production load, use Cloudflare Workers [gradual deployments](https://developers.cloudflare.com/workers/versions-and-deployments/gradual-deployments/) to upload a version without sending traffic, then shift traffic in steps between at most two versions:

```bash
pnpm --filter web build
pnpm --filter web exec wrangler versions upload --var WEBHOOK_TRANSPORT:platform --tag "<release-tag>" --message "<short reason>"
pnpm --filter web exec wrangler deployments list
pnpm --filter web exec wrangler versions deploy <old-version-id>@90 <new-version-id>@10
```

- **Keep `--var WEBHOOK_TRANSPORT:platform` on the upload.** `wrangler.jsonc` leaves the transport out so local workerd stays fail-closed; a version uploaded without the flag ends every [webhook](/docs/features/webhooks) delivery as a configuration error. `scripts/deploy-webhook-transport.test.mjs` keeps this command and the CI deploy in step.
- **Zero-percent verification before ramping.** Deploying `<old-version-id>@100 <new-version-id>@0` puts the new version in the active deployment without routing live visitors to it. Smoke-test it on production by sending `Cloudflare-Workers-Version-Overrides: <worker-name>="<new-version-id>"` ([version overrides](https://developers.cloudflare.com/workers/versions-and-deployments/version-overrides/)) or by using its [Version URL](https://developers.cloudflare.com/workers/versions-and-deployments/version-urls/).
- **Static asset version skew.** Each Worker version carries its own `/assets/*` manifest. During a traffic split, a browser that receives HTML from the new version can hit the old version when fetching a content-hashed chunk and get a `404` ([version skew and static assets](https://developers.cloudflare.com/workers/versions-and-deployments/version-skew/)). Either keep client assets unchanged during a backend-only split, or configure a Request Header Transform Rule that sets `Cloudflare-Workers-Version-Key` so requests with the same key stay on one version while percentages hold steady ([version affinity](https://developers.cloudflare.com/workers/versions-and-deployments/gradual-deployments/version-affinity/)).
- **Version attribution and limits.** `apps/web/wrangler.jsonc` already binds `CF_VERSION_METADATA` so error reports and logs carry the running version ID, and Workers Logpush exposes `ScriptVersion`. Cloudflare allows two versions per deployment, chosen from the 100 most recent uploaded versions ([versions and deployments](https://developers.cloudflare.com/workers/versions-and-deployments/)).
- **Triggers are a separate step.** `wrangler versions upload` and `wrangler versions deploy` release code and bindings only. A change to the cron schedule, routes or custom domain in `wrangler.jsonc` is applied by `pnpm --filter web exec wrangler triggers deploy` ([`wrangler triggers deploy`](https://developers.cloudflare.com/workers/wrangler/commands/workers/#triggers-deploy), experimental), or by the next plain `wrangler deploy`.
- **Promote or revert.** Once error rates and traces are clean, promote with `pnpm --filter web exec wrangler versions deploy <new-version-id>@100`, or cancel the split immediately with `pnpm --filter web exec wrangler rollback <old-version-id>`. Command details: [`wrangler versions upload`](https://developers.cloudflare.com/workers/wrangler/commands/workers/#versions-upload), [`wrangler versions deploy`](https://developers.cloudflare.com/workers/wrangler/commands/workers/#versions-deploy) and [`wrangler rollback`](https://developers.cloudflare.com/workers/wrangler/commands/workers/#rollback).

## Migrations and rollback [#migrations-and-rollback]

Migrations run before the new code is deployed. Review compatibility with the previous Worker because that version can still serve traffic while the database changes — and throughout any gradual deployment split. Prefer additive changes and staged removal over a destructive migration coupled to one deploy. When the previous Worker's statements would fail on the new schema, bridge them in the database (for example a trigger that fills a new required column) and drop the bridge in a later migration; `packages/db/scripts/migration-tests.mjs` runs the previous Worker's statements against the migrated schema.

Deploy the MCP grant-generation release directly to 100% of traffic. Existing MCP clients must re-authorize once after cutover.

To roll back code, identify a known-good version among the 100 most recent versions and run `wrangler rollback <version-id>` (or select **Rollback** in the Cloudflare dashboard under **Deployments**). Rolling back replaces either a single-version deployment or an active gradual deployment split with 100% traffic to the chosen version ([rollbacks](https://developers.cloudflare.com/workers/versions-and-deployments/rollbacks/)). Verify runtime routes and scheduled behavior afterward. A Worker rollback does **not** reverse Postgres migrations, restore deleted records or undo external deliveries. Database recovery requires its own reviewed plan: Neon history, the daily dump and the monthly restore drill are described in [backups and restore](/docs/production#backups-and-restore).

### Rolling back this release [#rolling-back-this-release]

Use a Worker-only rollback to go below the upload staging release. Keep its database migrations in place and bypass the old deploy workflow.
Pause uploads and file mutations while the current cron drains unfinished staged intents. Check pending copies, key holds and live files at those destinations before switching.
The older Worker loses staging and key holds, and its upload cleanup can unconditionally delete a live file. Keep writes and upload cron paused if those checks fail.
Verify database grants, file mutations and upload cron behavior before restoring traffic.
During the rollback window, a document conversion started on the new Worker may need to be retried.
A conversion completed by the previous Worker may show the preparing member in its attribution.

## Verification [#verification]

Build and run the produced Worker locally, then validate the preview URL and its discovery/auth behavior before merging. Check workflow logs for migration and target selection, and production traces for job execution after deployment. Never treat a green Node dev server as workerd compatibility evidence.

## Key files [#key-files]

- [`.github/workflows/deploy-prod.yml`](https://github.com/CarlosZiegler/fofo/blob/main/.github/workflows/deploy-prod.yml)
- [`.github/workflows/pr-preview.yml`](https://github.com/CarlosZiegler/fofo/blob/main/.github/workflows/pr-preview.yml)
- [`scripts/preview.mjs`](https://github.com/CarlosZiegler/fofo/blob/main/scripts/preview.mjs)
- [`scripts/restore-drill.mjs`](https://github.com/CarlosZiegler/fofo/blob/main/scripts/restore-drill.mjs)
- [`.agents/skills/deploy-cloudflare/SKILL.md`](https://github.com/CarlosZiegler/fofo/blob/main/.agents/skills/deploy-cloudflare/SKILL.md)
