wealth/.claude/skills/front-end-architect/references/lib-env.md

286 lines
14 KiB
Markdown

# Env lib (`packages/libs/src/env`)
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.
Contents: Structure · Types · API · Validation · The app's env · Project env · Bootstrap · Implementation · Usage · Acceptance checklist
## Structure
```
packages/libs/src/env/
├── env.client.ts # createClientEnv, and the error formatter both functions use
├── env.server.ts # createServerEnv; starts with import 'server-only'
├── types.ts # EnvSchema, EnvValues, ClientEnvOptions, ServerEnvOptions
├── index.ts # createClientEnv and the types
└── server.ts # import 'server-only'; createServerEnv
```
- The project's `src/server.ts` re-exports `createServerEnv` by name.
- Import by subpath: `import { createClientEnv } from '@project/libs/env'` and `import { createServerEnv } from '@project/libs/env/server'`.
## Types
```ts
import type { StandardSchemaDictionary } from '@t3-oss/env-core';
export type EnvSchema = StandardSchemaDictionary; // variable name → valibot schema
export type EnvValues<TSchema extends EnvSchema> = Readonly<StandardSchemaDictionary.InferOutput<TSchema>>;
export type ClientEnvOptions<TPrefix extends string, TSchema extends EnvSchema> = {
prefix: TPrefix; // 'NEXT_PUBLIC_'
schema: TSchema & {
[TKey in keyof TSchema]: TKey extends `${TPrefix}${string}` ? TSchema[TKey] : `${TKey & string} must start with ${TPrefix}`;
};
runtimeEnv: NoInfer<Record<keyof TSchema, string | undefined>>; // every declared variable, each read literally
};
export type ServerEnvOptions<TSchema extends EnvSchema> = {
schema: TSchema;
runtimeEnv: Record<string, string | undefined>; // process.env
skipValidation?: boolean; // only for steps that run without the real env (see Validation)
};
```
## API
- `createClientEnv(options)` returns `EnvValues<TSchema>`.
- 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.
- Both:
- Empty strings count as missing (`emptyStringAsUndefined`), so `API_URL=` in a `.env` file fails instead of passing as `''`.
- The values are the schema outputs, so transforms apply: `v.pipe(v.string(), v.transform(Number), v.integer())` turns `'24'` into the number `24`.
- 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.
## The app's env
```
apps/<app>/src/env/
├── env.client.ts # public variables: export const clientEnv = createClientEnv({ ... })
├── env.server.ts # server variables: export const serverEnv = createServerEnv({ ... }); import 'server-only'
├── index.ts # clientEnv
└── server.ts # import 'server-only'; serverEnv
```
- These files are the only code in the repo that reads `process.env`.
- App code (bootstrap, configs) reads `clientEnv` and `serverEnv` directly. Only server code imports `../env/server`.
- 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.
## Project env
Every project except apps that reads env has:
```
<project>/src/env/
├── 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`.
## Bootstrap
- 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'`.
- The server module graph and the client module graph each hold their own copy of every project 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 {
const lines = issues.map((issue) => {
const name = issue.path?.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.');
return `- ${name ?? 'env'}: ${issue.message}`;
});
throw new Error(`Invalid environment variables:\n${lines.join('\n')}`);
}
export function createClientEnv<const TPrefix extends string, TSchema extends EnvSchema>(
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<TSchema extends EnvSchema>(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';
import * as v from 'valibot';
export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_',
schema: {
NEXT_PUBLIC_API_URL: v.pipe(v.string(), v.url()),
NEXT_PUBLIC_CDN_URL: v.pipe(v.string(), v.url()),
NEXT_PUBLIC_CATALOG_API_URL: v.pipe(v.string(), v.url()),
},
runtimeEnv: {
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_CDN_URL: process.env.NEXT_PUBLIC_CDN_URL,
NEXT_PUBLIC_CATALOG_API_URL: process.env.NEXT_PUBLIC_CATALOG_API_URL,
},
});
```
`apps/<app>/src/env/env.server.ts`
```ts
import 'server-only';
import { createServerEnv } from '@project/libs/env/server';
import * as v from 'valibot';
export const serverEnv = createServerEnv({
schema: {
API_INTERNAL_URL: v.pipe(v.string(), v.url()),
CATALOG_API_INTERNAL_URL: v.pipe(v.string(), v.url()),
},
runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',
});
```
`packages/island/src/env/env.ts`. `types.ts` declares `IslandEnv`, and `index.ts` exports both functions and the type.
```ts
import type { IslandEnv } from './types';
let islandEnv: IslandEnv | undefined;
export function setEnv(env: IslandEnv): void {
islandEnv = env;
}
export function getEnv(): Readonly<IslandEnv> {
if (!islandEnv) {
throw new Error('island env is not set. The app bootstrap must call setEnv from @project/island/env first.');
}
return islandEnv;
}
```
`apps/<app>/src/bootstrap/bootstrap.server.ts`
```ts
import 'server-only';
import { setEnv as setIslandEnv } from '@project/island/env';
import { configureServerHttp } from '@project/libs/server';
import { setEnv as setPlatformEnv } from '@project/<platform>/env';
import { cookies } from 'next/headers';
import { clientEnv } from '../env';
import { serverEnv } from '../env/server';
setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL });
setPlatformEnv({ catalogApiUrl: serverEnv.CATALOG_API_INTERNAL_URL });
configureServerHttp({
baseUrl: serverEnv.API_INTERNAL_URL,
getCookieHeader: async () => (await cookies()).toString(),
});
```
`apps/<app>/src/bootstrap/bootstrap.client.ts`. It also turns on refresh and registers the shared interceptors (see [lib-http.md](lib-http.md#usage)).
```ts
import { setEnv as setIslandEnv } from '@project/island/env';
import { http } from '@project/libs/http';
import { setEnv as setPlatformEnv } from '@project/<platform>/env';
import { clientEnv } from '../env';
setIslandEnv({ cdnUrl: clientEnv.NEXT_PUBLIC_CDN_URL });
setPlatformEnv({ catalogApiUrl: clientEnv.NEXT_PUBLIC_CATALOG_API_URL });
http.configure({ baseUrl: clientEnv.NEXT_PUBLIC_API_URL });
```
`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.
```ts
import { http } from '@project/libs/http';
import { getEnv } from '../../env';
export const catalogHttp = http.extend({ baseUrl: () => getEnv().catalogApiUrl });
```
## Acceptance checklist
For building or changing the lib:
```
[ ] createClientEnv and createServerEnv return typed, read-only values; transforms apply
[ ] A public variable without the prefix, or a declared variable missing from runtimeEnv, is a type error
[ ] A missing, empty, or invalid variable throws one Error that lists every invalid variable and why
[ ] Importing @project/libs/env/server outside the React server graph throws (server-only), so a client import fails the build
[ ] process.env is unchanged after createServerEnv runs
[ ] skipValidation returns the raw values without validating
[ ] A project's getEnv throws the clear error before setEnv and returns the values after it
[ ] No process.env outside the app's env/ files
[ ] No hard-coded env value, fallback, or schema default; every env value comes from the app's .env, and only apps have .env files
```