What is NestJS config validation, and why is unvalidated process.env a problem?
NestJS config validation means checking every environment variable your service depends on once, at startup, against an explicit schema. If a variable is missing or malformed, the process refuses to boot. Without this step, configuration problems stay hidden until some code path happens to read the bad value.
The root issue is that Node types every process.env value as string | undefined. A port is a string. A boolean flag is the string "false", which is truthy. A typo like DATABSE_URL produces undefined with no warning. The compiler can't help, because from its point of view all of these are valid strings or valid absences.
ConfigService.get doesn't fix this. If you call it without type arguments, you get a loosely typed value. If you pass a generic, it is only an assertion: TypeScript trusts it, and nothing checks it at runtime. So the same failures move further from their cause. A missing Redis URL shows up as a connection error on the first request that needs a cache. A non-numeric timeout becomes NaN deep inside an HTTP client.
ConfigModule provides a validate option that runs a function over the loaded environment before the application starts. If you pass a Zod schema through it, that one schema does two jobs. It validates and coerces values at runtime, and it serves as the source of your TypeScript types.
Backend and platform engineers who ship services in containers or through CI benefit most. For them, a bad deploy should fail loudly at boot, where orchestrators and pipelines notice immediately. It shouldn't surface minutes later as an intermittent error that someone has to trace back to a misspelled variable.
// env.ts
import { z } from 'zod';
// Without validation, every value is string | undefined and nothing checks it:
// process.env.PORT -> "3000" (a string, not a number)
// process.env.DEBUG -> "false" (a truthy string)
// process.env.DATABSE_URL -> undefined (typo, no warning)
export 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(),
REDIS_URL: z.string().url(),
HTTP_TIMEOUT_MS: z.coerce.number().int().positive(),
// Parse "true"/"false" explicitly. z.coerce.boolean() would turn "false" into true.
DEBUG: z.enum(['true', 'false']).default('false').transform((v) => v === 'true'),
});
// The TypeScript type is derived from the same schema that validates at runtime.
export type Env = z.infer<typeof envSchema>;
// ConfigModule calls this before the app starts. Throwing here aborts boot.
export function validate(config: Record<string, unknown>): Env {
const result = envSchema.safeParse(config);
if (!result.success) {
throw new Error(`Invalid environment configuration:\n${result.error.message}`);
}
return result.data;
}
// app.module.ts
// @Module({ imports: [ConfigModule.forRoot({ isGlobal: true, validate })] })
// In a service, inject ConfigService<Env, true>:
// const port = this.config.get('PORT', { infer: true }); // number, checked at boot
A single Zod schema passed through ConfigModule's validate option rejects missing or malformed variables at startup and supplies the Env type used by ConfigService.
Who should use Zod-based config validation?
This pattern fits teams that run NestJS services where a configuration mistake is expensive to find after deploy:
- Backend engineers maintaining services with more than a handful of variables. These include database URLs, queue endpoints, secrets, timeouts and feature flags. Once the list is long enough that nobody remembers it all, a schema becomes the reference for what the service needs.
- Platform and DevOps engineers who own deployment pipelines, container images and orchestrator configuration. A service that refuses to start on bad config gives them a clear, early signal in deployment status. Without that check, the problem shows up later as an application error that gets routed to the wrong team.
- Teams with several environments (local, CI, staging, production) where variables are set in different places and can drift apart. A schema states one contract that every environment has to meet.
- Teams already using TypeScript strictly who want config values typed as
number,booleanor a union of literals instead ofstring | undefined, without maintaining a separate interface by hand.
It is less useful for small scripts or services that read two or three variables. The trade-offs are covered in the last section.
How does it work?
The mechanism has four steps, all of which happen before your application handles any traffic:
- Load. When
ConfigModule.forRootinitializes, it reads any configured.envfiles and merges them withprocess.env. The result is a flat record of string values. - Validate and coerce. NestJS passes that record to your
validatefunction. The function runsenvSchema.safeParseon it. Zod checks that each required key exists, converts strings to numbers or booleans where the schema says so, applies defaults for omitted optional keys, and collects every failure. - Fail or return. If there are failures,
validatethrows one error listing them, bootstrap aborts, and the process exits. If there are none,validatereturns the parsed object. - Serve typed values.
ConfigServiceserves the returned object. BecauseEnvis inferred from the same schema withz.infer,ConfigService<Env, true>gives callers the coerced types at compile time. The startup check is what makes those types true at runtime.
The rest of this article covers each step in detail: how validate plugs into ConfigModule, how to write the schema without coercion traps, how to report errors without leaking secrets, and how to read the values with types intact.
How does Zod validation plug into ConfigModule?
ConfigModule.forRoot accepts a validate option: a function that receives the raw configuration and returns the configuration the application will actually use. Before calling it, the module loads any .env files you configured and merges them with process.env. By default, a variable already set in the runtime environment wins over the same key in a file. Your function sees one flat record of strings, the same shape your deployment platform injects.
Inside validate, call schema.safeParse(config) rather than parse. safeParse never throws. It returns either the parsed data or a list of issues, and the list is what you want. Map each issue to a line such as DATABASE_URL: Required or PORT: Expected number, join them, and throw a single Error. The throw happens while the module is being constructed, so NestFactory.create rejects and the process exits before it listens on a port. An operator gets every missing or malformed variable in one log entry, instead of fixing them one redeploy at a time.
On success, return result.data, not the original input. That object holds Zod's output: "3000" coerced to 3000, "true" to a boolean, and omitted keys filled with their defaults. ConfigService reads from this returned object, which makes the coercion and defaults visible to your services.
This check runs once, at bootstrap. It confirms shape, not meaning. A well-formed DATABASE_URL pointing at a host that is down or unreachable passes validation. Reachability belongs in readiness and health checks, which run continuously and can report a dependency failing after startup.
+---------------+ +---------------+
| .env files | | process.env |
+-------+-------+ +-------+-------+
| |
+-----------+------------+
| merge: runtime env wins on same key
v
+-----------------------------+
| raw config: flat record of |
| strings |
+-------------+---------------+
v
+-----------------------------+
| validate(config) |
| schema.safeParse(config) |
+------+---------------+------+
| |
success | | issues
v v
+--------------------+ +--------------------------+
| return result.data | | map issues to lines, |
| coerced + defaults | | throw one Error |
+---------+----------+ +------------+-------------+
v v
+--------------------+ +--------------------------+
| ConfigService | | NestFactory.create |
| reads returned obj | | rejects; exits before |
+--------------------+ | listening on a port |
+--------------------------+
Runs once at bootstrap: shape only. Reachability -> health checks
ConfigModule merges .env files with process.env, runs the Zod schema once in validate, and either throws one aggregated error that aborts bootstrap or returns coerced, defaulted data that ConfigService serves.
How do you define a typed environment schema with Zod?
Start with one z.object that lists every variable the application reads. Each value arrives as a string or undefined, so most fields need conversion. Use z.enum(['development', 'test', 'production']) for NODE_ENV-style values. A typo like prod then fails at boot instead of quietly selecting a code path you didn't intend. Finish with z.infer<typeof envSchema> to derive the Env type. The schema stays the single source of truth, and the type can't drift away from the runtime checks.
Coercion traps
z.coerce passes the raw value through JavaScript's constructors, and the semantics are often wrong for config:
z.coerce.boolean()callsBoolean(value). Every non-empty string is truthy, soFEATURE_X=falseparses astrue.z.coerce.number()callsNumber(value). That turnsPORT=into0, which still passes a plain number check.
Parse booleans explicitly instead. z.enum(['true', 'false']).transform((v) => v === 'true') rejects yes, 1, and empty strings. You can widen the accepted set deliberately if your deployment tooling emits other forms.
For numbers, check the string's shape before converting. A regex such as /^\d+$/, followed by .transform(Number) and .pipe(z.number().int().min(1).max(65535)), rejects empty strings, decimals and out-of-range ports.
Defaults
Use .default() only for settings that are safe to omit everywhere, such as log level or request timeout. A default like postgres://localhost:5432/app is dangerous. If a production deploy loses its DATABASE_URL, the service starts and fails later on connection, far from the real cause.
Leave connection strings and secrets required. If you want local convenience, apply defaults conditionally. You can do this in a superRefine that checks NODE_ENV, or by loading a local .env file that production never reads.
import { z } from 'zod';
// Strict boolean: only the literal strings 'true' or 'false' are accepted.
// An unset variable becomes false. 'yes', '1' and '' are rejected.
const boolFlag = z
.enum(['true', 'false'])
.optional()
.transform((v) => v === 'true');
// Strict number: validate the string shape before converting, so 'PORT='
// fails instead of becoming 0. Decimals and out-of-range values also fail.
const port = z
.string()
.regex(/^\d+$/, 'must be a positive integer')
.transform(Number)
.pipe(z.number().int().min(1).max(65535));
export const envSchema = z
.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
PORT: port,
FEATURE_X: boolFlag,
// Safe to default everywhere.
LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
// No unconditional default. See the refine and transform below.
DATABASE_URL: z.string().url().optional(),
})
.superRefine((env, ctx) => {
// Outside local development and test, a missing DATABASE_URL must fail at boot.
if (env.NODE_ENV === 'production' && !env.DATABASE_URL) {
ctx.addIssue({ code: 'custom', path: ['DATABASE_URL'], message: 'required in production' });
}
})
// A localhost fallback only applies when the refine above has allowed it.
.transform((env) => ({
...env,
DATABASE_URL: env.DATABASE_URL ?? 'postgres://localhost:5432/app',
}));
export type Env = z.infer<typeof envSchema>; // Inferred from the schema's output, so DATABASE_URL is typed as string.
A Zod env schema that parses booleans as strict 'true'/'false' strings, checks that number values are digit-only strings before converting them, and falls back to a localhost database only outside production.
Wiring the schema into ConfigModule.forRoot without leaking secrets
ConfigModule's validate option takes a function that receives the merged configuration (process environment plus any loaded .env file) and returns the object that ConfigService will serve. Use safeParse instead of parse so you control the error output. safeParse gives you every failing issue at once, so an operator sees all missing or malformed variables in one failed deploy rather than fixing them one restart at a time.
Format each issue as the variable name (the issue's path) plus the rule that failed, such as the issue code or a short label you derive from it. Do not forward issue.message unchanged. Some built-in Zod messages, such as those for enum mismatches, can include the received input. A message like that, about a misplaced database URL or API key, ends up in container logs, CI output, and whatever log aggregation you ship to. Never include the raw input object in the thrown error either.
When validation fails, throw a single Error that lists every issue. Because forRoot runs during module initialization, the throw stops bootstrap before any provider can read bad config. When validation succeeds, return result.data, not the original input. That makes coercions, transforms, and defaults take effect at runtime.
Choose required and optional fields deliberately. Make a variable required only if the service cannot do its core job without it, such as the database, auth secrets, or the queue. Give non-critical integrations like analytics, feature-flag endpoints, or optional webhooks .optional() or a safe .default(), and have the consuming code turn itself off when the value is absent. That way a missing analytics key logs a warning instead of blocking a release.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { z } from 'zod';
const envSchema = z.object({
// Required: the service cannot do its core job without these.
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32),
// Safe defaults: absence is not an error.
PORT: z.coerce.number().int().positive().default(3000),
NODE_ENV: z.enum(['development', 'test', 'production']).default('production'),
// Optional integrations: consumers turn the feature off when these are undefined.
ANALYTICS_API_KEY: z.string().optional(),
FEATURE_FLAGS_URL: z.string().url().optional(),
});
export type Env = z.infer<typeof envSchema>;
export function validate(config: Record<string, unknown>): Env {
const result = envSchema.safeParse(config);
if (!result.success) {
// Report variable name + failed rule only. Skip issue.message and the input,
// because they can echo secret values into container logs and CI output.
const lines = result.error.issues.map(
(issue) => ` - ${issue.path.map(String).join('.') || '(root)'}: ${issue.code}`,
);
// Throwing here stops bootstrap before any provider reads bad config.
throw new Error(`Invalid environment configuration:\n${lines.join('\n')}`);
}
// Return parsed data, not the raw input, so coercions and defaults take effect.
return result.data;
}
@Module({
imports: [ConfigModule.forRoot({ isGlobal: true, validate })],
})
export class AppModule {}
A validate function for ConfigModule.forRoot that uses safeParse to collect every failing variable and reports only its name and the failed rule, without the received value, then returns the parsed data with required, optional and defaulted fields chosen on purpose.
How do you get type-safe access to validated config?
Once the schema passes, the next problem is reading values without losing their types. ConfigService<Env, true> takes your inferred schema type as the first generic. The second argument tells the compiler that validation has run, so get stops adding undefined to the return type. Calling get('PORT', { infer: true }) then returns the property type from Env, and the compiler rejects misspelled keys.
This is a compile-time convenience only. infer does not re-check the value at runtime. If the schema and the Env type drift apart, or someone passes the wrong generic, the compiler will trust you. The guarantee comes from the validation at startup, not from get.
A thin alternative is a provider that exposes the parsed object directly, for example an injection token bound to a frozen Env. Consumers then depend on a plain typed object instead of a string-keyed lookup.
| Approach | Strength | Weakness |
|---|---|---|
ConfigService<Env, true> |
Built in, works with namespaces | String keys, generic must be repeated |
| Typed config provider | Plain object, easy to mock in tests | One more provider to maintain |
Whichever approach you pick, forbid direct process.env reads outside the config module. They return raw strings, not the values Zod coerced or defaulted, so drift comes back quietly. Enforce this with a no-restricted-properties lint rule or a review checklist item.
For grouping by domain (database, auth, HTTP), use either registerAs namespaces or nested objects in one root schema. Validating per namespace lets each team own its slice. The cost is that a variable nobody claims sits outside every schema and is never checked. A single root schema avoids that gap but centralises ownership.
How do you test config validation and run it safely in production?
Test the schema as a plain function, without bootstrapping Nest. Keep a few fixture objects: one complete, valid environment; copies with a single required key deleted; and copies with malformed values, such as PORT="eighty" or a DATABASE_URL with no scheme. Run safeParse on each. For failure cases, assert on the issue path rather than the message text, so rewording an error doesn't break the suite. These tests run in milliseconds and catch schema mistakes before anything is deployed.
E2E tests should not depend on whatever .env file sits on a developer's machine. In the test setup, pass ignoreEnvFile: true to ConfigModule.forRoot and populate process.env from a fixture before compiling the testing module. Restore the original values afterward. The suite then behaves the same on a laptop and in CI, and validation still runs, so the tests exercise the real path.
In production, fail fast. When validation throws during bootstrap, the process exits with a non-zero code. An orchestrator restarts it, and the restarts become a visible crash loop. The new replicas never pass readiness, so a rolling deployment stalls while the old replicas keep serving traffic. The failure appears in deployment status, not in customer requests.
The alternative is worse. A service that reads config lazily boots cleanly, passes health checks, takes traffic, and then fails on the first request that touches the missing value. That looks like an application bug, and it is often a partial outage.
Make the boot error name the variable and the reason, and never print the value. "REDIS_URL: required" in the crash log turns a search through dashboards into a one-line fix.
How can it save engineering time?
The time savings come from catching config errors earlier and making the diagnosis obvious:
- Shorter diagnosis. A lazily read bad variable shows up as a symptom, such as a connection timeout, a
NaNin a calculation, or a feature that is silently on. Someone then has to trace it back to the environment. A boot-time error names the variable directly, so most of that investigation disappears. - Fewer redeploy cycles.
safeParsereports every failing variable in one error. An operator fixes all of them before the next deploy instead of finding them one restart at a time. - No incident response for config mistakes. A failed boot stalls the rollout while old replicas keep serving. There is no partial outage to triage, no rollback under pressure, and no customer-facing error to explain.
- Less duplicated code.
z.inferderives the type from the schema. Adding a variable is one edit, not one edit in a validator plus one in an interface, and there is no class of bug where the two disagree. - Faster onboarding. The schema documents every variable the service needs, which ones are required and what format each takes. New engineers and platform teams read one file instead of searching the codebase for
process.env. - Cheaper review. With direct
process.envreads banned by lint, reviewers don't need to check each new config access for parsing and fallback logic.
To make the effect concrete, here is an illustrative estimate. Every input is assumed, not measured. Assume a team ships a config mistake (a missing or misspelled variable) twice a quarter. Assume that without boot-time validation, each one takes two engineers about three hours to notice, trace and fix, because it surfaces as an intermittent runtime error. That is roughly 12 engineer-hours per quarter. With validation, assume the same mistake becomes a stalled rollout with an error naming the variable, fixed by one engineer in about 15 minutes. That is roughly half an engineer-hour per quarter. Your own numbers will depend on how often config changes, how many services you run and how good your observability already is. The direction of the effect does not depend on these numbers: errors found at boot, with the variable named, are cheaper to fix than errors found under traffic.
When should you avoid Zod for config, and what are the alternatives?
Zod is not the only way to validate configuration in NestJS, and it is not always the best one. ConfigModule also accepts a Joi schema through validationSchema. It accepts any function through validate, which means a class-validator class run through plainToInstance and validateSync, or a hand-written set of if checks. The real difference between these options is how much work they take to maintain.
| Approach | Runtime dependency | TypeScript type | Fits best when |
|---|---|---|---|
Zod via validate |
Zod | Inferred from the schema | Config is large or changes often |
Joi via validationSchema |
Joi | Separate interface you maintain | The codebase already uses Joi |
class-validator class via validate |
class-validator, class-transformer | The class, often plus an interface for ConfigService |
Request DTOs already use class-validator |
| Manual checks | None | Hand-written | A handful of variables |
Zod's main benefit is that one schema produces both the runtime check and the static type. With Joi or manual checks, you write each variable twice, once in the validator and once in an interface. Nothing forces those two definitions to stay in sync. Every new variable is a chance for the type and the check to disagree, and that cost keeps growing for as long as the service lives.
Zod has costs too. It adds a runtime dependency. In a codebase where request DTOs already use class-validator decorators, it also introduces a second validation style that reviewers have to understand. Some teams will reasonably choose consistency over type inference.
Use Zod when:
- The service has many variables.
- Config changes frequently.
- No validator has been standardized yet.
Skip Zod when:
- The service reads three or four variables. A short manual check is enough.
- The organization has already standardized on Joi or class-validator.
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.