Validates the app's environment variables and gives apps typed, read-only values. `createClientEnv` validates the public variables and is safe on both sides; `createServerEnv` validates the server variables and runs only on the server. Built on @t3-oss/env-core with valibot schemas. Framework-agnostic: the app passes its prefix and its runtime values, so the lib never reads `process.env` itself.
Only apps call it. Every other project gets its values from the app's bootstrap through its own `env/` (`setEnv` and `getEnv`), so no project below the app reads the environment.
No project hard-codes an env value. An env value is a value that changes between environments: a service or CDN address, a key, a third-party ID, a feature flag. Every env value comes from the `.env` of the app that serves it, and only apps have `.env` files.
- Every variable name must start with `prefix`. A name that doesn't is a type error: `API_SECRET must start with NEXT_PUBLIC_`.
-`runtimeEnv` lists every declared variable with a literal reference, `NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL`, because bundlers inline only literal references and the browser has no real `process.env`. Leaving one out is a type error.
- It has no `skipValidation`: public variables are inlined when the app is built, so they must be present at build time anyway.
-`createServerEnv(options)` returns `EnvValues<TSchema>`. It is server-only, so a client import fails the build, and it reads `runtimeEnv: process.env` at runtime.
- On failure they throw one `Error` that lists every invalid variable and why:
```
Invalid environment variables:
- NEXT_PUBLIC_API_URL: Invalid URL: Received "not-a-url"
- NEXT_PUBLIC_CDN_URL: Invalid type: Expected string but received undefined
```
- The result is read-only, and reading an undeclared variable is a type error.
## Validation
- Validation runs when the app's env module first loads. Both bootstraps import it first, so a bad variable stops the app with one clear error before any page renders.
- Next.js: to fail the build instead, load `env/env.client.ts` from `next.config.ts` (with jiti when the config can't resolve it). Never load `env.server.ts` there: `server-only` throws outside the React server graph.
-`skipValidation` (server env only) is for steps that run without the real env: lint, type-check, and a Docker image build without runtime secrets. The app sets it from a flag (`SKIP_ENV_VALIDATION=true`). Skipped validation returns the raw strings without transforms, so a running app never sets it.
- Messages come from the schemas, and valibot's default messages repeat the received value. Give every secret's schema its own message (`v.minLength(32, 'Use at least 32 characters')`), and never log env values.
- Every value comes from the app's `.env` files. Only apps that serve in production have `.env` files; platforms, island, libs, integrations, and tools have none.
- Every variable is required. Never give a schema a default (`v.optional(schema, 'http://localhost:3000')`) or add a fallback in code (`clientEnv.NEXT_PUBLIC_API_URL ?? '...'`). A default or a fallback is a hard-coded value that hides a missing variable.
├── env.ts # setEnv and getEnv, for this project's values only
├── types.ts # the project's env type, e.g. IslandEnv
└── index.ts
```
-`setEnv(env)` stores the project's values. `getEnv()` returns them, and throws a clear error when called before `setEnv`.
- The type uses the project's own names (`cdnUrl`, `catalogApiUrl`), not variable names. The bootstrap maps one to the other, so renaming a variable only touches the app.
- Read `getEnv()` inside functions, never at module top level, because bootstrap may not have run yet: `baseUrl: () => getEnv().catalogApiUrl`.
- The project never imports the app or reads the raw environment, so the dependency graph stays acyclic.
- The project never hard-codes an env value: no literal address, key, ID, or flag, and no fallback for a `getEnv()` value. A new env value goes in the project's env type, and the app fills it from its `.env`.
- Libs have no project env; they never read env. The bootstrap passes their settings through `configure`: `http.configure({ baseUrl })`, `configureServerHttp({ baseUrl, getCookieHeader })`, `cookie.configure({ secure })`. A lib never has a default address, key, or ID; it gets them through `configure`.
- The app's bootstrap calls each project's `setEnv` at startup with the values that project needs. Bootstraps are idempotent, so `setEnv` may run again with the same values.
- Every project exports the same names, so import each under its project's name: `import { setEnv as setIslandEnv } from '@project/island/env'`.
-`bootstrap.server.ts` fills the server copy. It may pass server-side values, such as an internal service address.
-`bootstrap.client.ts` fills the client copy, with public values only.
- Both must provide every field of a project's env type, so a project env never holds a secret. A secret stays in the app's `serverEnv`, and only the app's server code uses it (for example a header in `configureServerHttp`).
## Implementation
`env.client.ts`
```ts
import { createEnv, type StandardSchemaV1 } from '@t3-oss/env-core';
import type { ClientEnvOptions, EnvSchema, EnvValues } from './types';
export function throwInvalidEnv(issues: readonly StandardSchemaV1.Issue[]): never {
throw new Error(`Invalid environment variables:\n${lines.join('\n')}`);
}
export function createClientEnv<constTPrefixextendsstring,TSchemaextendsEnvSchema>(
options: ClientEnvOptions<TPrefix,TSchema>,
): EnvValues<TSchema> {
return createEnv<string,{},EnvSchema>({
clientPrefix: options.prefix,
client: options.schema,
// env-core deletes empty strings from the object it gets, so it gets a copy
runtimeEnvStrict: { ...options.runtimeEnv },
emptyStringAsUndefined: true,
onValidationError: throwInvalidEnv,
}) as EnvValues<TSchema>;
}
```
`env.server.ts`
```ts
import 'server-only';
import { createEnv } from '@t3-oss/env-core';
import { throwInvalidEnv } from './env.client';
import type { EnvSchema, EnvValues, ServerEnvOptions } from './types';
export function createServerEnv<TSchemaextendsEnvSchema>(options: ServerEnvOptions<TSchema>): EnvValues<TSchema> {
return createEnv<undefined,EnvSchema>({
server: options.schema,
// env-core deletes empty strings from the object it gets, so process.env gets a copy
runtimeEnv: { ...options.runtimeEnv },
isServer: true,
emptyStringAsUndefined: true,
skipValidation: options.skipValidation ?? false,
onValidationError: throwInvalidEnv,
}) as EnvValues<TSchema>;
}
```
The explicit type arguments on `createEnv` are needed, because env-core's option types can't be checked against a generic schema. Call sites stay fully typed through `ClientEnvOptions` and `ServerEnvOptions`.
## Usage
`apps/<app>/src/env/env.client.ts`
```ts
import { createClientEnv } from '@project/libs/env';
`platforms/<platform>/src/features/catalog/http.ts` reads the platform's env. The server copy holds the internal address and the client copy the public one.