Deploy to Cloudflare Workers

Deploy a Federation project to Workers, D1, Queue, and R2 with fed deploy.

This page is the operational path for deploying a Federation project to Cloudflare Workers.

If you only want to understand how Federation is wired to Workers, read Cloudflare Workers first. This page focuses on production steps: federation.toml, local project creation, local deploys, D1 / Queue / R2, interactive administrator setup, env setup, OAuth callbacks, and health checks.

PostgreSQL and Supabase

Workers can keep Queues and R2 while connecting to managed PostgreSQL through Hyperdrive. Use @downcity/database-postgresql; existing Federation Accounts, Credits, Payment and AI services remain in place. Supabase Auth and Storage are not required.

Configure Hyperdrive's Supabase origin with the project's Direct endpoint. Hyperdrive pools upstream connections; disable query caching for authorization and financial queries. Local migration tools connecting independently to Supabase may still use the Session pooler. Store connection credentials in secrets or local environment variables.

When using @downcity/database-postgresql through Hyperdrive, set prepare_statements: true so postgres-js uses the prepared statement protocol; Cloudflare's postgres-js integration prohibits prepare: false. The adapter forces prepare: true for unsafe queries and carries this behavior into begin transactions and savepoint clients, overriding Drizzle's explicit prepare: false.

Create a separate PostgreSQL client and Federation container for each Worker invocation, with at most one client connection. Never reuse sockets across invocations. For HTTP streaming responses, dispose the client after completion or cancellation and after that invocation's registered background work has finished. Queue batches and scheduled handlers dispose their own containers in finally blocks.

For a guarded cutover, the official Worker accepts DOWNCITY_MAINTENANCE="true". It allows only GET health, discovery, JWKS and login provider catalog requests. Other requests return retryable 503 responses; scheduled work is skipped and queue messages are retried without acknowledgement. Pause queue delivery during maintenance, then disable the guard and resume delivery after verification. Never acknowledge an unprocessed payment webhook as successful.

For a D1 migration, preserve all source tables, including historical tables. Pause every writer, queue consumer and scheduled processor before taking a consistent export. Run prepare_schema() on empty PostgreSQL to create structures only; import and verify the original identities, keys, accounts and ledgers before prepare_database() establishes constraints and runtime readiness. Never publish a production entry pointing to an empty target.

Archive snapshots and per-table content hashes verify preservation. PostgreSQL hashes the original UTF-8 archive payloads and aggregates per-table counts, sorted SHA-256 digests and required ledger-order digests; only summaries cross the network. Duplicate rows still participate in both counts and hashes. Archives do not replace usable application tables. Once writes switch to PostgreSQL, rollback requires reconciliation and transferring new writes back.

Prerequisites

  • A Cloudflare account
  • Dependencies installed in the project

Downcity does not deploy Workers automatically after git push. Deployment is explicit:

fed deploy

1. Create a Federation project

Developers normally start from an empty directory:

mkdir my-city
cd my-city
fed create --path . --template cloudflare-workers

fed create --path . --template cloudflare-workers asks for the Federation name and generates the Worker project skeleton:

  • federation.toml
  • src/index.ts
  • package.json
  • tsconfig.json

The generated federation.toml stores project information and deployment intent. Federation project configuration uses TOML only; JSON configuration is not supported:

schema = 1
type = "federation"
id = "fed_example"
name = "my-city"
entry = "src/index.ts"

[deployment]
target = "cloudflare-workers"

[deployment.resources.d1]
type = "d1"
binding = "DB"
name = "my-city-db"

[deployment.resources.queue]
type = "queue"
binding = "DOWNCITY_QUEUE"
name = "my-city-queue"

[deployment.resources.storage]
type = "r2"
binding = "DOWNCITY_STORAGE"
name = "my-city-storage"
public_url_prefix = "https://images.example.com"

id is the path-independent Fed identity, and deployment.target declares where it deploys. entry and deployment.resources are commit-safe deployment intent; D1 ids, account state, Worker URLs, and Wrangler config are handled by fed deploy.

If the City template already lives in a Git repository, use fed create to bring it local first:

fed create --path my-city --template https://github.com/example/my-city.git
cd my-city

fed deploy does not deploy remote URLs directly. It only deploys local Federation projects, so .env and deploy results have a clear project owner.

2. Deploy the current directory

Inside the Federation project directory:

fed deploy

When federation.toml sets target = "cloudflare-workers" in [deployment], fed deploy checks Cloudflare auth automatically. Account state is stored in the system-level Federation registry and reused by later deploys.

fed create and fed deploy default to --path .. Use --path <path> for another local directory; positional path arguments are not accepted:

fed deploy --path ./my-city

