Skip to Content
SsuperslateDocs

Deploy the web API and frontend

Choose Railway, AWS, or GCP for the Bun API and PostgreSQL, then configure the frontend host and verify the release.

For the React web edition, choose where to run the Bun API and PostgreSQL first. That choice determines which hosts you can use for the frontend. The Start and mobile editions have their own deployment paths.

EditionSupported targets
apps/web and apps/server (React + Hono)Railway, AWS, or GCP for the Bun API and PostgreSQL; the static frontend on its native AWS or GCP host or Cloudflare.
apps/mobile (Expo)No infrastructure of its own: app stores and Expo updates, talking to the web foundation's API.
apps/start (TanStack Start)Cloudflare Workers and D1, deployed with one command. See apps/start/docs/deploy.md.

Start with Go live when coordinating product, provider, backup, and browser proof. Use this page for the supported infrastructure and release mechanics of the web foundation.

BackendNative frontendExternal frontendAPIPostgreSQLConfigured by
RailwaynoneCloudflare Workers Static AssetsRailway serviceRailway PostgreSQLapps/server/railway.toml
AWSS3 + CloudFrontCloudflare Workers Static AssetsECS Fargate + HTTPS ALBRDS PostgreSQL 18OpenTofu (infra/roots/aws)
GCPGCS + Cloud CDNCloudflare Workers Static AssetsCloud RunCloud SQL PostgreSQL 18OpenTofu (infra/roots/gcp)

OpenTofu manages the AWS and GCP targets and becomes more useful as environments and teams grow. The repository supports OpenTofu 1.13.2 only. It does not claim Terraform compatibility.

Choose a target

Use Railway for the shortest managed deployment path. Choose AWS or GCP when provider-native identity, networking, observability, and managed PostgreSQL are required. Every target runs the same apps/server/Dockerfile image and the same migrate-then-serve release contract.

Each environment has one backend, one object-storage provider, and one frontend target. AWS defaults to S3 and may select R2. GCP defaults to GCS and may select R2. Railway uses R2.

  • native creates the cloud-native static host. It exists for AWS and GCP only.
  • cloudflare accepts an existing exact production origin and creates no Cloudflare resources. Railway always uses it.

Multi-cloud means portability between independent environments. It does not mean active-active operation, cross-cloud replication, or shared state.

The application creator asks Set up cloud deployment now? when the web foundation is included. Choose yes to select AWS, GCP, or Railway, then the storage provider, frontend host, environment, sibling production domains, and, for AWS and GCP, the region and the cost-first or HA profile. It writes deployment/config.json, generates an exact checklist in deployment/README.md, and removes every unused deployment path:

  • AWS or GCP removes the other cloud's OpenTofu root and release scripts and apps/server/railway.toml;
  • Railway removes infra/, scripts/deploy/, .github/workflows/deploy-cloud.yml, and the verify:infra script;
  • a native frontend removes apps/web/wrangler.toml.

The selection is deliberately locked so a later agent cannot silently turn one environment into a different provider.

Choose no to keep every provider while the product is still local. Configure and prune them later from the generated repository with:

bun run deploy:configure

Restore removed paths from a fresh licensed release before changing a locked provider.

Delivery files

  • apps/server/Dockerfile builds the shared production image.
  • apps/server/railway.toml defines the Railway release and service commands.
  • scripts/verify-production-image.sh proves the image migrates before it serves, using the disposable topology in scripts/production-image/.
  • apps/web contains the static SPA and its Cloudflare adapter, apps/web/wrangler.toml.
  • .github/workflows/deploy-cloud.yml implements the AWS and GCP OIDC release sequence.

apps/start deploys separately through apps/start/wrangler.jsonc and .github/workflows/deploy-start.yml; see apps/start/docs/deploy.md.

Runtime contract

The compiled image exposes two deployment commands:

./server migrate
./server serve

migrate resolves the external migration directory, takes a PostgreSQL advisory lock, applies each pending dbmate up section transactionally, and exits. Concurrent invocations serialize. serve validates its external email templates, connects to PostgreSQL, and starts HTTP without changing the schema.

/health is process liveness and never queries PostgreSQL. /ready returns 200 only after startup resources are loaded and PostgreSQL answers a probe. Managed load balancers and container health checks use /ready for traffic admission.

Application endpoint limits use PostgreSQL atomic fixed windows, so replicas share one budget. Better Auth keeps its own database limiter. Set pool limits so:

maximum replicas × (APP_DB_POOL_MAX + AUTH_DB_POOL_MAX) ≤ 80% of database connections

Every cloud module enforces this calculation from its declared connection capacity. On Railway, set the two pool variables against the PostgreSQL service's connection limit yourself.

Prove the image locally before a first release or after changing the Dockerfile, migrations, or email templates:

bash scripts/verify-production-image.sh

It builds the image, starts a disposable PostgreSQL, runs ./server migrate to completion, then starts ./server serve as uid 1000 and checks that the API never applied migrations itself.

OpenTofu layout

infra/
  bootstrap/{aws,gcp}/
  modules/{aws,gcp}/
  roots/{aws,gcp}/
  tests/verify.sh
deployment/
  config.json
  README.md

Each root has an independent backend, provider constraints, committed provider lock, example environment values, and mocked cost-first and HA tests. Environments use separate state paths or state buckets, never OpenTofu workspaces.

deployment/config.json is the committed, non-secret source for common inputs. deployment/README.md lists the state, OIDC, DNS, secret-manager, and GitHub environment work that requires the buyer's cloud authorization.

Verify all roots with:

bun run verify:infra

This runs tofu fmt -check -recursive, backend-free initialization with a read-only lock, validation, and mocked tofu test plans for every root.

State bootstrap

Run the matching bootstrap once with a tightly controlled administrator identity:

  • infra/bootstrap/aws/README.md creates a private, encrypted, versioned S3 bucket using native use_lockfile locking.
  • infra/bootstrap/gcp/README.md creates a uniform-access, versioned GCS bucket dedicated to one environment. GCS provides native state locking.

Copy the output into backend.hcl outside version control. Real backend.hcl, .tfvars, .tfstate, .terraform/, and generated cloud credentials are excluded from buyer scaffolds. Only examples and provider locks ship.

Common inputs and outputs

All roots accept project_name, environment, region, storage_provider, frontend_target, external_frontend_origin, api_domain, frontend_domain, image_digest, traffic_enabled, ha_enabled, API sizing, replica limits, pool limits, database sizing, backup retention, log retention, deletion protection, and an optional alert email. The DNS zone input is provider-specific because provider zone identifiers are not interchangeable.

The AWS and GCP roots provision native application storage only when storage_provider is s3 or gcs. They create separate staging and public buckets, exact-origin CORS, one-day staging expiry, public profile-image reads, and workload-identity permissions. When storage_provider is r2, the operator supplies R2 configuration through the cloud's runtime secret container. See Storage.

External frontends require external_frontend_origin. It must be the exact stable production origin, not a preview URL. Guided setup derives it from the selected frontend domain. The workflow supplies the immutable sha256: OCI image_digest; buyers do not guess the first digest. traffic_enabled remains false until the first migration succeeds. Provider-specific SKU overrides fail at provider planning or apply with the selected region and requested SKU visible; if a default database SKU is unavailable, set the documented db_instance_class, db_tier, or db_sku_name override instead of silently accepting a larger tier.

Every root returns:

  • api_origin and frontend_origin;
  • container_repository;
  • api_service_id, migration_job_id, and the provider-specific release_target;
  • database_secret_id, never its value;
  • dns_validation_records;
  • native_frontend_target and native_frontend_deployment;
  • observability_url.

AWS quickstart

