Skip to content

fix(env): serve async env.ts values to Void app requests - #792

Merged
cpojer merged 1 commit into
voidzero-dev:mainfrom
morinokami:fix/void-env-async-reads
Nov 11, 2026
Merged

cpojer merged 1 commit into
voidzero-dev:mainfrom
morinokami:fix/void-env-async-reads

Conversation

@morinokami

Copy link
Copy Markdown
Collaborator

When env.ts declares a key with an async validator, such as a Zod schema with an async refinement, a Void app can't read it:

// env.ts
import { defineEnv } from 'void/env';
import * as z from 'zod';

export default defineEnv({
  API_TOKEN: z.string().refine(async (token) => token.startsWith('sk_')),
});
// routes/api/token.ts
import { defineHandler } from 'void';
import { env } from 'void/env';

export const GET = defineHandler(() => ({ token: env.API_TOKEN }));
Error: env: Async validator for 'API_TOKEN' cannot be resolved synchronously.

The route answers 500 on every request, in vp dev and in a production build. A cron job that reads the key fails the same way, and so does a Valibot schema built with pipeAsync.

The generated entry awaits _validateEnvOnce(env), which resolves async validators ahead of the synchronous env.X reads, and then opens the request scope. _validateEnvOnce cached the resolved values under the env that reads would use at that moment. Outside a scope, that is the env from cloudflare: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

_validateEnvOnce now 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.

  • A completed validation is reused for the same raw values, so a schema is still validated once per isolate. This includes vp dev, which passes a new env object for each request.
  • An env with other values is validated again 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 takes a key's value from the latest validation while that env holds the raw value the value came from. That serves the copy that remote dev mode reads, and the cloudflare:workers env outside a request scope.
  • 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.
  • defineEnv replaces 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:

  • The whole-schema validation used to run once per isolate, whatever the values. It now runs once per set of raw values: a failed validation runs again once the values change, and an env with new values is validated instead of skipped.
  • The cloudflare:workers env 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 _validateEnvOnce and reads env:

  • An async value is read in a request scope opened after validation, and through another env object that holds the same values.
  • A key is served only for the raw value it was validated from, inside and outside a request scope.
  • An env with other values is validated again, and the first env keeps its values afterwards.
  • A failed validation runs again once the value changes.
  • A validation that never settles doesn't block the next call, and a schema registered during the wait is the one validated.

packages/void/test/unit/routing-runtime.test.ts (3 cases) sends requests through createWorkerFetch to 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 main already 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.
  • By hand on a copy of playground/ssr with the env.ts and route above, API_TOKEN=sk_live in .env, and a cron job that logs the value:
    • vp dev and vp preview: the route answers {"token":"sk_live"} on every request, and in vp dev the cron job logs the value. Without this fix, the route answers 500 in both, and the cron job fails.
    • The built Worker in workerd through Miniflare: the route and the scheduled handler read the value, also when the cron event is the isolate's first event. Without API_TOKEN, or with a value the refinement rejects, requests answer 500 with the boot validation error, and the cron event fails.
    • With Valibot's pipeAsync and checkAsync in place of the Zod schema: the route reads the value in vp dev and vp preview, and answers 500 in both without this fix.
    • With database: 'pg' and no database connection, since the route doesn't query it: the route reads the value in vp dev and vp preview.
    • With a WebSocket route whose onRequest reads the key: it reads the value in vp dev and vp preview. Without this fix, it fails in both.
  • Not run: void deploy against 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

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 cpojer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@cpojer
cpojer merged commit 9c48a62 into voidzero-dev:main Nov 11, 2026
18 checks passed
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants