apps/web also builds with vinext,
a Vite+ implementation of the Next.js API, into route-free Cloudflare Workers
named tuturuuu-web-vinext-<family>. The gateway reaches them through service
bindings (see Gateway Worker). The Next.js
build is unchanged: next.config.ts and vite.vinext.config.ts both build
their config from next-config.web.ts, and next.config.test.ts checks that
the two agree.
Why families
The whole app is 17.3 MiB gzip as one Worker (cf deploy --dry-run), over the
10 MiB upload limit. apps/web/cloudflare/vinext/families.json splits it:
nodeOnly lists entries that still need Node-only APIs, which no family
owns. It is empty. families.test.ts checks that every route entry has exactly
one family and that only api-ops owns denied paths.
Building a family
Builds run in a disposable checkout, because they delete unowned routes and upgrade React to 19.3.1, which vinext requires. The monorepo keeps its React pin.build-family.sh refuses to run when:
- the checkout has no disposable marker;
- Node is older than 24.22, which cannot strip TypeScript (use the version in
.node-version); - the checkout sits under another directory with a
tsconfig.json, such as.worktrees/in the main checkout. Vite+ resolvestsconfig.jsonupward past the checkout root, so create the checkout elsewhere, for example~/.t3/scratch/vinext-<family>.
NEXT_PUBLIC_APP_URL, NEXT_PUBLIC_WEB_APP_URL,
NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,
NEXT_PUBLIC_TURNSTILE_SITE_KEY, NEXT_PUBLIC_GA_MEASUREMENT_ID,
NEXT_PUBLIC_DISCORD_LINK and NEXT_PUBLIC_SHORTENER_URL. The metadata step
stamps /api/build-info with the commit, so build every family from a commit
on main.
build-family.sh builds the workspace packages, prunes with
cloudflare/vinext/prune.ts, runs vp build --config vite.vinext.config.ts,
runs cf deploy --dry-run --prebuilt, then
scripts/ci/web-vinext-bundle-check.mjs. The check fails when the resolved
react-server-dom-webpack is vulnerable to GHSA-xqc2-xf4c-x3h3 (below
19.2.9, 19.3.0 or any prerelease), when any emitted module carries the real
Redis client, or when the upload exceeds the 9.5 MiB family budget.
build-family.sh also runs the version check right after install. The result,
including the resolved version, is in
apps/web/cloudflare/vinext/<family>.check.json.
Before vp build, build-family.sh runs cloudflare/vinext/service-worker.ts.
The Next.js route src/app/serwist/[path]/route.ts bundles src/app/sw.ts
with esbuild-wasm and reads the revision through node:child_process at
prerender time. Neither runs in a Worker. For the family that keeps that route
(web-rest), the helper calls buildOfflineWorker from @tuturuuu/offline/route
with the same config (src/lib/offline-worker-config.ts): the offline
fallback /~offline, no public-file precache, and the checkout’s commit as
revision. It then replaces the route with createPrebuiltOfflineRoute
(@tuturuuu/offline/route/prebuilt). /serwist/sw.js and /serwist/sw.js.map
are served from the prebuilt bytes with the Next.js headers
(application/javascript, Service-Worker-Allowed: /). A family build has no
.next/static, so its precache manifest holds only the offline fallback.
Hashed assets are cached when first fetched.
build-family.sh also exports PLATFORM_DEPLOYMENT_STAMP as the first 12
characters of the build commit. cloudflare.config.ts binds it as a text var,
so the /serwist/sw.js?v=<stamp> cache-buster in src/app/[locale]/layout.tsx
changes with each build. cloudflare/vinext/service-worker.test.ts checks the
single owner, the order of the build steps, the binding and the parity with the
Next.js route.
Worker builds emit no source maps (build.sourcemap: false): Cloudflare
rejects an upload whose source maps exceed 60 MiB (error 10021), and the
public-auth maps alone reach about 70 MiB.
Deploying a family
A new Worker needs its secrets in the first upload. Fromapps/web of the
built checkout:
PLATFORM_DEPLOYMENT_STAMP
binding (the first 12 characters of the build commit, set by
build-family.sh), so build every family from one main commit. Use the full
40-character commit in the message so the serving version names its source.
A redeploy of an existing Worker omits --secrets-file; its secrets carry
over. The deploy reports No targets deployed: the Worker has no routes,
custom domains, workers.dev or preview URLs. A family the gateway flags takes
production traffic as soon as the deploy finishes, so:
- Before deploying, record the version that serves the Worker now
(
GET /accounts/<account>/workers/scripts/tuturuuu-web-vinext-<family>/deployments, the first deployment’s version at 100%). That is the rollback target. - Deploy, then confirm the new version is at 100% in the same listing. The
listing can show 100% a few seconds before the edge serves the new
version, so the smoke in the next step retries
/api/build-infofor up to 40 seconds before treating an old commit as a failure. - Smoke through
https://tuturuuu.com: every response carriesx-gateway-family: <family>. Check/api/build-info(api-core) for the commit andenvironment: production, a page of the family (for example/vi/loginfor public-auth) and one/_f/<family>/_next/static/*asset it references. - On any failure, roll back at once: create a deployment of the recorded
version at 100% (
POST .../deploymentswith{"strategy":"percentage","versions":[{"version_id":"<previous>","percentage":100}]}).
Gateway routing
The gateway routes each family fromapps/gateway/src/web-routes.generated.json. Regenerate it with
bun run --cwd apps/web routes:gateway after changing routes or
families.json. See Gateway Worker
for matching, flags, cutover and rollback. A family build sets assetPrefix
to /_f/<id> from WEB_VINEXT_FAMILY, so each family’s client assets have
their own URL base. Page families need that build before their id goes into
GATEWAY_WEB_FAMILIES.
All six families are flagged. Web has no HTTP origin: a path no flagged
family claims, including unprefixed /_next/static/* and /_f/<id>/* for an
id no Worker builds, goes to the bound web-rest family, and without that
binding the gateway answers 503.
Rollback ladder: a broken family Worker rolls back to its previous Worker
version (above). A broken routing change rolls back by re-assigning the
previous gateway version. Removing an id from GATEWAY_WEB_FAMILIES sends
that family’s paths to web-rest, which does not own them, so it is not a
rollback.
Runtime bindings
apps/web/cloudflare.config.ts declares the Worker (workersDev and
previewUrls off, no routes):
ABUSE_GUARDservice binding totuturuuu-abuse-guard(AbuseGuardEntrypoint) for proxy, rate-limit and native-integrity state.@upstash/redisis aliased tocloudflare/opennext/redis-unavailable.ts.IMAGES(Cloudflare Images) behindImageTransformerfor profile media, feedback images and external project assets. Animated input is flattened to one frame. A profile upload makes at most six transformations.CHATGPT_FILES, the private R2 buckettuturuuu-web-chatgpt-files, onapi-opsand the whole-app build only. See ChatGPT credential storage.- Secret names only for Supabase, app coordination and the abuse-guard
pepper.
@opennextjs/cloudflareresolves tocloudflare/vinext/cloudflare-context.ts, which readscloudflare:workers.
ChatGPT credential storage
api-ops serves /api/ai/chatgpt, /api/ai/chatgpt/new and
/api/v1/users/chatgpt. These routes back the
ChatGPT plan picker beside the Mira chat
model picker. They list, use and disconnect a user’s ChatGPT subscription
accounts. They hold per-user OAuth credential stores (access and refresh
tokens), not uploaded files. The routes answer 404 or enabled: false
unless TUTURUUU_DEPLOYMENT_MODE=self-hosted and OPENAI_CHATGPT_ENABLED=true.
src/lib/chatgpt/storage.ts picks a ChatGPTStorageAdapter per call:
storage-r2.tswhen the Worker bindsCHATGPT_FILES. Each user has one object atchatgpt/<userId>/store.json, whereuserIdis the session user’s UUID and the object name is a constant, so no client input reaches a key. The object records its owner in custom metadata, and a read rejects a mismatch. A create-onlychatgpt/<userId>/store.lockobject (If-None-Match: *) serializes refresh-token rotation. A lock older than 45 seconds is taken over with an ETag-conditional write. The closing store write is fenced on the ETag of the opening one, so a request that outlived its lock fails instead of overwriting newer tokens.storage-fs.tsotherwise (local development, tests, self-hosted Node): owner-only files underCHATGPT_SUBSCRIPTIONS_DIRor~/.config/tuturuuu/chatgpt.
storage-r2.test.ts (fake bucket
round-trip, owner isolation, traversal, locking) and storage.test.ts
(filesystem).
There is nothing to migrate. The hosted service never enables the
integration. On Vercel, any credential file would have lived on the ephemeral
function filesystem, so it was never durable. Create the bucket before the
first api-ops deploy, with no public access and no r2.dev URL:
TUTURUUU_DEPLOYMENT_MODE or
OPENAI_CHATGPT_ENABLED, so they answer the disabled responses and never read
the bucket. scripts/chatgpt-connect.ts writes only the filesystem store, so
nothing populates the R2 store yet.
Worker runtime behavior
cloudflare.config.tsenables Workers observability (logs at a head sampling rate of 1, with invocation logs), so every family deploy keeps requests and console output queryable in Workers Logs.- The
api-*families, and the unsplit Worker, run withplacement: { region: 'aws:ap-southeast-1' }. At the nearest edge, Vietnamese traffic mostly lands in Hong Kong, and the Gemini API rejects requests from Hong Kong as an unsupported location. Mira and AI chat then fail before the first token, as a generic stream error. Singapore is a supported region and sits beside the Supabase database. The page families stay at the edge. cloudflare/vinext/worker-entry.tsis the Worker entrypoint. It installscloudflare/vinext/workers-fetch.ts, because workerd’s fetch rejects everycachemode exceptno-store(“Unsupported cache mode”). The bundler inlines the entry’s side-effect imports into the entry chunk, which runs after every chunk it imports, socloudflare/vinext/workers-fetch-first.tsmakes vinext’s fetch-cache shim import the install module: ESM dependency order then runs the install before vinext captures the network fetch. vinext keeps its own handling ofcache,next.revalidateandnext.tags, and the network fetch drops the mode workerd rejects. workerd’s fetch andRequestconstructor also throwInvalid redirect valueforredirect: 'error', which server code (the Mastermind store client,@tuturuuu/internal-api, auth attestation and asset fetches) passes so credentialed requests never follow a redirect. The installed global fetch, and any patch later assigned to it such as vinext’s caching fetch, sends those requests withredirect: 'manual'and fails a 3xx response with aTypeError. Without it every such call fails, and the Mastermind fleet routes answer503 {"error":"unavailable"}.bun run --cwd apps/web test:vinext:runtimechecks both in workerd, and that a secret no config declares reachesprocess.envas a whole object and by a dynamic key.- Workers send no User-Agent on subrequests, and the proxy answers 400 to a
sessionless API request without one.
@tuturuuu/internal-apitherefore sendsUser-Agent: tuturuuu-<service>/1.0on server requests that set none, with the service fromTUTURUUU_SERVICE_NAME.
Local check
After a build,vp preview --config vite.vinext.config.ts --configLoader runner
serves the Worker in workerd. Put disposable values in apps/web/.dev.vars
(gitignored). Delete it afterwards.
Known gaps
cacheComponentsis partial in vinext:"use cache"pages render and reuse results in memory, but no CDN or data cache adapter is configured, so pages answerCache-Control: private, no-store.next/imageis served unoptimized.- The 4 external rewrites to infrastructure and calendar forward credential headers, matching Next.js.
Production migration deployment proof
The Production Deployment Planner callsweb-cloudflare-production.yaml
for each admitted production revision. The job uses the Cloudflare Workers
API to read the gateway and every activated vinext family’s serving version.
The gateway flags and service bindings must match the committed vinext
inventory. Each Worker must serve one version at 100%, and the job rechecks
the serving versions before recording success. The version upload message
identifies the build commit. For vinext it must agree with the build stamp
binding. A 12-character stamp also needs an authenticated GitHub commit
resolution. Cloudflare Worker versions and deployments
Web families publish from main. During that arrangement the release gate
accepts the production commit itself, a descendant contained in main, or
an ancestor whose Worker build inputs are unchanged through the production
commit. GitHub’s repository comparison proves the relationship, and
verify-cloudflare-web-production.mjs defines the build paths for each Worker
type. Diverged commits, incomplete comparisons, stale build inputs, mixed
traffic, and unknown routing withhold the marker. The job retries at two-minute
intervals for up to 20 minutes. A public build-info response can support a smoke
test.
The job records cloudflare-production-web with GITHUB_TOKEN, binding the
marker to the exact production SHA and planner attempt. The database workflow
checks the pinned caller, reusable workflow, verifier and recorder blobs,
the successful marker step, and the existing successful staging marker.
Manual recovery requires the same Web proof. A missing marker keeps migration
apply closed. Check the producer’s Worker/version summary, coordinate an
authorized Web publication with the serving owner, then rerun the planner on
the pinned production SHA.
Move vinext publication to the production branch
- With the Web owner, qualify the active family build matrix and gateway
configuration from one pinned
productionSHA on CI. Stamp each upload with its full build SHA. Retain the current serving Worker version IDs and gateway routing preimage. - Stage the version set and verify representative route families and gateway bindings before assigning traffic. Serialize the production publisher with the serving owner, and fence activation against a moved production ref or newer deployment. Keep one-step rollback to the retained version set.
- After staged and production qualification, make the planner’s proof depend on that publication, require exact SHA equality for all serving Workers, and review the resulting producer contract pins. Verify an exact-SHA marker and separate staging proof before authorizing a database apply.