Repository navigation
fix(env): serve async env.ts values to Void app requests - #792
Merged
Merged
Conversation
A Void app could not read an env.ts key whose validator is async: every request that read it failed with "Async validator ... cannot be resolved synchronously", in dev and in production builds. The generated entry validates the env before it opens the request scope. _validateEnvOnce cached the resolved values under the env that reads use outside a scope, while reads in the scope look them up under the env the handler received. _validateEnvOnce now seeds the cache of the env it receives. A completed validation is reused for the same raw values, so a schema is still validated once per isolate, also when a dev server passes a new env object for each request. An env with other values is validated again rather than given values validated for another, and keeps its own values: Cloudflare may keep an isolate running when only its bindings change, so requests that hold the old and the new values can overlap. A read through an env that was never validated itself, such as the remote dev copy or the cloudflare:workers env outside a request scope, takes the value from the latest validation while that env holds the raw value the value came from. Only a completed validation is reused. In workerd, a promise that waits on the I/O of a canceled request never settles, so each call runs its own validation until one completes. A call that finds another schema registered after it waited validates again with that schema. The per-env caches no longer stay referenced after their env is gone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
cpojer
pushed a commit
that referenced
this pull request
Nov 16, 2026
…kers (#820) In a TanStack Start, React Router or vinext app, `env` from `void/env` ignores `env.ts`: ```ts // env.ts import { boolean, defineEnv, number, string } from 'void/env'; export default defineEnv({ STRIPE_KEY: string(), PORT: number().default(3000), DEBUG: boolean(), }); ``` ```ts // A React Router loader import { env } from 'void/env'; export const loader = () => Response.json({ stripeKey: env.STRIPE_KEY, port: env.PORT, debug: env.DEBUG }); ``` With `DEBUG=false` and neither `STRIPE_KEY` nor `PORT` set, the route reads `PORT` as `undefined` and `DEBUG` as the string `"false"`, and the missing `STRIPE_KEY` reads as `undefined` rather than failing. This happens in `vp dev` and in a production build. An async validator never runs. Only the Worker entry of a Void app imports `env.ts`. A framework's Worker never loads it, so no schema is registered there, and `env` returns raw values, whatever the Vite plugin loaded in its own process. ## Fix The entry that Void generates around the framework's Worker entry (`.void/<framework>-trigger-wrapper.ts`) now imports `env.ts` ahead of the framework entry, and awaits a new internal `_prepareEnv(env)` on every request, in `vp dev` and in builds. - `_prepareEnv` validates every key, async validators included, and keeps each key's result. It never rejects: a read of a key that failed throws that key's error, also for an async validator, so a request that doesn't read the key still runs, and so does a build-time prerender without production secrets. - Like `_validateEnvOnce` since #792, it reuses a validation for the same raw values and keeps the results with the env object it receives. A request whose env holds the same raw values compares them and validates nothing. - A D1 app's framework reads outside a request scope, through the `cloudflare:workers` env, which is another object. Such a read gets the latest validation's result while that env holds the raw value the result came from. The results are never copied to that object, which can come to hold other values. - In `vp dev`, the wrapper also prepares the env before it dispatches a cron or queue job. - `void deploy` bundles a framework app's cron and queue jobs apart from the app, with a copy of `void/env` of their own. With this change, they would see the schema that the app registers and fail to read an async key. The jobs of an app with `env.ts` now prepare the env through the `_prepareEnv` that the registering copy publishes on the env registry, so the public `VITE_*` values embedded in the app are the ones validated. Results by env object move from the module to the registry, where every copy reads them. Unlike the entry of a Void app, an invalid value doesn't fail every request. That would also stop a build-time prerender, which runs without production secrets, and every request of an existing app with one invalid value. Checking the whole schema in production is left for a follow-up. Only TanStack Start, React Router and vinext are covered here, since Void generates their Worker entry. SvelteKit, Nuxt, Analog and Astro build their Workers differently and are left for follow-ups. Other behavior changes: - A read of a missing required key throws an `EnvValidationError` instead of returning `undefined`. - An `env.ts` that throws when it loads stops the Worker from starting, since the Worker now loads it. - `_validateEnvOnce`, which Void apps use, now keeps a result for each key too. A read that doesn't go through its whole-schema check, such as one in a Durable Object handler, gets the key's own result from the latest validation, even when another key failed. It used to validate the key again, which fails for an async validator. - A validation in which a validator threw runs again on the next call, as with `_validateEnvOnce` since #792. Until then, a read of that key throws what the validator threw. - Validators of different keys run concurrently in `_validateEnvOnce` and `_prepareEnv`. `validateAllEnv`, which the dev server's warning and the deploy check use, still runs them in order. - The registry keeps the latest validation in a new field, `latestValidation`. 1.8.0 through 1.9.1 store another shape under `validation`, and two Void versions in one process share the registry. ## Docs - `docs/integrations/frameworks/overview.md` lists environment variables among the features of TanStack Start, React Router and vinext apps. - `packages/void/AGENTS.md` records why the wrapper loads `env.ts`, and how reads find the results. ## Tests - `packages/void/test/unit/env-schema.test.ts` (10 cases): - `_prepareEnv` serves defaults, converted values and async results, resolves with invalid keys and fails only their reads (what a validator throws included), redacts the raw value from an async validator's failure, validates once for the same raw values and again for others, runs a validator that threw again, and resolves without an env. - Outside a request scope, it serves the results, failures included, while the env there holds the same values, and stops once it holds another. - With two copies of `void/env`, one reads what the other prepared, the registering copy's `_prepareEnv` is published, and registering a schema again drops the results in every copy. - `packages/void/test/unit/plugin-class-a-wrapper.test.ts` (4 cases): - The generated wrapper imports `env.ts` ahead of the framework entry and calls `_prepareEnv`. - The PostgreSQL dev and build wrappers run in Node, with a new env object for each request. A request that reads no key answers 200, a default is read as a number, a read of a missing key answers 500 with that key's error (also for an async validator), and values that the env holds read as the schema returns them. The runner gives Node a file URL for the Windows paths that the wrappers import. - A D1 app's build wrapper, bundled and run in workerd, answers the same. - `packages/void/test/unit/wrapper.test.ts` (2 cases): in workerd, the cron job and queue consumer that `void deploy` bundles for a D1 and a PostgreSQL app read a default and an async value that the app prepared. The jobs of an app without `env.ts` stay as they were. - The React Router, TanStack Start, vinext app and vinext pages playgrounds get an `env.ts` with a default that nothing else supplies, and a route that returns it. Their dev integration suites read it, and `test/check-playground-build-artifacts.mjs` checks that each server bundle contains `env.ts`. All 16 unit cases and the 4 dev cases fail without this fix. ## Verification - `vp test run`: 805 files pass, 1 skipped (17,032 tests pass, 33 skipped). The dev servers of `astro.test.ts` and `websockets-playground.test.ts` timed out starting under the suite's load, and both files pass when run alone. - `vp run check`: 34/34 pass. - `vp preview` of the four playgrounds' production builds: `/api/env` answers `{"SCHEMA_DEFAULT":48213}`. - By hand before the rebase, on copies of the React Router and TanStack Start playgrounds, with an async validator for a `TOKEN` key that falls back to a value, and a prerendered page that reads it and `SCHEMA_DEFAULT`: the build prerenders the page with both values. React Router's `vp build` doesn't exit after prerendering, with or without `env.ts`. - By hand on the TanStack Start copy with `"sideEffects": false`: the server bundle keeps `env.ts`, and the prerendered page has both values. - Not run: `void deploy` against Cloudflare, a dev server with a PostgreSQL database (the unit tests run the PostgreSQL dev wrapper in Node), and Windows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
When
env.tsdeclares a key with an async validator, such as a Zod schema with an async refinement, a Void app can't read it:The route answers 500 on every request, in
vp devand in a production build. A cron job that reads the key fails the same way, and so does a Valibot schema built withpipeAsync.The generated entry awaits
_validateEnvOnce(env), which resolves async validators ahead of the synchronousenv.Xreads, and then opens the request scope._validateEnvOncecached the resolved values under the env that reads would use at that moment. Outside a scope, that is the env fromcloudflare:workers. Reads in the scope look values up under the env the handler received, which is another object in workerd. The cron, queue and email handlers validate in the same order.Fix
_validateEnvOncenow seeds the cache of the env object it receives. The request scope opens with that object, or in remote dev mode with a copy of it.vp dev, which passes a new env object for each request.cloudflare:workersenv outside a request scope.defineEnvreplaces the per-env caches. It used to clear them through a list that kept every cache alive, one per env object.Two behaviors change besides the fix:
cloudflare:workersenv used to receive the values of the first validation, whatever it held. It is now served a value only for the raw value it holds.A handler that runs in a Durable Object (a WebSocket route, a Durable State definition) doesn't validate the env. It can now read an async key in an isolate where a request or a cron, queue or email event has validated, but not in one that runs only the Durable Object. Validating from those handlers is left for a follow-up.
Tests
packages/void/test/unit/env-schema.test.ts(12 cases) calls_validateEnvOnceand readsenv:packages/void/test/unit/routing-runtime.test.ts(3 cases) sends requests throughcreateWorkerFetchto a Hono route that reads an async key: with a new env object for each request, with the remote dev copy, and with two overlapping requests that hold different values.12 of the 15 cases fail without this fix. The other three check behavior that
mainalready has: a read outside a request scope with the same values, a validator that throws running again, and an unfinished validation not blocking the next call.Verification
vp test run: 792 files pass, 1 skipped (16,644 tests pass, 30 skipped).vp run check: 33/33 pass.playground/ssrwith theenv.tsand route above,API_TOKEN=sk_livein.env, and a cron job that logs the value:vp devandvp preview: the route answers{"token":"sk_live"}on every request, and invp devthe cron job logs the value. Without this fix, the route answers 500 in both, and the cron job fails.scheduledhandler read the value, also when the cron event is the isolate's first event. WithoutAPI_TOKEN, or with a value the refinement rejects, requests answer 500 with the boot validation error, and the cron event fails.pipeAsyncandcheckAsyncin place of the Zod schema: the route reads the value invp devandvp preview, and answers 500 in both without this fix.database: 'pg'and no database connection, since the route doesn't query it: the route reads the value invp devandvp preview.onRequestreads the key: it reads the value invp devandvp preview. Without this fix, it fails in both.void deployagainst Cloudflare, remote dev mode, and a binding change that reuses an isolate. The last two are covered by the unit tests above.🤖 Generated with Claude Code