Guided setup keeps the AWS root and removes the GCP root and the Railway configuration. Bootstrap state once, put the Route 53 zone or existing certificate identifiers in the protected TFVARS_JSON overlay, then use the deployment workflow. For direct OpenTofu inspection:

cd infra/roots/aws
tofu init -backend-config=/protected/aws-backend.hcl
tofu plan -var-file=/protected/aws.tfvars

Cost-first runs one public-subnet Fargate task reachable only from the ALB security group and a private, encrypted, single-AZ db.t4g.micro RDS instance. It creates no NAT gateway. HA runs two API tasks in private subnets, one NAT gateway per availability zone, Multi-AZ RDS, and an ECS deployment circuit breaker. The native frontend is a private S3 bucket read only through CloudFront Origin Access Control, with immutable asset caching and no-cache HTML.

GCP quickstart

Guided setup keeps the GCP root and removes the AWS root and the Railway configuration. Bootstrap state once, put the project and Cloud DNS inputs in the protected TFVARS_JSON overlay, then use the deployment workflow. For direct OpenTofu inspection:

cd infra/roots/gcp
tofu init -backend-config=/protected/gcp-backend.hcl
tofu plan -var-file=/protected/gcp.tfvars

Cost-first runs Cloud Run from zero to three instances and a private-IP zonal db-f1-micro Cloud SQL instance. HA keeps at least one Cloud Run instance warm, uses regional Cloud SQL HA, and enables point-in-time recovery. Cloud Run uses Direct VPC egress. The API sits behind the external HTTPS load balancer so the gcp-cloud-run proxy profile can validate the provider-appended forwarding shape. The native frontend uses a versioned GCS bucket, a backend bucket, Cloud CDN, and managed TLS.

Railway quickstart

Guided setup keeps apps/server/railway.toml and removes every OpenTofu path. Railway has no OpenTofu root: its project, services, and variables live in the Railway dashboard or CLI, and deployment/README.md lists the exact values for the locked environment.

  1. Create a Railway project with a PostgreSQL service and an API service connected to this repository. Build from the repository root, because the image copies the whole workspace.
  2. Set the API service's config-as-code path to apps/server/railway.toml. Its preDeployCommand runs ./server migrate, its start command runs ./server serve, and traffic waits for /ready. A failed migration fails the deploy and leaves the previous deployment serving.
  3. Set DATABASE_URL from the PostgreSQL service's private connection string, plus ENVIRONMENT=production, TRUSTED_PROXY_PROFILE=railway, DEPLOYMENT_CLOUD=railway, the exact FRONTEND_URL and SERVER_URL, and the values in Secrets. Railway injects PORT; leave it unset.
  4. Add the API domain to the service and publish the DNS records Railway reports. A Cloudflare-managed zone keeps them DNS only: proxying the record hides the client IP the railway proxy profile reads and blocks Railway's certificate issuance.
  5. Deploy the frontend to Cloudflare Workers Static Assets.

Railway backups, replicas, and alerts are configured on the Railway services. Schedule and restore-test a PostgreSQL backup before the first paying customer.

Frontend selection

The browser has one provider-neutral backend variable:

VITE_APP_ENV=production
VITE_API_URL=https://api.example.com
VITE_TERMS_URL=https://example.com/terms/
VITE_PRIVACY_URL=https://example.com/privacy/
VITE_MARKETING_URL=https://example.com

VITE_MARKETING_URL is optional. Setting it links the brand lockup on the authentication screens to your marketing site and adds a "Website" entry to the account menu; leaving it unset renders both without a link. The marketing site in apps/site deploys separately with bun run deploy:site.

Every target keeps the deployed application out of search results with the noindex, nofollow meta tag in apps/web/index.html, which the SPA fallback serves on every route. apps/web/public/robots.txt allows crawling on purpose, because a blocked URL is never fetched and is therefore still eligible for URL-only indexing on the strength of inbound links alone. Publish a route by removing the meta tag, not by editing robots.txt.

