Deploy on Cloudflare
Set up your own free-tier DireWork instance, one step at a time
DireWork runs on Cloudflare Workers with a D1 (SQLite) database — two small workers and a database. The core app supports Cloudflare's free plan within its account quotas. Free-tier support is a project commitment; no paid Cloudflare service is required. No servers or Docker to maintain.
You deploy these resources to your own Cloudflare account and operate your own instance. DireWork is always self-hosted; MrDemonWolf, Inc. does not provide a hosted or managed service.
Quick start
Use Cloudflare + GitHub Actions. You configure accounts once; the Deploy workflow then creates and updates the app and database for you. You do not need a server or a local development environment. Cloudflare remains the default, with free-tier support for the core app; account quotas still apply.
Work through these in order. The detailed steps below use the same numbers:
- Prepare: fork DireWork, sign in to Cloudflare, and find your workers.dev subdomain under Workers & Pages.
- 1. Cloudflare: create one API token.
- 2. Twitch: create or open your Twitch app and add both callback URLs. Save its client ID and secret.
- 3. GitHub: add seven secrets and two variables to your fork. The tables below give their exact names.
- 4. Deploy and claim: enable Actions and run Deploy. Keep the run open. When it turns green, open your app and Claim with Twitch immediately.
- Finish: connect your bot account, keep one bot page open (the widget or the dock), add the overlays, and complete the live checklist.
The Deploy on Cloudflare link opens this guided setup. It does not create resources with a single click. Twitch authorization and your private credentials still need your input. After setup, Actions → Deploy → Run workflow runs the deployment.
About Cloudflare's native deploy button
Cloudflare's native Deploy to Cloudflare button discovers resources through a repository's Wrangler configuration. DireWork instead uses Alchemy to coordinate two Workers, D1 migrations, shared deployment state and post-deploy checks. There is no committed Wrangler configuration for that setup.
The Workers Builds monorepo guide describes connecting each Worker separately. We have not validated a native-button integration that preserves DireWork's full deployment flow. Use the GitHub Actions path below; the setup link deliberately avoids promising unsupported provisioning.
What gets deployed
| Piece | Where | What it does |
|---|---|---|
dirework | dirework.<your-subdomain>.workers.dev | The web app — dashboard, overlays, bot page |
dirework-api | dirework-api.<your-subdomain>.workers.dev | The API — sign-in, tRPC, bot OAuth |
dirework-db | Cloudflare D1 | Your tasks, timer, and settings |
The web app proxies sign-in and dashboard traffic to the API worker behind the scenes,
so everything works from the one dirework.…workers.dev address.
Before you start
- A Cloudflare account (free plan is fine)
- Your two Twitch keys (client ID + secret)
- A fork or copy of the DireWork repository on GitHub
- Your workers.dev subdomain: Cloudflare dashboard → Workers & Pages → the
Subdomain shown in the account details panel (for example
aliceinalice.workers.dev). Every<your-subdomain>below means that label, so your web origin ishttps://dirework.alice.workers.dev. A new account picks its subdomain the first time it opens Workers & Pages.
Step 1 — Create a Cloudflare API token
- Cloudflare dashboard → My Profile → API Tokens → Create Token
- Use the Edit Cloudflare Workers template, and add D1 → Edit permissions
- Under Account Resources, choose Include → your account. The deploy uses the first account the token can see, so a token scoped to one account always deploys there.
- Copy the token — this is
CLOUDFLARE_API_TOKEN
Step 2 — Tell Twitch about your domain
In the Twitch Developer Console, create a Confidential application if you do not already have one (see Twitch setup), or open your existing app, and add these two redirect URLs (swap in your workers.dev subdomain):
https://dirework.<your-subdomain>.workers.dev/api/auth/callback/twitch
https://dirework.<your-subdomain>.workers.dev/api/bot/callback/twitchYou can keep your localhost URLs in the list too, so local development still works.
Step 3 — Set your GitHub secrets
The deploy job runs in a GitHub environment named production, so keep the secrets
there: only that job can read them, and any protection rules you add to the environment
(required reviewers, deploying only from main) apply to every deploy. In your repository:
Settings → Environments → New environment, name it production, then
Add environment secret for each row below. (Repository secrets under Settings →
Secrets and variables → Actions still work as a fallback, but every workflow can read
those; an environment secret with the same name wins.)
| Secret | Value |
|---|---|
CLOUDFLARE_API_TOKEN | the token from Step 1 |
ALCHEMY_PASSWORD | random string, at least 32 characters (e.g. openssl rand -base64 32) — encrypts deploy state |
ALCHEMY_STATE_TOKEN | a unique random token (min 32 characters) for the account-wide alchemy-state CI store worker; reuse it only across apps intentionally sharing that same worker |
BETTER_AUTH_SECRET | another long random string (openssl rand -base64 32) |
PROXY_SECRET | a third long random string (openssl rand -base64 32, min 32 characters) — lets the API rate limiter tell browsers apart behind the web worker's proxy |
TWITCH_CLIENT_ID | from the Twitch console |
TWITCH_CLIENT_SECRET | from the Twitch console |
Generate fresh secrets for production — never reuse the ones from your computer.
Generate each of the four random values separately with your password manager, or
run openssl rand -base64 32 four times. Save ALCHEMY_PASSWORD and
ALCHEMY_STATE_TOKEN securely: future deploys need the same values.
And set these repository variables
Switch to the Variables tab (same Settings → Secrets and variables → Actions page) → New repository variable. Swap in your own workers.dev subdomain:
| Variable | Value |
|---|---|
BETTER_AUTH_URL | https://dirework.<your-subdomain>.workers.dev (your web origin) |
CORS_ORIGIN | https://dirework.<your-subdomain>.workers.dev (same web origin) |
Optional repository variables are supported too; leave them unset to use the defaults:
| Variable | Purpose |
|---|---|
DOCS_URL | HTTPS documentation origin used by !dwhelp and the home page's docs links |
PRIVACY_POLICY_URL | HTTPS privacy-policy page linked from the footer |
TERMS_OF_SERVICE_URL | HTTPS terms page linked from the footer |
The deploy workflow reads these via ${{ vars.* }} — you don't edit the workflow file.
It validates every required value, minimum secret lengths, same-origin HTTPS URLs,
optional external URLs, and disabled development-login flags before touching Cloudflare.
Invalid configuration fails before any deployment begins.
There is deliberately no NEXT_PUBLIC_SERVER_URL variable. Alchemy resolves the API
worker's URL during the deploy and injects it into both the web build and the runtime
binding. Setting it as a repository Variable does nothing — and a stale value there is
actively misleading when you're debugging. It's a local-development variable only.
Step 4 — Run the first deploy
Forked the repo? GitHub turns off workflows on new forks. Open the Actions tab
and click I understand my workflows, go ahead and enable them first. A fork already
has a main with nothing new to push, so start the first deploy from Actions → Deploy
→ Run workflow.
Every push to main runs the full verification pipeline — dependency audit, lint,
type check, tests with coverage thresholds, and a production build — and only then deploys via
Alchemy: both workers, the D1 database, and its migrations.
CodeQL also runs extended static security analysis on pushes, pull requests, and weekly.
You can also trigger a deploy by hand from the Actions tab (Deploy → Run workflow).
On a deploy the dependency audit only warns (a yellow annotation on the run): a
freshly published advisory must never block a revert or hotfix. Pull requests still fail
on high-severity advisories, so fix them there.
✅ Visit https://dirework.<your-subdomain>.workers.dev as soon as the Deploy run turns
green. You should see the DireWork setup screen. Click Claim with Twitch and sign in
with your streamer account to become the owner.
Sign in immediately after the first deploy. Until someone signs in, the instance is
unclaimed, and the first Twitch account to sign in — anyone's — becomes its permanent
owner. workers.dev hostnames are predictable (dirework.<your-subdomain>.workers.dev),
so keep the Deploy run open, sign in the moment it finishes, and don't post or share the
URL before then. When the Dashboard greets you by your own Twitch name, you're safe:
every later sign-in by another account is refused. If someone else got there first, see
Recovering an instance someone else claimed.
The docs site workflow (Build and deploy docs to GitHub Pages) only runs on the
upstream repository. Forks don't need it; your instance's !dwhelp links point at
DOCS_URL, which defaults to the public docs.
Deploying from your own machine (optional)
Prefer the command line? packages/infra/.env, apps/web/.env and apps/server/.env
hold your local development values (http://localhost URLs), which a production deploy
rejects. Export the production values in your shell instead — they take precedence over
anything in the .env files. Any variable you don't export is still read from those three
files, so also override the dev-only ones:
export CLOUDFLARE_API_TOKEN="..."
export ALCHEMY_PASSWORD="..."
export BETTER_AUTH_SECRET="..."
export PROXY_SECRET="..."
export TWITCH_CLIENT_ID="..."
export TWITCH_CLIENT_SECRET="..."
export BETTER_AUTH_URL="https://dirework.<your-subdomain>.workers.dev"
export CORS_ORIGIN="https://dirework.<your-subdomain>.workers.dev"
export DEV_LOGIN=false NEXT_PUBLIC_DEV_LOGIN=false
bun install
bun run deployA local deploy keeps Alchemy's state in files under packages/infra/.alchemy/, separate
from the state the GitHub Actions deploy keeps, so pick one way to deploy an instance and
stick with it. The deploy refuses to run with DEV_LOGIN or NEXT_PUBLIC_DEV_LOGIN
enabled, so export both as false (or comment them out of the .env files). Optional
URLs such as DOCS_URL, PRIVACY_POLICY_URL and TERMS_OF_SERVICE_URL must use https
in production: if a .env file sets one to an http/localhost value, export the
production URL or remove that line before you run bun run deploy or bun run destroy.
To tear everything down again: bun run destroy (with the same values exported).
A local bun run destroy only sees what a local deploy created. An instance deployed
by GitHub Actions keeps its Alchemy state in the shared Cloudflare state store, so to
destroy it from your machine run it with CI=true and the same ALCHEMY_STATE_TOKEN
as the workflow (plus the values above in packages/infra/.env):
CI=true ALCHEMY_STATE_TOKEN=… bun run destroy. Deploy and destroy always use the
runner stage unless you set ALCHEMY_STAGE.
After you're live — quick checklist
- Both Twitch redirect URLs point at your
dirework.…workers.devdomain - You claimed the instance with your own streamer account (the Dashboard shows your Twitch name)
- Your bot account connects (Dashboard → Bot)
- The bot page is open: the invisible widget in an OBS browser source or a Moblin widget, or the dock in an OBS custom browser dock or a pinned tab — the bot only listens to chat while that page is open. See Chat commands.
- The timer and task list overlays show up in OBS
- A real chat command adds a task, and a timer cycle advances in OBS
- One bot page is open. A second copy won't run commands twice (DireWork dedupes each chat message by its Twitch message id), but every command then costs two Worker requests
- Bot and overlay URLs are kept private and regenerated after any suspected disclosure
-
mainis protected and requires the Verify and CodeQL workflows before merge - Deploy secrets live in the
productionenvironment, with no leftover repository-level copies - GitHub secret scanning and push protection are enabled
- GitHub and Cloudflare accounts use MFA and least-privilege access
- Monitoring and the recovery checks below are complete
Monitoring
Each deploy ends with a smoke check: the workflow fails unless the api worker's /ready
answers with limits: "ok" (it pings D1 and confirms all four rate-limit bindings
attached), the web worker's /api/version reports the commit that was just deployed, the
home page renders, and the dashboard's /rpc proxy refuses an anonymous request (401
from the api, or a Cloudflare Access login redirect; see below). limits reads missing:RL_AUTH,… when a binding did not attach; the worker
stays ready regardless, because the limiter fails open rather than taking the app down,
but the smoke check does not pass it. So a fork's first deploy fails at the smoke check if
the rate-limit bindings did not bind — look for the four RateLimit resources in the
Alchemy step's output.
Cloudflare Access
You can put Cloudflare Access
in front of /dashboard, /setup and /rpc/* as an extra layer on top of DireWork's own
owner check (it never replaces it). The smoke check accepts Access's login redirect
(a 302/303 to https://<team>.cloudflareaccess.com/cdn-cgi/access/login/…) from
/rpc/user.me, and from /setup when an unclaimed instance's home page sends visitors
there, so a fresh deploy passes before you claim it. It says which case passed in its
output. When the Access session runs out on an open dashboard, the dashboard stops
refreshing and shows "Your sign-in expired" with a Reload button, which takes you through
the Access login again. Keep /, /api/*, /bot/* and /overlay/*
outside the Access application: the Twitch OAuth callbacks, the OBS overlays and the bot
page must reach them without an Access login.
For monitoring between deploys, choose one of these options:
- Point a free uptime monitor (UptimeRobot, Better Stack, etc.) at
https://dirework-api.<your-subdomain>.workers.dev/ready. It returns503when D1 is unreachable;/healthonly tells you the worker is running. Check every 5 minutes or slower, as every check counts toward the daily request limit. - No external monitor? Set two repository Variables (same page as Step 3):
UPTIME_API_URL=https://dirework-api.<your-subdomain>.workers.devandUPTIME_WEB_URL=https://dirework.<your-subdomain>.workers.dev. The Uptime workflow (.github/workflows/uptime.yml) then requests/readyand/api/versionevery 30 minutes — 96 Worker requests a day, or up to 288 while both are down and every probe retries — and keeps one issue labelleduptime: it opens the issue when either stops answering, adds a comment while the outage lasts, and comments "Recovered" and closes it once both answer again. Each failed probe is also a failed workflow run, so it shows up with your other Actions failures. Leave the variables unset and the workflow does nothing. GitHub runs schedules only on the default branch, may start one a few minutes late, and pauses them after 60 days without activity in the repository.
Also review usage:
- Review account-wide Workers requests and D1 usage in the Cloudflare dashboard before long streams and after a representative session. Notification types depend on your plan: enable a relevant usage alert if your account offers one, but do not rely on a paid alerting feature for the free-tier setup. See Cloudflare's available notifications.
Recovery checks
Before your first production stream, run the local recovery drill from the repository:
bun run recovery:checkThis exports and restores schema first, then data, for a synthetic local database with the project's migrations. It compares all application rows and schema/indexes and checks foreign keys. It does not read or change production, and it does not test Cloudflare Time Travel. A passing drill confirms the local recovery path, not a recovered production instance.
For your own deployment:
- Export the production database before a recovery operation, using
bunx wrangler d1 export dirework-db --remote --output=dirework-backup.sql. Store that file privately: it contains session data, bot credentials, and private URLs. - Practice importing an export into a separate test database. Check tasks and settings
there before considering the backup usable. Never restore over production as a test.
Create all tables before importing rows that reference them; export schema and data
separately with Wrangler's
--no-dataand--no-schemaflags if a combined import fails on a missing parent table. Data imports may needPRAGMA defer_foreign_keys = ON;at the start; do not disable constraints permanently. - D1 Time Travel is always enabled: the recovery window is 7 days on Free and 30 days on Paid. See Cloudflare's D1 limits.
- After a real restore, review sessions and private URLs and reconnect the bot if needed. A database restore also restores older authorization state; it does not undo Twitch's token changes or roll back Worker code. Follow Rolling back.
Private backup storage and a restore drill are sufficient to start; an R2 bucket or another paid service is not required.
Recovering an instance someone else claimed
DireWork has no in-app way to transfer ownership: the instance counts as claimed while the
D1 user table has any row, and the sign-in hook refuses every new account after that.
So if the Dashboard shows someone else's Twitch name (or your own sign-in fails with "This
DireWork already belongs to a different Twitch account"), reset the owner in D1 and claim
it again.
-
Back up first (optional but cheap):
bunx wrangler d1 export dirework-db --remote --output=dirework-backup.sql -
Delete the other account and everything it could reuse. Run this from a clone of the repo, logged in to the same Cloudflare account (
bunx wrangler login), or paste the SQL into Cloudflare dashboard → Storage & Databases → D1 →dirework-db→ Console:bunx wrangler d1 execute dirework-db --remote --command "DELETE FROM session; DELETE FROM account; DELETE FROM verification; DELETE FROM user; DELETE FROM bot_account; DELETE FROM instance_config;"Statement Why DELETE FROM sessionsigns the other account out everywhere DELETE FROM accountremoves its Twitch sign-in link DELETE FROM verificationdrops any half-finished OAuth sign-in state DELETE FROM userempties the owner table, so the next sign-in claims the instance DELETE FROM bot_accountdisconnects any bot account they connected DELETE FROM instance_configdiscards the overlay and bot URLs they could see, plus the cached chat channel ( channel_login) that would still point your bot at their channel. Fresh tokens are generated on your next sign-in -
Sign in immediately at
https://dirework.<your-subdomain>.workers.dev/setupwith your streamer account — the setup screen is back, and the first sign-in claims it again. Open/setupdirectly: the home page remembers that the instance was claimed, so until the web worker's instances recycle or you next deploy,/may still show the "already claimed" landing. -
Re-copy your OBS URLs. The timer overlay, task overlay and bot page URLs all changed in step 2, so update each OBS browser source (Dashboard → OBS sources, Dashboard → Bot), then reconnect your bot account.
-
Review what they could have changed: timer and task styles, bot commands, aliases, message templates, and the task list. The reset above deliberately keeps those rows so your own settings survive; to wipe them too, also run
DELETE FROM timer_config; DELETE FROM timer_style; DELETE FROM task_style; DELETE FROM bot_config; DELETE FROM task;(defaults are recreated on sign-in).
Updating your instance
New DireWork releases reach your instance when your fork's main changes:
- Read
CHANGELOG.md(or the GitHub Releases page, which carries the same notes per version) for the releases you're catching up on. Add any new required secrets or variables, and note any reconnect steps, before you sync — the deploy fails early when a required value is missing. - Optionally back up the database first:
bunx wrangler d1 export dirework-db --remote --output=dirework-backup.sql - Sync the fork: Sync fork → Update branch on your fork's GitHub page, or
git pull upstream main && git push origin mainfrom a clone. - The push to
mainruns the Deploy workflow. It applies new D1 migrations, which only move forward; there is no automatic rollback (see Rolling back). - Afterwards, check
https://dirework-api.<your-subdomain>.workers.dev/readyreturns OK and the Dashboard, overlays, and bot page still work.
Rolling back
If a release misbehaves, roll back the workers, not the database.
-
Cloudflare: dashboard → Workers & Pages →
dirework-api(ordirework) → Deployments → pick the last good version → Rollback. From a clone of the repo:bunx wrangler rollback --name dirework-api # api worker bunx wrangler rollback --name dirework # web workerWithout a version id,
wrangler rollbackgoes back one version; pass the id frombunx wrangler deployments list --name <worker>to pick an older one. Roll back both workers to the same release so the web and api stay in step. -
GitHub: open Actions → Deploy, choose the run for the last good commit, and click Re-run all jobs; it rebuilds and redeploys that exact commit (leave
force_state_tokenunset if you start a run by hand instead). The next push tomaindeploys whatevermainholds, so revert the bad commit there too. If you restricted theproductionenvironment tomain, revert onmainrather than deploying another branch.
A worker rollback is only safe when the older code works with the current D1 schema.
DireWork migrations are forward-only and expand/contract: a release only adds tables,
nullable or defaulted columns and indexes, and anything removed (so far one redundant index,
migration 0017) goes a release after no shipped code reads it, so an older worker keeps
working against a newer schema. Check CHANGELOG.md for upgrade notes first.
Never roll the database back to undo a bad release. The only D1 rollback is Time Travel,
bunx wrangler d1 time-travel restore dirework-db --timestamp=<unix-or-RFC3339>, and it
discards everything written since that moment (tasks, settings, the bot connection).
Use it only to recover from data loss, after exporting a backup
(bunx wrangler d1 export dirework-db --remote --output=dirework-backup.sql).
Free plan limits
Workers' free plan allows 100,000 requests/day, shared by every Worker on your Cloudflare account and reset at 00:00 UTC. Rough hourly usage:
| Source | Polling | Requests/hour |
|---|---|---|
| Timer + task overlays (open in OBS) | every 5s each, even in the background | ~1.4k |
| Dashboard tab (visible, in use) | timer 2s + tasks 3s, each counted twice | ~6k |
| Dashboard tab (visible, untouched 2+ min) | timer + tasks every 15s, each counted twice | ~1k |
| Dashboard live preview (switched on) | one overlay every 5s, paused while hidden | ~720 |
| Each open bot page (widget or dock) | lease check-in every 2 min, plus commands | 30 + commands |
Dashboard requests count twice because the web worker proxies /rpc to the api
worker, and both invocations are billed. Dashboard polling slows to every 15 seconds
once nobody has clicked, typed, scrolled, or moved the pointer over it for two minutes,
and pauses entirely while its tab is hidden or minimized, live preview included; the
overlays open in OBS keep polling.
So a six-hour stream with only the overlays running uses about 9k requests, and with the dashboard left open but untouched about 14k. Actively using the dashboard the whole time costs about 45k, and a 12-hour day of constant dashboard use (about 89k) comes close to the daily cap. Once the cap is hit, overlays can no longer fetch updates and chat commands stop until the reset. Close unused OBS sources and dashboard tabs to reduce usage. Workers Paid is optional if your account outgrows the free quotas; it does not remove all platform limits. Check Cloudflare's current pricing before upgrading. The free-tier path remains supported.
D1 rows read
D1's free tier allows 5 million rows read per day, and every task-list poll (task overlay and dashboard) reads rows. DireWork keeps that bounded:
- Done tasks are purged 24 hours after they're completed. The purge runs lazily — when a task is added or marked done, or the timer is started or reset — never on a poll, and it is an index range delete, so it costs only the rows it removes.
- A poll never scans the task table. It reads the open (pending + active) tasks and
at most the 50 most recently completed done tasks through an index, plus an index
count of done tasks so the overlay's
done/totalcounter stays right past 50. With the overlay's Show done option off, done task details are omitted, but counting still reads the retained done rows and uses the D1 quota.
Roughly, a poll reads open tasks + min(done tasks, 50) + done tasks rows. A six-hour
stream polled by the task overlay and a dashboard (~14,400 polls) with 20 open tasks and
100 done stays near 2.5M rows; the 24h purge keeps yesterday's tasks from adding to
tomorrow's. For very busy co-working streams, !clear done between streams (or Clear
done on the Dashboard) resets the count to zero immediately.
The 50-row display limit does not cap counting costs. For example, if 1,000 done tasks remain throughout an eight-hour stream, the task overlay's 5,760 polls alone read roughly 5.76 million rows just for counts, before open tasks or dashboard polls. Check D1 Metrics → Row Metrics after a representative stream; shorten the retained list with Clear done when needed. These are workload estimates, not measured production usage; Cloudflare counts scanned rows toward the quota.
Worker size and startup
Cloudflare limits each Worker
to 64 MiB uncompressed on every plan (the Total Upload size Wrangler prints), and gives
its global scope, the code outside its handlers, 1 second of CPU to start. Cloudflare
refuses an upload past either limit, after the deploy has already applied the D1
migrations. The compressed size is no longer a limit: Cloudflare
dropped its 3 MB Free / 10 MB Paid check
on September 4, 2026.
The Verify workflow checks both Workers right after the build:
- Size (
packages/infra/bundle-budget.ts): fails past 64 MiB uncompressed, and past 1600 KiB gzip. That second number is DireWork's own budget, not a Cloudflare limit: it keeps the bundles, and with them the startup cost, from growing unnoticed. - Startup (
packages/infra/startup-check.ts): profiles each Worker's startup locally withwrangler check startup, adds the time to the run's summary, and fails above 500 ms, half the limit, so a slow CI runner can't fail it by chance.