For a local target, omitting deployment.port uses the fixed default port 12314. Set port in [deployment] to override it. If the selected port is occupied, an interactive terminal shows the listener PID, start time, command, working directory, and whether it belongs to the current project, then asks whether to stop it and continue (default: No). After confirmation, the CLI rechecks process identity, sends SIGTERM, and waits up to 5 seconds for the port to become available, without escalating to a forced kill. Deployment fails in non-interactive terminals, when process identity cannot be verified, or when the port remains unavailable. --yes does not bypass this confirmation. Process inspection requires lsof and ps. The CLI does not scan for another port or infer one from deployment history.

3. Resource Config

Cloudflare Workers currently supports three resource declarations:

[deployment]
target = "cloudflare-workers"

[deployment.resources.d1]
type = "d1"
binding = "DB"
name = "my-city-db"

[deployment.resources.queue]
type = "queue"
binding = "DOWNCITY_QUEUE"
name = "my-city-queue"

[deployment.resources.storage]
type = "r2"
binding = "DOWNCITY_STORAGE"
name = "my-city-storage"
public_url_prefix = "https://images.example.com"

If D1 / Queue are omitted, fed deploy uses ${name}-db and ${name}-queue. Storage is enabled only when deployment.resources.storage exists.

During deployment, fed deploy reuses same-name D1 databases, Queues, and R2 buckets. If a declared resource is missing and this is not --dry-run, it creates the resource automatically. The D1 database id is Cloudflare deploy state and is not written back to project config.

Set dead_letter_queue = "my-city-dead-letter" and max_retries = 10 under [deployment.resources.queue] to pass them to the Wrangler consumer. The dead-letter queue name must be a non-empty string, and the queue must already exist; the CLI does not create it. max_retries accepts an integer from 0 to 100; 0 disables retries after the first failed attempt, and omission uses Cloudflare's default. When a dead-letter queue is configured, messages that exhaust their retries are moved to that queue.

Cloudflare account is not part of the Federation project config. fed deploy reuses Wrangler login first; only when Cloudflare cannot resolve the account automatically does the CLI prompt once and save it into local fed CLI state.

You can also pass the account id for one deploy:

fed deploy --account-id <your-cloudflare-account-id>

4. Dry-run

Before publishing, check the bundle and Wrangler config:

fed deploy --dry-run

For another directory:

fed deploy --path ./my-city --dry-run

5. Deploy flow

fed deploy runs these steps:

  • reads federation.toml from the target directory
  • checks the target platform identity from deployment.target in federation.toml; Cloudflare Workers opens Wrangler login or guides account selection when needed
  • if this is not --dry-run, automatically bumps package.json.version by one patch version before deployment
  • runs pnpm build if package.json has a build script
  • runs pnpm typecheck if package.json has a typecheck script
  • prepares D1 by looking up deployment.resources.d1.name, and creates it automatically when missing
  • prepares Queue by looking up deployment.resources.queue.name, and creates it automatically when missing
  • if deployment.resources.storage is declared, prepares the corresponding R2 bucket and creates it automatically when missing
  • generates Wrangler config temporarily instead of writing it into the project directory
  • builds and loads the Worker's prepare_database(env) export, using the project's Wrangler getPlatformProxy to connect D1 to the exact remote database; schema, bootstrap, and service preparation must succeed before upload
  • interactively asks for administrator credentials on first initialization or when --admin-reset is used, then writes the password digest through deployment-authorized D1 access
  • runs wrangler deploy --config <generated-wrangler.toml>
  • requests Worker /health to check runtime readiness and verifies /v1/admin/login when new credentials were applied
  • registers the Worker URL, deploy state, administrator ID, and time-limited Session Token in the local Federation registry
  • requests Worker /health when --verify is passed

Deploy output is grouped by stage: Project, Version, Build, Typecheck, D1 Database, Queue, Storage, Wrangler, Deployment, and Federation Registry.

Fed has no global active/default Federation and does not store active_server_url. A deployed instance appears in the list without a global-current star marker. Use mutually exclusive, exact-match --id <id> or --name <name> for instance commands such as fed status --id fed_example, fed manage --id fed_example, or fed web --id fed_example. Without a selector, a TTY prompts for this operation only and non-interactive execution fails. Duplicate names prompt in a TTY and fail outside one.

status shows the registry record and a live health probe for any saved connection, plus separate launchd/systemd manager status for local instances. These are independent facts. logs, stop, and restart only support managed local instances, not Worker process control or remote logs. Local restart uses only the installed release and persisted runtime configuration, without reading or rebuilding source, and works after the original project is deleted. An explicitly selected database keeps its absolute path. Local logs reads the existing service.log; stop disables automatic startup and stops the service. It remains stopped across system restarts until an explicit deploy/restart. See Independent Local Node Releases. Remove connection only removes the saved connection; it does not stop the service.