Native

Native hosting exists for AWS and GCP. The protected deployment workflow builds apps/web after the API is ready. AWS syncs hashed assets with immutable caching and invalidates only index.html. GCP synchronizes the bucket, sets asset and HTML cache metadata, and refreshes the HTML CDN entry.

Cloudflare Workers Static Assets

Create a Workers project rooted at apps/web and use apps/web/wrangler.toml. It contains only the dist asset directory and not_found_handling = "single-page-application"; there is no Worker API entry point. Build with bun run build:prod, set VITE_API_URL to the stable API origin, and attach the exact frontend_domain as the Worker's custom domain. Prefer Cloudflare Git integration. An API-token deployment is optional, but the token must live in a protected deployment environment.

The web foundation uses Cloudflare for static assets only; its API stays on Railway, AWS, or GCP. An API Worker, D1, Hyperdrive, Containers, Queues, or Durable Objects under apps/web are unsupported. A product that wants its whole stack on Cloudflare starts from the TanStack Start edition instead.

Documentation site

apps/docs is a separate Next.js application and is not deployed by the product frontend or OpenTofu paths. It requires its own Node-compatible host and public-origin verification when a buyer chooses to publish it. Follow Operate the documentation site; do not point the SPA deployment workflow at the docs workspace.

Mobile edition

apps/mobile is not deployed by any path on this page. It is distributed through the app stores and Expo's update service, and it needs no infrastructure of its own — it talks to the same API this page provisions. Follow Mobile for the EAS build, submit, and over-the-air runbook.

Two deployment values do belong to the API side:

VariableEffect
MOBILE_APP_SCHEMEThe URI scheme the app registers. Native callbacks are validated against it.
PUSH_NOTIFICATIONS_ENABLEDtrue before push reaches a device; false logs instead of calling Expo.

MOBILE_APP_SCHEME must match the scheme in apps/mobile/app.json. A mismatch is not a silent failure: native sign-in is refused with INVALID_CALLBACK_URL, and the app reports the mismatch by name. EXPO_PUBLIC_API_URL is baked into a mobile bundle at export time, so a change to the API hostname needs a new build or update, not just a server deploy.

DNS, CORS, and same-site auth

Production uses stable HTTPS names such as app.example.com and api.example.com. Keep them under the same registrable site so Better Auth cookies do not depend on third-party-cookie exceptions. OpenTofu configures the exact frontend origin in FRONTEND_URL; Hono CORS and Better Auth trusted origins reject any other origin.

Preview domains never use the production API. Give previews a stable staging alias and staging API under the same registrable site.

A native client is not a browser origin and is not added to CORS_ORIGIN. It is trusted through MOBILE_APP_SCHEME instead; see Native clients.

TRUSTED_PROXY_PROFILE is one of direct, railway, aws-alb, or gcp-cloud-run. The runtime discards a user-supplied internal client-IP header and rebuilds it from the selected ingress shape. Do not expose the container through another public path.

Secrets

Never put Better Auth, email, billing, Sentry, R2 credentials, OAuth, or secret provider values in committed .tfvars. On AWS and GCP, OpenTofu creates the cloud secret container and runtime identity, and a protected workflow writes values directly to Secrets Manager or Secret Manager before the first application release. On Railway, set them as service variables in the protected Railway environment.

On AWS and GCP, database credentials are generated by OpenTofu because the database resource requires them. They remain sensitive in encrypted state and are written to a database URL secret. No root outputs the credential value.

Required production application values remain documented in apps/server/.env.example, including BETTER_AUTH_SECRET, RESEND_API_KEY, exact FRONTEND_URL, exact SERVER_URL, pool limits, deployment metadata, the proxy profile, and SENTRY_PROJECT_IDS when the browser error tunnel is enabled.

