Skip to content

Commit bfcd655

Browse files
committed
Merge branch 'next' into structural-option-cleanup
2 parents ee6e116 + 9f8363c commit bfcd655

9 files changed

Lines changed: 285 additions & 156 deletions

File tree

‎.changeset/top-level-env.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@solidjs/vite-plugin': patch
3+
---
4+
5+
Move typed env out of `start` to a top-level `env` option, since it also works without start mode. An explicit `env` (`true` or a schema path) now works in any setup, for example a manual `ssr: true` server. Left unset, only start mode probes for the conventional `env.ts` / `env.js`, so projects without `start` that happen to have an unrelated `env.ts` are unaffected. `start.env` fails at config time with a message naming the replacement.

‎README.md‎

Lines changed: 97 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ same server functions.
234234
The object form carries the options (`start: true` is pure sugar for
235235
`start: {}` — both mean the identical start mode with defaults, and
236236
`false`/absent means off): `app`, `document`, `entries`,
237-
`middleware`, `setup`, `instrument`, `clientSetup`, `renderMode`, `env`,
237+
`middleware`, `setup`, `instrument`, `clientSetup`, `renderMode`,
238238
`devtools`, `productionErrorBoundary`,
239239
`external`, `node`, all documented below.
240240

@@ -656,90 +656,6 @@ settle, so the option is a documented no-op there. A nonce set during the
656656
client-mode shell prerender is ignored (and the build warns): baking one
657657
into `dist/client/index.html` would replay it on every load.
658658

