13 KiB
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.
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.tsre-exportscreateServerEnvby name. - Import by subpath:
import { createClientEnv } from '@project/libs/env'andimport { createServerEnv } from '@project/libs/env/server'.
Types
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)returnsEnvValues<TSchema>.- Every variable name must start with
prefix. A name that doesn't is a type error:API_SECRET must start with NEXT_PUBLIC_. runtimeEnvlists 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 realprocess.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.
- Every variable name must start with
createServerEnv(options)returnsEnvValues<TSchema>. It is server-only, so a client import fails the build, and it readsruntimeEnv: process.envat runtime.- Both:
-
Empty strings count as missing (
emptyStringAsUndefined), soAPI_URL=in a.envfile fails instead of passing as'', and an optional variable gets its default. -
The values are the schema outputs, so defaults and transforms apply:
v.optional(v.pipe(v.string(), v.transform(Number), v.integer()), '24')gives the number24. -
On failure they throw one
Errorthat 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.tsfromnext.config.ts(with jiti when the config can't resolve it). Never loadenv.server.tsthere:server-onlythrows 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 defaults or 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
clientEnvandserverEnvdirectly. Only server code imports../env/server.
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 beforesetEnv.- 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.
- 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 }).
Bootstrap
- The app's bootstrap calls each project's
setEnvat startup with the values that project needs. Bootstraps are idempotent, sosetEnvmay 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.tsfills the server copy. It may pass server-side values, such as an internal service address.bootstrap.client.tsfills 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 inconfigureServerHttp).
Implementation
env.client.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
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
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
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.
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
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).
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/<app>/src/features/catalog/http.ts reads the platform's env. The server copy holds the internal address and the client copy the public one.
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; defaults and 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