What is NestJS config validation and why does it matter?
NestJS config validation is a typed boundary around process.env. Before any module, provider, or controller reads configuration, a schema checks that every required variable is present, parses it into the correct type, and rejects anything malformed. The rest of the application then works with a known, typed object instead of raw environment strings.
This matters because the environment has no type system. Every value in process.env is a string or undefined. PORT=3000 arrives as "3000". ENABLE_CACHE=false arrives as "false", which is truthy in JavaScript. A misspelled DATABSE_URL produces undefined with no warning. Without validation, these problems don't appear where they start. They appear later, deep inside a database driver, a feature flag check, or a retry loop. The stack trace points at the symptom, not the cause.
The teams that benefit most are backend and platform engineers running several environments and services. Each deploy target has its own set of variables, and different people often own different parts of the configuration. The approach fits any service with more than a handful of settings, more than one deploy target, or configuration shared across teams.
The payoff is time. A missing or malformed variable becomes one clear error at startup, naming the variable and what was wrong with it. Without that check, the same typo can surface as a production incident that someone has to trace back through logs. Because the process refuses to boot, the bad deploy fails before it receives traffic.
How does @nestjs/config load .env files per environment?
ConfigModule.forRoot is where that check gets wired in. Set isGlobal: true so every feature module can inject ConfigService without re-importing the module. Build envFilePath from NODE_ENV, for example .env.development locally and .env.test under the test runner, with a shared .env listed after it as a fallback. In production, set ignoreEnvFile: true so the process reads only process.env.
Two precedence rules decide which value a key ends up with:
- Real environment variables beat
.envvalues. A variable already present inprocess.envis not overwritten by any file. - When
envFilePathlists several files, the first file that defines a key wins. Put the most specific file first and the shared defaults last.
The first rule is the one that causes confusion. A stale DATABASE_URL exported in a developer's shell, or a value injected by the CI runner, silently overrides the file. That makes local, CI and container runs behave differently. Production should not depend on files at all. Have the orchestrator or secret store inject variables, which keeps the source of truth outside the image.
| Setup | Source of values | .env files |
|---|---|---|
| Local | Shell plus .env.development |
Loaded, shell wins |
| CI | Runner-injected variables plus .env.test |
Loaded, runner wins |
| Container/production | Orchestrator or secret store | Ignored (ignoreEnvFile) |
process.env ──┐ (wins)
├──► merged map ──► validate(schema) ──► registerAs namespaces ──► services
.env.<env> ───┤ (first file wins) │ fail fast
.env ─────────┘ ▼
boot aborted
// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { envSchema } from './config/env.schema'; // Zod object schema from the previous section
import databaseConfig from './config/database.config'; // registerAs('database', ...)
import appConfig from './config/app.config'; // registerAs('app', ...)
const nodeEnv = process.env.NODE_ENV ?? 'development';
const isProduction = nodeEnv === 'production';
@Module({
imports: [
ConfigModule.forRoot({
// Inject ConfigService anywhere without re-importing ConfigModule.
isGlobal: true,
// Most specific file first: the first file that defines a key wins,
// so the shared .env only fills gaps. Variables already in process.env
// are never overwritten by either file.
envFilePath: [`.env.${nodeEnv}`, '.env'],
// In production, read only process.env as injected by the orchestrator
// or secret store. A stray .env in the image is never read.
ignoreEnvFile: isProduction,
// Runs once on the merged map. parse() throws on invalid input,
// which aborts bootstrap before any provider is created.
validate: (config: Record<string, unknown>) => envSchema.parse(config),
// Typed namespaces consumed by services via ConfigType<typeof databaseConfig>.
load: [appConfig, databaseConfig],
}),
],
})
export class AppModule {}
ConfigModule.forRoot loads environment-specific .env files in first-file-wins order, skips files in production with ignoreEnvFile, validates the merged values with a Zod schema, and registers typed namespaces.
How do you write a Zod configuration schema for environment variables?
Every value in process.env arrives as a string or undefined, so the schema has to turn text into typed values. Build it one variable at a time and decide for each one whether it may be missing.
Coerce numbers, constrain strings
Ports and timeouts use z.coerce.number().int().positive(). Coercion calls Number() on the raw string, so "3000" becomes 3000 and "abc" fails. An empty assignment such as PORT= coerces to 0. The .positive() check exists to reject that case. NODE_ENV and LOG_LEVEL belong in z.enum([...]), which rejects typos like prod and narrows the inferred type to a literal union.
Connection strings use z.string().url(), which catches a missing scheme or a truncated value at boot. Without it, the same mistake surfaces later as a confusing driver error. Secrets get z.string().min(32) or whatever length your signing algorithm needs. That rejects placeholders like changeme.
Default only when it is safe
PORT and LOG_LEVEL can take .default(). DATABASE_URL and JWT_SECRET should not, because a silent fallback is how a service ends up connected to the wrong database.
Booleans need an explicit transform
z.coerce.boolean() uses JavaScript truthiness, so the non-empty string "false" becomes true. Accept z.enum(["true", "false"]) and add .transform((v) => v === "true") instead.
Required in production, defaulted elsewhere
Make the secret optional on the object. Then add a .superRefine() that reports an issue when NODE_ENV is production and the value is absent. This pattern costs you something. The inferred type stays string | undefined, so consumers need a guard or a post-validation transform. Keep the number of such rules small.
import { z } from "zod";
// Boolean env flags: accept only the literal strings, then map explicitly.
// z.coerce.boolean() would turn the string "false" into true.
const envBoolean = z.enum(["true", "false"]).transform((v) => v === "true");
export const envSchema = z
.object({
NODE_ENV: z.enum(["development", "test", "production"]),
LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
// "3000" -> 3000; "abc" fails; "PORT=" coerces to 0, which positive() rejects.
PORT: z.coerce.number().int().positive().default(3000),
HTTP_TIMEOUT_MS: z.coerce.number().int().positive().default(5000),
// No default: a silent fallback could point the service at the wrong DB.
DATABASE_URL: z.string().url(),
// Long enough to reject placeholders like "changeme".
JWT_SECRET: z.string().min(32),
ENABLE_SWAGGER: envBoolean.default("false"),
// Optional at the object level; required in production by the rule below.
WEBHOOK_SIGNING_KEY: z.string().min(32).optional(),
})
.superRefine((env, ctx) => {
if (env.NODE_ENV === "production" && env.WEBHOOK_SIGNING_KEY === undefined) {
ctx.addIssue({
code: "custom",
path: ["WEBHOOK_SIGNING_KEY"],
message: "WEBHOOK_SIGNING_KEY is required when NODE_ENV=production",
});
}
});
// Cost of the conditional rule: this is still string | undefined here,
// so consumers need a guard even though production guarantees a value.
export type Env = z.infer<typeof envSchema>;
// Example: envSchema.parse({ NODE_ENV: "development",
// DATABASE_URL: "postgres://app:app@localhost:5432/app_dev",
// JWT_SECRET: "dev-only-secret-0123456789abcdef0123" })
A Zod env schema that coerces numeric ports and timeouts, constrains NODE_ENV and LOG_LEVEL with enums, validates URLs and secret lengths, parses booleans with an explicit transform, and uses superRefine to require a key only in production.
How does the validate hook fail fast without leaking secrets?
ConfigModule.forRoot accepts a validate function that receives the merged record of loaded .env values and process.env. Whatever it returns becomes the configuration that ConfigService serves, and whatever it throws aborts application bootstrap. Call schema.safeParse(config) there. On success, return result.data, not the raw input, so the coerced numbers, booleans and defaults from the schema are what the rest of the app reads. Parsing happens once, at boot, and no consumer re-validates later.
Prefer safeParse over parse because you control the error. On failure, result.error.issues already contains every problem, not only the first. Map each issue to its dotted path plus a short reason, join the lines, and throw a single Error. An operator then sees DATABASE_URL: required and PORT: expected number together and fixes both in one deploy cycle.
Build the reason from issue.code or from messages you set in the schema, and do not pass default messages through blindly. Depending on the Zod version, some built-in messages echo the received input, such as the rejected value of an enum. Never log error.format(), the issue objects, or the config argument. Any of these can carry an API key straight into your log pipeline.
Failing fast is deliberate, and it is also a blast-radius risk. A typo in a shared secret store can crash every replica at once. Gate rollouts on readiness or health checks, and deploy in stages, such as canary first, then batches. A config error then stalls the rollout on a few instances while the old version keeps serving traffic.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { z } from 'zod';
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().positive().default(3000),
DATABASE_URL: z.string().url(),
API_KEY: z.string().min(1),
});
export type Env = z.infer<typeof envSchema>;
// Reasons come from issue.code, never issue.message: some built-in
// messages echo the received value, which may be a secret.
const REASONS: Record<string, string> = {
invalid_type: 'missing or wrong type',
too_small: 'too short or too small',
invalid_enum_value: 'not an allowed value', // Zod 3
invalid_value: 'not an allowed value', // Zod 4
invalid_string: 'invalid format', // Zod 3
invalid_format: 'invalid format', // Zod 4
};
export function validate(config: Record<string, unknown>): Env {
const result = envSchema.safeParse(config);
// Return parsed data so coerced numbers and defaults reach ConfigService.
if (result.success) return result.data;
// Report every issue at once: key path + reason, no received values.
const lines = result.error.issues.map((issue) => {
const key = issue.path.map(String).join('.') || '(root)';
return ` ${key}: ${REASONS[issue.code] ?? issue.code}`;
});
// Throwing here aborts bootstrap before any provider reads config.
throw new Error(`Invalid environment configuration:\n${lines.join('\n')}`);
}
@Module({ imports: [ConfigModule.forRoot({ isGlobal: true, validate })] })
export class AppModule {}
A ConfigModule validate hook that runs safeParse once at boot, returns the coerced data, and throws a single error listing every invalid key by path and reason without echoing any received values.
How do you get typed access with z.infer, ConfigService, registerAs and ConfigType?
Once validation passes, the remaining job is to make the rest of the codebase consume configuration through types instead of raw strings. Derive the type with type Env = z.infer<typeof envSchema> rather than writing an interface by hand. Adding, renaming or retyping a variable then requires a single edit, and the compiler reports every consumer that is now wrong.
Inject ConfigService<Env, true>. The second type argument tells the service that values were validated, so get drops undefined from its return type. Passing { infer: true } as the options argument makes get('PORT', { infer: true }) return the schema's type, such as number after coercion, instead of any. Keys remain string literals, though. They are only checked where someone supplied the generic. A bare ConfigService injected elsewhere accepts any string and returns undefined at runtime, so the schema and the call sites can drift apart without a compile error.
Namespaces with registerAs
Namespaces narrow that surface. Use registerAs('database', ...), registerAs('http', ...) and registerAs('auth', ...) to group related settings into objects. Each factory exposes a KEY token. A provider then injects @Inject(databaseConfig.KEY) typed as ConfigType<typeof databaseConfig>, which yields one typed object and requires no key strings.
Factories read process.env directly. To avoid repeating coercion and defaults, have them read from the parsed Zod result instead.
ConfigModule.forFeature(databaseConfig) registers a namespace only for the module that imports it, which keeps auth secrets out of unrelated modules. Async factories use the same token. TypeOrmModule.forRootAsync imports forFeature(databaseConfig), lists databaseConfig.KEY in inject, and receives the typed object in useFactory.
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigType, registerAs } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { z } from 'zod';
export const envSchema = z.object({
DATABASE_HOST: z.string().default('localhost'),
DATABASE_PORT: z.coerce.number().int().default(5432),
DATABASE_USER: z.string().min(1),
DATABASE_PASSWORD: z.string().min(1),
DATABASE_NAME: z.string().default('app_dev'),
});
// Derived, never hand-written: the schema stays the single source of truth.
export type Env = z.infer<typeof envSchema>;
// The namespace reads the parsed result, so coercion and defaults live only in the schema.
export const databaseConfig = registerAs('database', () => {
const env = envSchema.parse(process.env);
return { host: env.DATABASE_HOST, port: env.DATABASE_PORT, user: env.DATABASE_USER,
password: env.DATABASE_PASSWORD, name: env.DATABASE_NAME };
});
@Module({
imports: [
// Fail fast at boot if the environment does not match the schema.
ConfigModule.forRoot({ validate: (raw) => envSchema.parse(raw) }),
TypeOrmModule.forRootAsync({
// Scope the namespace to this module so other namespaces, such as auth, stay out.
imports: [ConfigModule.forFeature(databaseConfig)],
inject: [databaseConfig.KEY],
// One typed object, no key strings that can drift from the schema.
useFactory: (db: ConfigType<typeof databaseConfig>) => ({
type: 'postgres', host: db.host, port: db.port,
username: db.user, password: db.password, database: db.name,
}),
}),
],
})
export class AppModule {}
A Zod schema serves as the single source of truth for the Env type and for a registerAs('database') namespace, and TypeOrmModule.forRootAsync consumes that namespace as a typed object through forFeature, inject and useFactory.
How do you test configuration and keep secrets out of the repo?
Unit tests rarely need the real config pipeline. Build the module with ConfigModule.forRoot({ ignoreEnvFile: true, load: [...] }) and pass inline values, or keep your normal imports and call .overrideProvider(databaseConfig.KEY).useValue({...}) on Test.createTestingModule so that a single namespace is swapped. Inline values keep each test's inputs visible next to its assertions. A .env.test file suits end-to-end suites that boot the whole application, but it creates hidden shared state. When a test breaks, you then have to open a second file to find out why.
Test the schema directly
The schema is a pure function, so you can test it with safeParse and no Nest module. Assert both directions: a minimal valid input succeeds, and each invalid input fails on the expected path. Cover the boolean cases explicitly. "false", "0" and an empty string must produce false or a rejection. They must never produce true, which is what z.coerce.boolean() returns for any non-empty string. Also test that keys required only in production, such as a database URL or signing key, are optional when NODE_ENV=development and fail when NODE_ENV=production.
Commit .env.example, never .env
Commit a .env.example file that lists every key with a placeholder value and a one-line comment. In CI, load that file and run it through the schema in production mode. If someone adds a required key without documenting it, the build fails. Add .env* to .gitignore, with an exception for the example file.
In production, do not ship .env files. Supply real environment variables, or inject secrets from a secret store at deploy time, and set ignoreEnvFile so a file left on the server cannot override them.
When should you avoid Zod, and what are the alternatives?
Zod is not the only way to validate configuration in NestJS. The validationSchema option on ConfigModule.forRoot accepts a Joi schema directly. The NestJS docs also show a custom validate function that uses class-validator and class-transformer. Each option makes different trade-offs.
| Criterion | Zod | Joi (validationSchema) |
class-validator + class-transformer |
|---|---|---|---|
| Type inference | z.infer derives the type from the schema |
None. You maintain a separate interface by hand | The decorated class is both the type and the schema |
| Dependency footprint | One package with no runtime dependencies | One package plus its own small dependencies | Two packages that rely on decorator metadata |
| Coercion behavior | Explicit, opt in per field with z.coerce |
Converts by default, so strings become numbers or booleans silently | Implicit only if you enable implicit conversion in plainToInstance |
| Team familiarity | Common in full-stack TypeScript | Long-standing in Node.js and older NestJS examples | Familiar to anyone who writes NestJS DTOs |
| Migration cost | Rewrite every schema and its consumers | Built in, so there is nothing to migrate | Reuses existing DTO conventions |
When to avoid the approach
If your team has already standardized on Joi or class-validator and its config is validated, switching may not be worth the effort. The main gain is removing a hand-written interface, and that rarely justifies a rewrite.
The startup validate hook runs once. Configuration that changes at runtime or is fetched from a remote source never passes through it, so that path needs its own refresh logic and its own validation.
A short script that reads two variables needs none of this.
For a service, the cost is one dependency and an afternoon of schema work. In return, misconfiguration fails at boot with a clear message instead of surfacing later as a production incident that someone has to debug.
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 nestjs config validation, 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.