659-
**`env`** — first-party typed environment variables. A schema file at the
660-
project root — `env.ts` (or `env.js`), probed automatically; point
661-
elsewhere with `start: { env: './path' }`, disable with `env: false` —
662-
default-exports `server` and `client` maps of
663-
[Standard Schema](https://standardschema.dev) validators (zod, valibot,
664-
arktype — even mixed per key; nothing is imported from the plugin):
665-
666-
```ts
667-
// env.ts
668-
import { z } from 'zod';
669-
670-
export default {
671-
server: {
672-
DATABASE_URL: z.url(),
673-
SESSION_SECRET: z.string().min(32),
674-
},
675-
client: {
676-
VITE_APP_NAME: z.string().min(1),
677-
},
678-
};
679-
```
680-
681-
The validated values come back through two fully typed virtual modules:
682-
683-
```ts
684-
// server-only modules (middleware, "use server" modules, the server entry)
685-
import { env } from 'virtual:env/server'; // every var
686-
687-
// anywhere
688-
import { env } from 'virtual:env/client'; // the VITE_-prefixed client vars
689-
```
690-
691-
- **Validation is node-only and layered.** The plugin loads the `.env*`
692-
files through Vite's `loadEnv` (with `process.env` winning, so CI
693-
secrets take precedence), folds them into `process.env` itself — no
694-
`loadEnv` one-liner in vite.config, and server code reading
695-
`process.env` directly sees the file-loaded vars too — and validates
696-
before anything builds. In dev every failure renders the error overlay
697-
with the per-key report, and `.env*`/schema edits revalidate live. In a
698-
build, `client` failures fail the build (those values are baked);
699-
`server` failures only warn — a build machine may legitimately not have
700-
the production secrets — and boot validation enforces them.
701-
- **Client values are baked, server values are runtime.** That's what the
702-
public `VITE_` prefix means: `virtual:env/client` is the validated
703-
output serialized as plain JSON (defaults applied, coercions done) with
704-
zero schema-library bytes. `virtual:env/server` is not baked — it reads
705-
`process.env` when the server boots and validates through your own
706-
schema (imported into the server bundle, where shipping the validator
707-
is fine). Platform-injected vars that don't exist at build time work,
708-
secrets rotate without a rebuild, and no secret value exists in any
709-
dist artifact; an invalid server environment fails boot with the same
710-
per-key report. Boot validation is synchronous: the generated server
711-
env module contains no top-level await, so the server bundle works
712-
under any downstream build target (Nitro's node-server preset,
713-
es2020 — no `esnext` override needed). The flip side: `server`
714-
validators must be synchronous — an async refinement/transform on a
715-
server key is rejected at config time with the fix in the message
716-
(`client` keys may stay async; they are awaited at build time where
717-
the values are baked).
718-
- **Leaks are errors.** Importing `virtual:env/server` from a client
719-
module graph is a hard error naming the importer (the app root and
720-
everything it imports hydrate — they are client code; keep server env
721-
in middleware, `"use server"` modules, or an authored server entry).
722-
Client keys must carry the public prefix (`VITE_`, or your `envPrefix`)
723-
— enforced at config time. And a client-build scan fails the build when
724-
a server var's literal value shows up quoted in a client chunk.
725-
- **Types are generated by inference.** A `solid-env.d.ts` is written next
726-
to the schema file (keep both inside your tsconfig `include`): it
727-
derives each var's type from your own schema through the Standard
728-
Schema output type, so `env.VITE_APP_NAME` is whatever your validator
729-
outputs — with any compliant library and no per-library plumbing.
730-
731-
Env works identically in both `start` modes (a client-mode static build
732-
carries only the client vars); it is a start-mode feature, so without `start`
733-
there is no env layer. See `examples/start-env` for the full story,
734-
including the failure modes.
735-
736-
Design credit: the shape of this feature — the schema-file convention,
737-
the `virtual:env/*` module names (kept identical on purpose), baked
738-
client values, the leak scan — follows
739-
[@vite-env/core](https://github.com/pyyupsk/vite-env) (MIT), the
740-
design-correct prior art, reimplemented on this plugin's machinery with
741-
Standard Schema as the only contract (and runtime-read server values).
742-
743659
**`productionErrorBoundary`** — in a production build, generated entries wrap the app
744660
in a default error boundary (and the document in an outer one): a render
745661
error streams a generic `500 | Internal Server Error` fallback — no stack
@@ -857,6 +773,102 @@ transform-only behavior. See `examples/start-ssr` for a complete SSR app
857773
`examples/start-client` for client mode (whose test flips the same app
858774
between the modes), and `examples/ssr` for the manual `ssr: true` wiring.
859775

776+
#### options.env
777+
778+
- Type: Boolean | String
779+
- Default: undefined (with `start`: probe `env.ts` / `env.js`, off when
780+
absent; without `start`: off)
781+
782+
First-party typed environment variables. A schema file at the project root,
783+
`env.ts` or `env.js`, default-exports `server` and `client` maps of
784+
[Standard Schema](https://standardschema.dev) validators (zod, valibot,
785+
arktype — even mixed per key; nothing is imported from the plugin). `env:
786+
true` requires that file, `env: './path'` points elsewhere, and `env: false`
787+
turns the feature off. With [`start`](#optionsstart) the conventional file is
788+
picked up with zero config; other setups opt in explicitly, so a project
789+
with an unrelated `env.ts` is unaffected:
790+
791+
```ts
792+
// vite.config.ts (without start mode)
793+
solidPlugin({ ssr: true, env: true });
794+
```
795+
796+
```ts
797+
// env.ts
798+
import { z } from 'zod';
799+
800+
export default {
801+
server: {
802+
DATABASE_URL: z.url(),
803+
SESSION_SECRET: z.string().min(32),
804+
},
805+
client: {
806+
VITE_APP_NAME: z.string().min(1),
807+
},
808+
};
809+
```
810+
811+
The validated values come back through two fully typed virtual modules:
812+
813+
```ts
814+
// server-only modules (middleware, "use server" modules, the server entry)
815+
import { env } from 'virtual:env/server'; // every var
816+
817+
// anywhere
818+
import { env } from 'virtual:env/client'; // the VITE_-prefixed client vars
819+
```
820+
821+
- **Validation is node-only and layered.** The plugin loads the `.env*`
822+
files through Vite's `loadEnv` (with `process.env` winning, so CI
823+
secrets take precedence), folds them into `process.env` itself — no
824+
`loadEnv` one-liner in vite.config, and server code reading
825+
`process.env` directly sees the file-loaded vars too — and validates
826+
before anything builds. In dev every failure renders the error overlay
827+
with the per-key report, and `.env*`/schema edits revalidate live. In a
828+
build, `client` failures fail the build (those values are baked);
829+
`server` failures only warn — a build machine may legitimately not have
830+
the production secrets — and boot validation enforces them.
831+
- **Client values are baked, server values are runtime.** That's what the
832+
public `VITE_` prefix means: `virtual:env/client` is the validated
833+
output serialized as plain JSON (defaults applied, coercions done) with
834+
zero schema-library bytes. `virtual:env/server` is not baked — it reads
835+
`process.env` when the server boots and validates through your own
836+
schema (imported into the server bundle, where shipping the validator
837+
is fine). Platform-injected vars that don't exist at build time work,
838+
secrets rotate without a rebuild, and no secret value exists in any
839+
dist artifact; an invalid server environment fails boot with the same
840+
per-key report. Boot validation is synchronous: the generated server
841+
env module contains no top-level await, so the server bundle works
842+
under any downstream build target (Nitro's node-server preset,
843+
es2020 — no `esnext` override needed). The flip side: `server`
844+
validators must be synchronous — an async refinement/transform on a
845+
server key is rejected at config time with the fix in the message
846+
(`client` keys may stay async; they are awaited at build time where
847+
the values are baked).
848+
- **Leaks are errors.** Importing `virtual:env/server` from a client
849+
module graph is a hard error naming the importer (the app root and
850+
everything it imports hydrate — they are client code; keep server env
851+
in middleware, `"use server"` modules, or an authored server entry).
852+
Client keys must carry the public prefix (`VITE_`, or your `envPrefix`)
853+
— enforced at config time. And a client-build scan fails the build when
854+
a server var's literal value shows up quoted in a client chunk.
855+
- **Types are generated by inference.** A `solid-env.d.ts` is written next
856+
to the schema file (keep both inside your tsconfig `include`): it
857+
derives each var's type from your own schema through the Standard
858+
Schema output type, so `env.VITE_APP_NAME` is whatever your validator
859+
outputs — with any compliant library and no per-library plumbing.
860+
861+
Env works identically in both `start` modes (a client-mode static build
862+
carries only the client vars), and in setups without `start` once enabled.
863+
See `examples/start-env` for the full story, including the failure modes.
864+
865+
Design credit: the shape of this feature — the schema-file convention,
866+
the `virtual:env/*` module names (kept identical on purpose), baked
867+
client values, the leak scan — follows
868+
[@vite-env/core](https://github.com/pyyupsk/vite-env) (MIT), the
869+
design-correct prior art, reimplemented on this plugin's machinery with
870+
Standard Schema as the only contract (and runtime-read server values).
871+
860872
#### options.serverFunctions
861873

862874
- Type: Boolean | Object

‎examples/start-env/solid-env.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Generated by @solidjs/vite-plugin (start.env) — do not edit.
1+
// Generated by @solidjs/vite-plugin (env) — do not edit.
22
// Regenerated on every dev server and build start from env.ts.
33
// Keep this file (and the schema) inside your tsconfig "include".
44

‎examples/start-env/test/run.mjs‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Start-mode typed-env fixture test: proves `start.env` gives a start-mode app
1+
// Start-mode typed-env fixture test: proves `env` gives a start-mode app
22
// first-party typed environment variables from a root env.ts of Standard
33
// Schema validators (zod + valibot mixed per key), with the validator never
44
// reaching any bundle:
@@ -539,19 +539,20 @@ async function clientMode() {
539539
// ---------------------------------------------------------------------------
540540
const requested = process.argv[2];
541541
const modes = requested ? [requested] : ['dev', 'guards', 'prod', 'client'];
542-
// Config-level: `start.env: false` removes the env plugin entirely; the
543-
// default (probe) includes it under start mode; without `start` there is no
544-
// env layer at all.
542+
// Config-level: `env: false` removes the env plugin entirely; left unset it
543+
// is included under start mode (which probes for env.ts) and absent without
544+
// `start`; an explicit `env` includes it in any setup.
545545
{
546546
const { default: solid } = await import('@solidjs/vite-plugin');
547547
const names = (opts) => solid(opts).map((p) => p.name);
548548
record(
549549
'config',
550550
'gating',
551-
'env plugin gated on start (+ env: false opt-out)',
552-
names({ start: true }).includes('solid:start-env') &&
553-
!names({ start: { env: false } }).includes('solid:start-env') &&
554-
!names({}).includes('solid:start-env'),
551+
'env plugin probed under start, opt-in without it (+ env: false opt-out)',
552+
names({ start: true }).includes('solid:env') &&
553+
!names({ start: true, env: false }).includes('solid:env') &&
554+
!names({}).includes('solid:env') &&
555+
names({ env: true }).includes('solid:env'),
555556
);
556557
}
557558
try {

‎examples/start-env/vite.config.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { defineConfig } from 'vite';
22
import solidPlugin from '@solidjs/vite-plugin';
33

4-
// Start-mode typed env: `start.env` is left unset here so the suite covers the
5-
// convention — env.ts at the project root is probed and picked up with zero
6-
// config. No loadEnv one-liner either: the plugin folds the .env files into
4+
// Start-mode typed env: the top-level `env` option is left unset here so the
5+
// suite covers the convention — under start mode, env.ts at the project root
6+
// is probed and picked up with zero config. No loadEnv one-liner either: the plugin folds the .env files into
77
// process.env itself.
88
//
99
// Fixture knobs (all driven by test/run.mjs):
@@ -13,7 +13,7 @@ import solidPlugin from '@solidjs/vite-plugin';
1313
// virtual:env/server from the client graph (must fail the build with the
1414
// server-only error), src/LeakApp.tsx hard-codes the secret's literal
1515
// value (must trip the client-chunk leak scan).
16-
// - ENV_SCHEMA points start.env at a fixture schema (explicit-path option):
16+
// - ENV_SCHEMA points `env` at a fixture schema (explicit-path option):
1717
// env.fail.ts requires a variable no .env provides (validation failure),
1818
// env.badprefix.ts declares a client var without the VITE_ prefix
1919
// (config-time prefix error), env.async.ts puts an async validator on a
@@ -30,8 +30,8 @@ export default defineConfig({
3030
start: {
3131
middleware: './src/middleware.ts',
3232
...(process.env.ENV_APP ? { app: process.env.ENV_APP } : {}),
33-
...(process.env.ENV_SCHEMA ? { env: process.env.ENV_SCHEMA } : {}),
3433
},
34+
...(process.env.ENV_SCHEMA ? { env: process.env.ENV_SCHEMA } : {}),
3535
ssr: !process.env.CLIENT_MODE,
3636
}),
3737
],

0 commit comments

Comments
 (0)