Provider-specific application contracts remain in Billing, Storage, and the background-work decision.

GitHub OIDC and release workflow

.github/workflows/deploy-cloud.yml uses a protected GitHub environment and OIDC. Configure only the matching identity inputs:

  • AWS: AWS_ROLE_ARN;
  • GCP: GCP_WORKLOAD_IDENTITY_PROVIDER and GCP_SERVICE_ACCOUNT.

Each environment also supplies protected BACKEND_HCL and TFVARS_JSON values plus public frontend and legal URL variables. TFVARS_JSON is only the provider-specific overlay; the workflow merges it with the locked non-secret deployment/config.json. Long-lived AWS keys and service-account JSON are unsupported.

The workflow rejects cloud, environment, or frontend dispatch inputs that disagree with the locked configuration. On the first release it creates only the selected container repository, builds and pushes one linux/amd64 image, provisions runtime infrastructure with public API traffic disabled, and runs the migration primitive. A successful migration admits traffic; a failed migration leaves the new service private or scaled to zero. Later releases preserve existing traffic until migration succeeds, then update the API to the exact digest. API resources ignore image drift from OpenTofu so an infrastructure apply cannot bypass the release primitive.

After readiness, the workflow builds the native frontend and runs:

API_ORIGIN=https://api.example.com \
WEB_ORIGIN=https://app.example.com \
bash scripts/verify-public-deployment.sh

Cloudflare Git integration deploys its own static build after VITE_API_URL is updated to the stable API origin.

Rollback and failed release recovery

Deploy additive expand/contract migrations once more than one API revision can overlap. Never automatically run database downs. On failure:

  1. preserve the migration execution logs and image digest;
  2. leave the previous API revision receiving traffic;
  3. fix forward unless a reviewed down is demonstrably data-safe;
  4. rerun the migration job with a new immutable image;
  5. release the API only after the job exits zero and readiness passes.

Application rollback selects the prior image digest. Frontend rollback redeploys the prior static artifact. If wire contracts changed, restore a compatible API/frontend pair.

Promote cost-first to HA

HA promotion applies to the OpenTofu clouds. Set ha_enabled=true, review the cost and topology plan, confirm the selected region supports every zone-redundant feature, and apply through the protected environment. Promotion changes availability; it does not migrate providers or combine entitlements across deployments.

Troubleshooting

  • Pool-capacity check failure: lower replicas or pool limits, or explicitly select a larger database tier and its documented connection capacity.
  • Database SKU unavailable: set the provider-specific tier override or choose a supported region.
  • API never ready: inspect database reachability, external migrations/templates, and the release digest metadata in structured logs.
  • CORS failure: compare the literal browser Origin with frontend_origin; wildcards are not used.
  • Incorrect client IP: confirm only the supported ingress reaches the service and select its exact proxy profile.
  • Managed certificate pending: publish every returned DNS validation record and wait for provider issuance before retrying.
  • OpenTofu lock mismatch: run the pinned OpenTofu 1.13.2 release, review provider changes, regenerate the lock intentionally, and commit it.

Teardown

Teardown is destructive and never part of the deployment workflow. On Railway, delete the services only after a retained and restore-tested database backup exists. In a disposable environment, set deletion_protection=false, apply that reviewed change, verify the selected state and cloud account, then run tofu destroy. Delete state backends, backups, registries, or customer data only with separate explicit authority. Production teardown requires a retained and restore-tested database backup.

Proof ledger

Mocked cost-first and HA plans are repository evidence, not live-cloud acceptance. The production image proof is repository evidence for the release contract every target shares. The landing page must not advertise the five web frontend/backend combinations (AWS or GCP with a native or Cloudflare frontend, and Railway with Cloudflare) as live-proven until disposable-environment records prove custom-domain auth, CORS, CRUD ownership denial, migration failure, rollback, caching, logs, alarms, no-drift plans, and apply/destroy for every combination.

On this page