Cloudflare Workers
Set up D1, R2, and production secrets step by step, then deploy with Workers Builds or GitHub Actions.
Deploy apps/web-cloudflare to Cloudflare Workers. Complete the 5 shared setup steps first, then pick one release path per production Worker.
Path A · Cloudflare Workers Builds
Connect your GitHub repository in the Cloudflare dashboard to build and publish automatically on every push or merge to your production branch.
Path B · GitHub Actions
Run the included Deploy Cloudflare Worker workflow manually with built-in workerd smoke tests and strict remote D1 checks.
Start here if you use Windows
On native Windows, use pnpm dev:cf for local development and the project's Wrangler CLI to provision resources and run D1 migrations. OpenNext has limited support for native Windows, so both release paths build the production Worker remotely on Linux. See OpenNext's Windows support notes.
All in on Cloudflare with a CLI workflow
If you’re starting a new product and want to plan, publish, and verify from the terminal, see MuseMVP Flare. Its TanStack Start app builds for Workers with Cloudflare’s Vite plugin, and the Flare deployment guide walks through muse:doctor, muse:deploy --plan, muse:deploy --yes, and muse:verify.
Before You Start
Confirm the following prerequisites before running the setup commands (run all local commands from the repository root):
- You have your own GitHub repository, Cloudflare account, and production hostname, and have completed Quick Start.
- Use brand-new remote D1 and R2 resources for a first launch. If you have existing users or business data, prepare an upgrade plan first.
Here are the key files involved in deploying apps/web-cloudflare:
1. Prepare the Account and Resources
These commands work in PowerShell and POSIX shells. Replace the sample my-app prefix with your own product name. After signing in, verify that wrangler whoami shows the exact Cloudflare account you intend to use before creating resources.
pnpm install --frozen-lockfile
pnpm --filter @musemvp/cloudflare exec wrangler login
pnpm --filter @musemvp/cloudflare exec wrangler whoami
pnpm --filter @musemvp/cloudflare exec wrangler d1 create my-app-db
pnpm --filter @musemvp/cloudflare exec wrangler r2 bucket create my-app-r2Record these four values immediately—you will need them in wrangler.jsonc and the Cloudflare dashboard:
| Resource | Example | What to verify |
|---|---|---|
| Worker name | my-app | Must match both the Cloudflare dashboard Worker and name in wrangler.jsonc |
| D1 name & ID | my-app-db / <your-d1-id> | Copy the exact database_id printed by wrangler d1 create |
| R2 bucket name | my-app-r2 | Stores user avatars and uploaded assets |
| Production hostname | app.example.com | Custom domains must belong to a zone managed in the same Cloudflare account |
Verify account features and quotas
Confirm that your target Cloudflare account can use Workers, D1, R2, and Email Sending, and check your plan's quotas and compressed Worker size limits. See Cloudflare Custom Domains · Workers limits
2. Configure Bindings
In apps/web-cloudflare/wrangler.jsonc, replace the demo's resource IDs, domain, and names with your own while keeping the rest of the template's compatibility and runtime settings. This excerpt highlights the fields to check:
{
"name": "my-app",
"main": ".open-next/worker.js",
"workers_dev": false,
"preview_urls": false,
"routes": [{ "pattern": "app.example.com", "custom_domain": true }],
"assets": { "binding": "ASSETS", "directory": ".open-next/assets" },
"d1_databases": [{
"binding": "DB",
"database_name": "my-app-db",
"database_id": "<your-d1-id>",
"migrations_dir": "../../packages/db/migrations-d1"
}],
"r2_buckets": [{ "binding": "R2_BUCKET", "bucket_name": "my-app-r2" }]
}| Binding | Service | Purpose |
|---|---|---|
DB | Cloudflare D1 | Primary database; the D1 migration script reads the database name bound to DB |
R2_BUCKET | Cloudflare R2 | Avatars and asset uploads, accessed through same-origin /files/avatars/* routes |
ASSETS | OpenNext static assets | Serves .open-next/assets; keep the binding name unchanged |
Regenerate types after binding changes
Run pnpm cf:typegen whenever you edit bindings in wrangler.jsonc. If you want to test on the default workers.dev hostname first, remove routes and set workers_dev to true.
3. Initialize Locally
Run these commands to generate local env files, check environment health, and start the dev server:
pnpm muse:init --app cloudflare
pnpm muse:doctor --json
pnpm dev:cfInit writes apps/web-cloudflare/.env.local and .dev.vars, and applies local D1 migrations automatically.
| Seed Account | Role | Default Password | Notes |
|---|---|---|---|
[email protected] | Admin | musemvp | Override with MUSE_SEED_PASSWORD |
[email protected] | User | musemvp | Local development only—never use in production |
Keep .env.local and .dev.vars in sync
After editing apps/web-cloudflare/.env.local, rerun pnpm muse:init --app cloudflare to synchronize .dev.vars. These files, local databases, and seed accounts are strictly for local development.
Preview the Built Worker on Linux
Use pnpm dev:cf for daily development (verification codes print directly to the terminal). To test the production-mode Worker bundle locally under workerd on Linux, use pnpm cf:preview.
Because production mode rejects the MAIL_PROVIDER=console default written by init, pass cloudflare temporarily for both the build and the local Worker preview:
pnpm db:migrate:d1:local
MAIL_PROVIDER=cloudflare pnpm cf:preview --var MAIL_PROVIDER:cloudflare --ip 127.0.0.1 --port 8787Once the preview server is listening, run the smoke check in a second terminal to verify the home page, health endpoint, sign-in page, and signed-out redirect:
node scripts/cf-smoke.mjs http://127.0.0.1:8787Configure and test real Cloudflare Email Sending credentials separately when verifying live email delivery.
4. Configure Production Variables and Secrets
Use the Environment Variables guide as your reference. Create a Worker in the Cloudflare dashboard matching name in wrangler.jsonc, then place each value in the right scope:
Configure in your production build environment (Workers Builds Build variables and secrets, or GitHub Actions Variables):
NEXT_PUBLIC_SITE_URL(required): Final HTTPS origin, e.g.https://app.example.com(no trailing slash).NEXT_PUBLIC_DEFAULT_LOCALE(optional): Default site locale.NEXT_PUBLIC_EMAIL_SUPPORT(optional): Public support email address.NEXT_PUBLIC_TURNSTILE_SITE_KEY(optional): Cloudflare Turnstile site key.NEXT_PUBLIC_GOOGLE_ONE_TAP_CLIENT_ID(optional): Google One Tap client ID.
Public variables are inlined at build time. Rebuild and redeploy after changing any
NEXT_PUBLIC_*value.
Never copy local env files to production
Configure production secrets independently and keep .env.local and .dev.vars strictly in local development. See Workers Builds variables · Worker secrets
5. Migrate Production D1
Before your first launch—and before any release that adds new migrations—verify your Wrangler account, database name, and ID, then check status, apply remote migrations, and confirm the strict check passes:
pnpm db:migrate:d1:status
pnpm db:migrate:d1:remote
pnpm db:migrate:d1:status --strictBackups and backward-compatible schemas
pnpm db:migrate:d1:remoteexports a backup, rehearses and checks migrations on a local clone, and then applies them remotely. Store backups securely because they may contain user data.pnpm cf:deploychecks whether remote D1 is current and stops automatically when migrations are pending.- For an existing production app, keep the currently running Worker compatible with the D1 schema during migration.
Once the 5 shared steps above are complete, choose one of the two release paths below for your production Worker.
Cloudflare Workers Builds
Best when you want pushes and merges to your production branch to deploy automatically from the Cloudflare dashboard.
Connect your repository and production branch
Open the target Worker in Cloudflare and go to Settings → Builds → Connect. Authorize the Cloudflare Workers & Pages GitHub App to access your product repository, then select the repository and production branch.
Set the monorepo root directory
Set Root directory to apps/web-cloudflare. Confirm that wrangler.jsonc uses the same Worker name as the dashboard, and keep the root pnpm-lock.yaml and workspace files in the repository for dependency installation.
Configure build variables
Under Build variables and secrets, add the public variables from Step 4 along with:
NODE_VERSION=24
MAIL_PROVIDER=cloudflareSet the Build command
Use the command below to supply a temporary auth secret to OpenNext during the build (production runtime still uses your Worker Secrets):
BETTER_AUTH_SECRET="$(node -p 'require("node:crypto").randomBytes(32).toString("hex")')" pnpm exec opennextjs-cloudflare buildSet the Deploy command and monitor releases
Set Deploy command to:
pnpm exec opennextjs-cloudflare deployUpdates to the production branch will now trigger releases automatically. Monitor logs under Deployments → View build history.
D1 checks and smoke tests on Workers Builds
When a commit includes a new migration, complete Step 5 and confirm pnpm db:migrate:d1:status --strict passes before pushing or merging to the production branch. Dashboard commands only build and publish the Worker—run D1 checks and smoke tests separately on this path. See Cloudflare's GitHub integration · Workers Builds monorepo setup · OpenNext's Workers Builds guide
GitHub Actions
Best when you want manual release control backed by automated builds, local workerd smoke tests, strict remote D1 checks, and live production verification.
Confirm the workflow file is on your default branch
Verify that .github/workflows/cloudflare-deploy.yml exists on your default branch. If you started from an older template, sync the workflow and its companion scripts first—see MuseMVP PR #159.
Create a scoped Cloudflare API token
In Cloudflare, go to My Profile → API Tokens → Create Token and create a custom token:
- Account Permissions:
Workers Scripts → Edit,D1 → Read - Account Resources: Restrict to the single account hosting your production Worker and D1 database
Add GitHub Actions Variables and Secrets
In GitHub, open Settings → Secrets and variables → Actions:
- Under Variables, add the public variables from Step 4 plus
CLOUDFLARE_ACCOUNT_ID. - Under Secrets, save the deployment token as
CLOUDFLARE_DEPLOY_API_TOKEN.
Trigger the workflow and verify the run
Push or merge the release commit onto your default branch, then trigger the workflow via UI or CLI:
Open Actions → Deploy Cloudflare Worker → Run workflow, select the default branch, and start the run.
The Ubuntu runner verifies the commit and target, builds once with OpenNext, smoke-tests the bundle under workerd with local D1, runs pnpm db:migrate:d1:status --strict, deploys the verified bundle, and runs smoke checks on your production domain.
After completion, open Check remote D1 and publish the verified Worker to record Current Version ID, and confirm Verify production passed.
Switching from Workers Builds to GitHub Actions?
Disconnect the repository under the Worker's Settings → Builds before running the GitHub workflow so both systems do not publish over each other. See Disconnecting Workers Builds
Check Your Result
After deployment succeeds, verify the release on your production HTTPS domain:
- Confirm release metadata: Check the expected Git commit and Worker Version ID in the release logs or Cloudflare Deployments.
- Check public endpoints & redirects: Verify the home page,
/api/health, sign-in page, and the signed-out redirect from/app. - Verify core user journeys: Register with a real mailbox to confirm email delivery and sign-in, then test uploading and downloading your own avatar.
Build checks vs. Worker runtime behavior
pnpm build:cf checks the Next.js application build. To verify Worker runtime behavior, follow the Linux preview steps above and keep the template's webpack build configuration and lockfile intact.
Complete the Release Checklist
Verify bilingual routes, OAuth, permissions, payment webhooks, R2 isolation, and rollback readiness.
Environment Variables Reference
Review every required and optional variable along with where it belongs.
Common Problems
Expand any issue below for quick diagnosis and fixes: