What is an Nx shared config library, and why not read process.env directly?
An Nx shared config library is a workspace library that owns every environment setting your services read. Each variable is declared once as a Zod schema with its type, coercion rule, default and constraints. At startup, a service parses process.env against that schema exactly once, gets back a typed object, freezes it, and passes it around. Each service imports only the slice it needs, such as database, queue or auth settings, rather than the whole surface.
The alternative is reading process.env wherever a value is needed, and it fails in predictable ways. Every value is typed string | undefined, so each call site has to decide how to handle absence and how to convert. One service treats "0" as false and another treats it as truthy. One parses PORT with Number(), and another uses parseInt and silently accepts "8080abc". Defaults get copied into several files and drift apart. Worst of all, a missing or malformed variable stays hidden until a code path touches it. That might be a rarely hit retry branch, minutes or days after deploy, and the error appears as a confusing failure deep inside a request handler.
This pattern pays off most for backend and platform teams running several Node services in one Nx workspace. The settings live in one place, so a change to one is a single reviewed edit. A bad value crashes the process at boot, and an orchestrator can refuse to roll out a pod that fails at startup. Teams also stop writing the same parsing helpers in every service.
// libs/config/src/index.ts: the only place env variables are declared
import { z } from 'zod';
// Each slice declares its variables once, with type, coercion, default and constraints.
export const dbSchema = z.object({
DATABASE_URL: z.string().url(),
DB_POOL_SIZE: z.coerce.number().int().positive().default(10),
});
export const httpSchema = z.object({
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
// z.coerce.boolean() would turn the string "false" into true, so map values explicitly.
TRUST_PROXY: z.enum(['true', 'false']).default('false').transform((v) => v === 'true'),
});
// Parse once at boot. On failure, list every problem and exit so the deploy fails right away.
export function loadConfig<T extends z.ZodType>(schema: T, env = process.env): Readonly<z.infer<T>> {
const result = schema.safeParse(env);
if (!result.success) {
const problems = result.error.issues
.map((issue) => ` ${issue.path.join('.')}: ${issue.message}`)
.join('\n');
console.error(`Invalid environment configuration:\n${problems}`);
process.exit(1);
}
return Object.freeze(result.data);
}
// apps/orders-api/src/config.ts: this service composes only the slices it uses
// import { z } from 'zod';
// import { dbSchema, httpSchema, loadConfig } from '@acme/config';
//
// export const config = loadConfig(z.object({ ...dbSchema.shape, ...httpSchema.shape }));
// config.PORT is a number, config.TRUST_PROXY is a boolean, and DATABASE_URL is a validated string.
A shared Nx library declares env settings once as Zod slices. Each service parses only the slices it needs into a frozen, typed object at startup and exits on any invalid or missing value.
Who should use an Nx shared config library?
Use it if you meet most of these conditions:
- You run several Node.js services or workers in one Nx workspace. These are processes that read their settings from environment variables at startup: API servers, queue consumers, cron jobs, migration runners.
- Those services share variables. Database connection strings, pool sizes, log levels, auth issuers and queue URLs show up in more than one app. Each extra copy is another place where parsing and defaults can drift.
- You already use TypeScript and are willing to take a Zod dependency. The value comes from
z.inferderiving the config type from the same schema that validates it. - Config mistakes have cost you time. Examples include a deploy that started and then failed on its first request, a flag that behaved differently in two services, or a variable that someone renamed in one app but not in another.
The typical owners are platform or backend teams who maintain the workspace and review changes to shared libraries. Service teams use the library, but they mostly add keys to their own service schema.
It is a weaker fit for a workspace with a single service, for code that runs mainly in browsers or on edge runtimes where environment access works differently, and for values that change at runtime without a redeploy. The last section of this article covers those cases in more detail.
How does it work, end to end?
The mechanism has four steps, and they run in the same order in every service:
- Declare. The shared library defines Zod schemas for each concern, such as core, database and HTTP. Each field states its type, how to coerce the raw string, whether it is required, its default and a
.describe()text. - Compose. Each app builds its own schema by merging the shared fragments it needs and adding keys that only it uses. TypeScript infers the config type from that composed schema.
- Parse once at boot. The app's entry point calls the loader before it opens a port or a connection. The loader runs
safeParseagainstprocess.envand collects every issue in one pass. If any issue exists, the app reports all failing keys by name and exits non-zero. Otherwise the app receives a frozen, typed object. - Use the object, not the environment. The rest of the code receives the config object, either as an import or as an injected dependency, and never reads
process.envitself. Because values are already coerced,config.PORTis a number andconfig.ENABLE_CACHEis a boolean everywhere.
Nx adds two things on top of this. The project graph knows which apps depend on the config library, so nx affected can run their tests and checks when the library changes. Module boundary lint rules can also stop browser projects from importing server-only schemas. The next sections explain each layer in detail.
How does a schema-based config library work in an Nx monorepo?
The library is built in three layers, and each depends only on the one below it.
Core, fragments, service modules
The core holds schemas every process needs: NODE_ENV as an enum, LOG_LEVEL, PORT coerced from a string to an integer, and a reusable validator for the shape of a database URL. It changes rarely and has no knowledge of any service.
Fragments cover cross-cutting concerns such as database (host, pool size, TLS mode) and auth (issuer, audience, signing key). A service that talks to Postgres includes the database fragment. A worker with no HTTP surface leaves out auth. Because fragments are named and versioned together, the meaning of DB_POOL_MAX stays the same across every service that uses it.
Service modules merge the core with the fragments they need and add settings specific to that service. They can live inside the shared library under a per-domain folder, or inside the app itself.
Graph direction
Each app's entry point imports a schema and calls the loader once, before it creates a server or a connection. In the Nx project graph, the edges therefore point from apps to the config library, never back. When the core changes, every app is affected. When a single service module changes, only that app is affected.
No side effects on import
The library exports schemas and a loader function, and nothing runs at module load. If parsing happened at import time, a unit test, a migration script, or an Nx task that only imports a type would crash because the environment is incomplete. Calling the loader explicitly puts validation where the process boots, and nowhere else.
+-------------+ +-------------+ +-------------+
| apps/api | | apps/web | | apps/worker |
| main.ts | | main.ts | | main.ts |
| load() once | | load() once | | load() once |
+------+------+ +------+------+ +------+------+
| import | import | import
v v v
+----------------------------------------------------------------+
| libs/config exports: schemas + loader |
| nothing runs at import time |
| +------------+ +------------+ +------------+ |
| | api | | web | | worker | SERVICE |
| | core+db | | core+auth | | core+db | MODULES |
| | +auth | | +own keys | | +own keys | |
| | +own keys | | | | (no auth) | |
| +-----+------+ +-----+------+ +-----+------+ |
| | | | |
| v v v |
| +----------------------------------------------------+ |
| | fragments: database (host, DB_POOL_MAX, TLS mode) | |
| | auth (issuer, audience, signing key) | |
| +-------------------------+--------------------------+ |
| | |
| v |
| +----------------------------------------------------+ |
| | core: NODE_ENV enum, LOG_LEVEL, PORT -> int | |
| | database URL shape validator | |
| +----------------------------------------------------+ |
+----------------------------------------------------------------+
Every arrow is an import / Nx graph edge; none point upward.
Apps import the config library and call the loader once at boot; inside the library, service modules build on named fragments, which build on a side-effect-free core, so every project-graph edge points from apps down toward the core.
How do you create the config library and write Zod env schemas?
Generate the library with nx g @nx/js:library and place it under a shared path such as libs/shared/config. Avoid putting it under any one service's folder. Every app will depend on it, and a neutral location makes that ownership clear.
File structure
Split the library into a core module and fragment modules. The core holds settings every service needs, such as NODE_ENV, LOG_LEVEL and the loader function. Each fragment covers one concern, such as database, redis or http, and exports its own schema. Services then compose only the fragments they use, so a worker without HTTP never has to define PORT.
Writing the schemas
Each env var type needs a specific schema choice:
| Env var type | Use | Avoid | Why |
|---|---|---|---|
Integer (PORT) |
z.coerce.number().int() or an explicit transform |
Unchecked Number() |
Coercion turns "" into 0, so add .int()/.positive() or reject empty strings |
Boolean (ENABLE_CACHE) |
z.enum(["true","false"]).transform(v => v === "true") |
z.coerce.boolean() |
Boolean("false") is true, because any non-empty string is truthy |
URL (DATABASE_URL) |
z.string().url() |
z.string() |
Catches typos and missing schemes at startup |
Fixed set (LOG_LEVEL) |
z.enum([...]) |
z.string() |
Rejects unknown values and narrows the type |
Defaults and required fields
Use .default() only where a wrong value is harmless, such as LOG_LEVEL. Leave secrets and connection strings required, so that a missing value fails loudly instead of silently pointing at localhost.
Documentation and types
Attach .describe() to each field. The text documents the variable in the schema and can feed generated .env.example files.
Finally, export type Config = z.infer<typeof schema>. The schema becomes the single source of truth, so no hand-written interface can drift from what is actually validated.
// libs/shared/config/src/lib/core.ts
import { z } from 'zod';
// Settings every service needs; harmless values get defaults.
export const coreSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).describe('Runtime environment'),
LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info').describe('Minimum log level'),
});
// libs/shared/config/src/lib/database.ts (fragment)
// Required: a missing URL must fail at startup, not fall back to localhost.
export const databaseSchema = z.object({
DATABASE_URL: z.string().url().describe('Postgres connection string, e.g. postgres://app:changeme@db:5432/app'),
});
// libs/shared/config/src/lib/http.ts (fragment)
export const httpSchema = z.object({
// coerce turns "" into 0, so .int().positive() rejects empty or invalid ports
PORT: z.coerce.number().int().positive().default(3000).describe('HTTP listen port'),
// Never z.coerce.boolean(): Boolean("false") === true
ENABLE_CACHE: z.enum(['true', 'false']).default('false').transform((v) => v === 'true').describe('Enable response cache'),
});
// An API service composes only the fragments it uses.
export const apiSchema = z.object({ ...coreSchema.shape, ...databaseSchema.shape, ...httpSchema.shape });
// The schema is the single source of truth for the type.
export type ApiConfig = z.infer<typeof apiSchema>;
export function loadConfig<T extends z.ZodTypeAny>(schema: T): z.infer<T> {
const result = schema.safeParse(process.env);
if (!result.success) {
console.error('Invalid environment configuration:', result.error.issues);
process.exit(1);
}
return result.data;
}
A core schema and two fragment schemas showing coerced integers, a string-enum boolean transform, URL and enum validation, defaults versus required fields, .describe() documentation, and a z.infer-derived type composed into one service config.
How do you load, validate and compose per-service config?
The loader is the only code that reads the environment directly. Its output is the configuration the application actually receives.
Loading and validating once
loadConfig(schema, source = process.env) calls schema.safeParse(source) exactly once. safeParse returns every issue instead of throwing on the first, so the failure report can list all problems at once. Map each issue to its key path (issue.path.join('.')) and a short reason built from issue.code and expected types. Do not print issue.message or the input verbatim, because some Zod messages echo the received value, and that value may be a credential. The output should look like DATABASE_URL: required; PORT: expected number.
On failure, throw a single ConfigError that contains this aggregated text. Do not call process.exit inside the library. The service entry point catches the error, logs it, and exits non-zero before it opens any ports. If you keep the exit in the entry point, tests can assert on the thrown error and the process stays alive. On success, return Object.freeze(result.data). Object.freeze is shallow, so freeze nested groups as well. Cache the result for the default process.env source so repeated imports skip re-parsing.
Composing per service
Each app builds its own schema from shared fragments. For example, baseSchema.extend(httpSchema.shape) adds HTTP settings, .merge(dbSchema) adds database settings, and queueSchema.pick({ QUEUE_URL: true }) takes a single key. A worker that never serves HTTP leaves out httpSchema completely, so it never needs a PORT value it would not use.
Testing
Unit tests pass a plain object, such as loadConfig(apiSchema, { DATABASE_URL: 'postgres://x' }). They assert the returned values, or assert that the error lists each missing key. Tests never touch the real environment.
import { z } from 'zod';
export class ConfigError extends Error {
constructor(public readonly problems: string[]) {
super(`Invalid configuration:\n ${problems.join('\n ')}`);
this.name = 'ConfigError';
}
}
// Memoize only for the real environment; tests pass fresh objects and must re-parse.
const cache = new WeakMap<z.ZodType, unknown>();
function deepFreeze<T>(value: T): T {
if (value && typeof value === 'object') {
for (const v of Object.values(value)) deepFreeze(v);
Object.freeze(value); // Object.freeze is shallow, so recurse into nested groups first
}
return value;
}
export function loadConfig<S extends z.ZodType>(
schema: S,
source: Record<string, string | undefined> = process.env,
): Readonly<z.infer<S>> {
const useCache = source === process.env;
if (useCache && cache.has(schema)) return cache.get(schema) as z.infer<S>;
const result = schema.safeParse(source); // single pass that collects every issue
if (!result.success) {
// Report key + reason only; never issue.message or raw input, which may contain secrets.
const problems = result.error.issues.map((issue) => {
const key = issue.path.join('.') || '(root)';
const top = issue.path[0];
if (typeof top === 'string' && source[top] === undefined) return `${key}: required`;
if (issue.code === 'invalid_type') return `${key}: expected ${issue.expected}`;
return `${key}: ${issue.code}`;
});
throw new ConfigError(problems); // the entry point logs this and exits non-zero
}
const config = deepFreeze(result.data);
if (useCache) cache.set(schema, config);
return config;
}
A loadConfig implementation that calls safeParse once, throws a single ConfigError listing every missing or invalid key without echoing values, deep-freezes the result, and memoizes it only when reading process.env.
Enforcing boundaries, affected builds and CI checks
Lock the library to server projects
Tag the config library scope:server in its project.json, and tag each project as either type:backend or type:frontend. Then add a depConstraints entry to the @nx/enforce-module-boundaries lint rule so that type:frontend projects can depend only on libraries tagged scope:public. If a React app imports the server schema, lint fails before a bundler can inline a secret name or a default value. Values that are meant to reach the browser, such as a public API base URL or an analytics key, go in a separate config-public library tagged scope:public. It has its own Zod schema, so a value becomes public only when someone adds it there on purpose.
Keep affected builds narrow
Nx tracks changes per project, not per file. Any edit inside config marks every project that depends on it as affected, so nx affected -t test reruns all of those projects. To avoid this, keep only the shared pieces in the library: the loader, shared fragments such as database and logging settings, and the error formatting. Each service's own schema lives inside that app. Adding BILLING_WEBHOOK_SECRET then rebuilds only the billing service.
Make CI check the contract
Add a target, for example config-check, that imports each app's schema and parses its .env.example or the env block from its deployment manifest. Run it through nx affected so a missing key fails the pull request rather than the deploy.
Generate .env.example and a Markdown reference from the same schemas. Read the keys, the defaults and the .describe() text, and fail CI if the generated files differ from the committed ones. Because the docs come from the schema, they always match the code.
How can a shared config library save engineering time?
The time savings come from moving config work earlier and doing it once, rather than from making any single step faster.
- Failures surface at boot, with every bad key listed. A missing
DATABASE_URLproduces one line at startup instead of a stack trace from the first query. BecausesafeParsereports all issues together, an engineer fixes every problem in one round instead of discovering them through a series of redeploys. - Failures surface in the pull request. The
config-checktarget catches a key that is missing from a manifest or.env.examplebefore merge. Nobody has to roll back a deploy or debug it in a live environment. - Parsing logic is written once. Coercion rules such as booleans, ports and URLs, and the error formatting, live in one tested place. New services import them instead of re-implementing them, and they do not repeat the
Boolean("false")bug. - Types remove a class of review comments and bugs.
config.DB_POOL_SIZEis a number at every call site, so code no longer needs?? '10'fallbacks orparseIntcalls, and reviewers do not have to check them. - Onboarding and documentation take less effort. The generated
.env.exampleand reference doc tell a new engineer exactly which variables a service needs and what each one means. Nobody has to maintain a wiki page that drifts. - Renames and changes to shared settings are one edit. Changing a shared key happens in one fragment.
nx affectedthen shows which services to test and redeploy, so nobody has to search the repository for string literals.
Illustrative estimate
The following numbers are illustrative only. Every input is assumed, not measured, so substitute your own figures:
- Assumed: 8 services in the workspace.
- Assumed: each service has 2 config-related incidents or failed deploys per quarter, caused by missing or mis-parsed variables.
- Assumed: each one takes 2 engineer-hours to diagnose, fix and redeploy when it surfaces at request time.
- Assumed: half of those would instead be caught at boot or in CI. Fixing one there takes 0.5 hours.
- Assumed: the one-time setup cost is 3 days, or 24 hours, for the library, schemas and CI target, plus about 4 hours per quarter of upkeep.
Under these assumptions, 16 incidents per quarter cost 32 hours. Catching 8 of them early costs 4 hours instead of 16, which saves 12 hours per quarter. Subtracting 4 hours of upkeep gives a net saving of 8 hours per quarter, so the setup pays back in roughly three quarters. This estimate ignores the parsing code that each new service no longer has to write. If your incident rate or service count is much lower, the payback period grows accordingly. That is why the guidance below recommends deferring the library for one or two services.
When should you avoid a shared config library, and what does it cost?
A shared library centralises configuration, so it also centralises the blast radius. Most of these costs are manageable if you plan for them.
| Risk | Why it bites | Mitigation |
|---|---|---|
| Breaking schema change | Making a field required puts every importer in the affected set and can block their deploys | Add fields as optional; tighten per service later |
| Fail-fast | A missing key for an optional integration crashes the process, and restarts turn that into a crash loop | Mark non-critical integrations optional and disable the feature |
| Parse-once | Feature flags and rotated secrets change after boot | Read them at use time from their own client |
| Code defaults | A localhost default lets production start pointing at nothing |
Default only outside production |
| Secret leakage | Validation errors and logged config objects can echo values | Report key names only and redact before logging |
| Edge, serverless and client bundles | Env access differs, or values are inlined at build time | Keep separate, minimal schemas per runtime |
| Shared Zod dependency | Every project must upgrade together | Treat upgrades as one workspace-wide change |
| One giant config object | Every service depends on every key, which recreates the coupling | Export small, per-concern schemas |
The development cost is real: more files, a library to scaffold, and schemas to write before the first deploy. In return you spend less time debugging misconfigured environments, and defaults stop drifting between services. The payoff grows with the number of services that share keys. It is usually not worth it for a single small service, where a local schema does the same job. It is also a poor fit when most of the code runs on the edge or in the browser, because those runtimes need different loading rules anyway.
What are the alternatives to a Zod-based Nx config library?
Each option below solves part of the problem. The question is which failure you can tolerate: a missing variable discovered at request time, duplicated parsing logic, or an extra dependency every service must track.
| Option | Fits better when | Main cost |
|---|---|---|
Ad hoc process.env reads |
Prototypes, one-off scripts | Missing or malformed values surface late, deep in call stacks |
| Per-app config module, no shared lib | Few services with little overlapping config | Shared settings such as database URLs and log levels drift between apps |
| Hand-written validation function | Tiny config surface, strict dependency policy | You maintain coercion and type inference yourself, and types can disagree with checks |
| Another schema/validation library | Team already standardised on one, or bundle size matters | Same pattern, different trade-offs in inference quality and error output |
| Runtime config service or secret manager | Values rotate or change without redeploy (credentials, feature flags) | Network dependency at startup, caching and fallback logic |
The last row complements a shared library rather than replacing it. Static settings still need a schema. Dynamic values need a fetch-and-refresh path that the schema validates after retrieval.
Decision guide
- Adopt the shared library when three or more services read the same variables, or when a config mistake has already reached production.
- Defer it while you have one or two services. Start with a per-app schema and keep its shape close to what a shared library would export, so you can extract it later without rewriting call sites.
- Pick a different schema library only if you already have one in the dependency graph. Running two schema libraries for the same job adds churn with no safety gain.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nx shared config library, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.