[deployment.process] applies only to local; declaring it for Cloudflare Workers is an error. Local launchd/systemd policies default to auto_start = false and restart_on_failure = true. See CLI Quickstart for configuration, recovery limits, and user manager requirements.

federation.toml stays as the commit-safe project declaration. Business secrets, provider keys, and service env should be written into Federation's own env table instead of federation.toml.

fed deploy --dry-run and fed deploy --verify-only do not change the project version.

Worker database preparation entry

Provide a named export. Share service registration with the request runtime, while creating a fresh instance for preparation:

function create_federation(env: Env): Federation {
  const fed = new Federation({
    database: new Database({ binding: env.DB }),
    database_initialization: "prepared",
  });
  // Register the same services used by the request runtime here.
  return fed;
}

export async function prepare_database(env: Env): Promise<void> {
  const fed = create_federation(env);
  await fed.prepare_database();
}

The CLI loads the entry in a Node subprocess with the project's installed Wrangler, its esbuild, and project dependencies. Install a Wrangler version supporting remote D1 bindings. The entry and its imports must be loadable in Node; avoid Worker-only globals or database operations at module scope. The temporary bundle lives inside the project and is removed on completion or failure; the proxy is always disposed. Local .env files are excluded from the preparation proxy. D1 uses the generated configuration's exact database ID and remote = true; Queue/R2 remain local proxies. Preparation should only perform database work.

--dry-run builds, loads, and checks the export without calling it or opening a remote D1 proxy. --verify-only skips preparation. --skip-build still prepares the database. Projects overriding deployment.scripts.deploy must arrange preparation themselves. Existing projects without the export fail deployment and must update their Worker and installed SDK packages. Run maintenance() periodically rather than on each cold start.

Preparation and administrator writes happen before upload and are not rolled back if upload fails; --admin-reset may already have revoked old administrator sessions. Historical SQL migration files are not automatically scanned or applied.

6. Developer edge starter

The Downcity repository keeps templates/edgefed as a developer-friendly starter project:

fed deploy --path templates/edgefed --verify

This starter is useful for local experiments and custom deployments. Downcity's private official production Worker implementation lives outside the public repository.

7. Initialize Federation

Call /health once after deployment. This lets the Worker boot Federation and create the built-in env / cities tables.

curl https://my-city.<your-subdomain>.workers.dev/health

Expected shape:

{
  "ok": true,
  "services": ["env"]
}

8. Administrator login

On the first fed deploy, Downcity asks for an administrator ID, password, and confirmation. Passwords must be at least 12 characters; only a PBKDF2 digest is stored in D1. To replace lost credentials, run fed deploy --admin-reset; this requires deployment authority, revokes all existing administrator sessions, and asks for new credentials. --yes confirms the destructive reset in non-interactive environments but does not skip credential prompts.

After deployment, fed web, the admin workspace, and fed query authenticate through /v1/admin/login and use a time-limited administrator Session Token. The browser never receives the remote Session Token; it remains in the local CLI BFF or registry.

9. Write provider and service env

Provider keys and service secrets should be written into the Federation env table instead of public clients.

Example:

curl -X POST https://my-city.<your-subdomain>.workers.dev/v1/env/upsert \
  -H "Authorization: Bearer <admin_session_token>" \
  -H "Content-Type: application/json" \
  -d '{"key":"DEEPSEEK_API_KEY","value":"sk-..."}'

Common keys:

KeyPurpose
DEEPSEEK_API_KEYProvider key used by the edge starter project
STRIPE_SECRET_KEYStripe API key for Checkout creation
STRIPE_WEBHOOK_SECRETStripe webhook signing secret
DOWNCITY_CITY_BASE_URLPublic City base URL used to derive payment result pages
CREEM_API_KEYCreem API key for Checkout creation
CREEM_PRODUCT_IDOne-time, tax-inclusive Creem product used for hosted Checkout
CREEM_CURRENCYCreem product currency; it must match the product's actual currency
CREEM_WEBHOOK_SECRETCreem webhook signing secret; the provider is disabled when missing
GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRETOptional Google OAuth login
WECHAT_CLIENT_ID / WECHAT_CLIENT_SECRETOptional WeChat website login

10. Configure OAuth callbacks

If you enable OAuth login, configure the provider callback URL to the deployed Worker:

https://my-city.<your-subdomain>.workers.dev/v1/accounts/oauth/callback

The callback domain must match the public domain users actually visit. If you later move to a custom domain, update the OAuth provider configuration as well.

11. Verify

If a Federation is already connected, run only the health check:

fed deploy --verify-only

You can also check manually:

curl https://my-city.<your-subdomain>.workers.dev/
curl https://my-city.<your-subdomain>.workers.dev/health

Updating the deployment

After code changes:

fed deploy --verify

Runtime env lives in D1, so redeploying the Worker does not erase provider keys, OAuth secrets, cities, balances, usage records, or Stripe payment records.