How does NestJS config validation work?

NestJS config validation is a step inside ConfigModule.forRoot() that runs once, at startup, before any other module consumes configuration. The flow has four stages, each covered in detail in the sections below:

  1. Load. ConfigModule reads the .env files listed in envFilePath and merges them with process.env. Real environment variables win.
  2. Validate. The merged map goes to either a Joi schema passed as validationSchema or a custom validate function. The Joi schema or the function checks that required keys exist, that values match the expected format, and converts strings to numbers or booleans where you ask for it.
  3. Fail or continue. If validation fails, the error is thrown during NestFactory.create(), so the process exits before app.listen() runs. If validation passes, the validated values become the configuration that ConfigService serves.
  4. Consume. registerAs factories group values into typed namespaces such as database or http. Services and forRootAsync factories receive those namespaces through dependency injection instead of reading process.env themselves.

The design depends on one rule: configuration enters the application only through this pipeline. Any code that reads process.env on its own bypasses steps 2 and 3.

How does ConfigModule load and resolve environment variables?

ConfigModule.forRoot() builds a single key/value map that ConfigService reads from. By default it parses a .env file in the project root. envFilePath accepts a path or an array of paths. When a key appears in several files, the first file that defines it wins. The parsed values are then merged with process.env. Real environment variables take precedence over .env values. This lets a container or CI runner override a checked-in development default without editing files.

isGlobal: true registers the module globally, so feature modules can inject ConfigService without importing ConfigModule again. cache: true memoizes lookups in ConfigService.get(). Values are not expected to change after boot, so repeated reads should not hit process.env again.

 .env files ──┐
 (envFilePath)│   merge (process.env wins)
 process.env ─┴──────────────► raw map
                                  │
                         validate / schema
                          │              │
                        fails          passes
                          │              │
                 throw during      typed, coerced config
                 NestFactory.create       │
                 (listen() never   ConfigService + registerAs
                  runs)            namespaces (database, cache, http)
                                          │
                                   app.listen()

Validation runs while the module graph is built. A failure throws during app creation, so the process exits before it binds a port or opens any connection.

This sets the ground rule for the rest of the article: nothing outside the config layer reads process.env directly. The ordering is the reason. A process.env read inside a decorator argument, a module-level constant, or a top-level import side effect runs when the file is loaded. That happens before forRoot executes. Those reads get the raw string, or undefined, and skip validation and coercion entirely.

// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, registerAs } from '@nestjs/config';

// Namespaced config: the factory reads process.env only inside the config layer.
export const databaseConfig = registerAs('database', () => ({
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT ?? '5432', 10),
}));

// Throwing here aborts NestFactory.create(), so app.listen() never runs.
function validate(raw: Record<string, unknown>) {
  if (!raw.DB_HOST) throw new Error('DB_HOST is required');
  if (Number.isNaN(Number(raw.DB_PORT ?? 5432))) throw new Error('DB_PORT must be a number');
  return raw;
}

// Anti-pattern: module-level code is evaluated at import time, before validate() runs.
// const PORT = process.env.PORT; // unvalidated, may be undefined

@Module({
  imports: [
    ConfigModule.forRoot({
      // First file that defines a key wins; real env vars override both files.
      envFilePath: ['.env.local', '.env'],
      isGlobal: true, // inject ConfigService anywhere without re-importing
      cache: true,    // memoize ConfigService.get() lookups after boot
      load: [databaseConfig],
      validate,
    }),
  ],
})
export class AppModule {}

// Shell: the exported value overrides DB_HOST=localhost from .env
// DB_HOST=db.internal.example node dist/main.js

A global, cached ConfigModule that loads two .env files, validates the merged map so a bad config stops boot before listen(), and exposes a registerAs('database') namespace, with a comment marking a module-level process.env read as the anti-pattern.

Why should NestJS config validation fail fast at boot?

Validation exists to close that gap. Every variable the application depends on should be checked once, when the process starts, so that a bad value stops the process before it accepts its first connection. Without that check, a misconfigured service boots, passes a shallow health check, and fails on the first request that touches the missing setting. In the worst case that is a payment webhook at 3 a.m., long after the deploy looked green.

The problem is worse than missing values. Environment variables are always strings. PORT=3000 arrives as "3000", and CACHE_ENABLED=false arrives as "false", which is truthy in JavaScript. A plain if (config.get('CACHE_ENABLED')) therefore enables the cache. A schema that coerces and type-checks at boot turns these silent logic bugs into explicit errors.

This matters most for backend and platform engineers running the same image across local, CI, staging and several production regions. Each environment has its own source of variables, and drift between them is normal. A startup failure that names the exact key and the expected type, such as "DATABASE_URL must be a URL", is a deploy-time failure. A developer can fix it in minutes. The same mistake found at runtime becomes an incident.

Fail-fast has a cost. If you mark an optional feature flag as required, one unset value puts every pod into a crash loop. Decide deliberately which variables are truly required. Give everything else an explicit default in the schema rather than a scattered ?? fallback in application code.

Who should use typed env validation in NestJS?

Typed env validation pays off in these situations:

  • Services deployed to more than one environment. If the same build runs locally, in CI, in staging and in production, each environment supplies variables from a different source. Validation is the single check that all of them agree with what the code expects.
  • Teams with several contributors to one service. When a new variable is added, the schema documents it for everyone. A teammate who pulls the change and lacks the variable gets a named error at startup. Nobody has to debug an undefined deep inside a service.
  • Platform and DevOps engineers who own deploy pipelines. A container that exits immediately with a clear message is easier to diagnose from orchestrator logs than one that starts and then fails health checks or individual requests.
  • Codebases that already use TypeScript strictly. If you rely on the compiler elsewhere, untyped config.get('SOME_KEY') calls are a gap. Typed namespaces close that gap.

It is less valuable for throwaway prototypes, single-file scripts, or libraries that should receive configuration from their host application instead of reading the environment themselves. The section on when to avoid env validation covers those cases.

What are the options for an env schema: Joi, class-validator or Zod?

Nest gives you two hooks for this: the validationSchema option, which takes a Joi schema, and the validate option, which takes any function that receives the raw env object and returns the validated config or throws. All three approaches below use one of those two hooks.

Approach Typing Coercion Extra dependencies Error messages
Joi via validationSchema None. You maintain a separate interface Converts strings to numbers and booleans by default joi Readable, one line per failing key
class-validator in validate The class is the type Opt-in via enableImplicitConversion or @Type() class-validator, class-transformer Verbose nested constraint objects that need formatting
Zod in validate Inferred with z.infer Explicit z.coerce.* per field zod Structured issues with paths that are easy to flatten

Joi's weakness is drift. The schema validates PORT, but nothing ties it to the interface you pass to ConfigService<T>. Rename a key in one place and the compiler stays silent.

Coercion has a trap in every option. Coercing the string "false" to a boolean with plain Boolean() gives true. This applies to z.coerce.boolean() and to class-transformer's implicit conversion. Handle boolean flags with an explicit string enum or a custom transform.

Choosing between them:

  • New project: pick Zod, or class-validator if the codebase already uses it for DTOs. Either way, you write the schema once and get the type for free. The extra setup is roughly a dozen lines of validate boilerplate. You pay that once, and it removes an entire category of type/schema mismatch bugs for the life of the service.
  • Existing project on Joi: keep it unless drift has actually caused incidents. When you do migrate, move one namespace at a time.

How do you implement a typed validate function with class-validator or Zod?

Start with the Joi baseline. Pass validationSchema: Joi.object({...}) to ConfigModule.forRoot, with rules such as Joi.number().port().default(3000) and Joi.string().uri().required(). It works, but the schema and your TypeScript types are two separate artifacts that can drift apart.

class-validator: one class, rules and type together

Define an EnvironmentVariables class and decorate each property. Then pass a validate function to forRoot that does three things:

  1. Calls plainToInstance(EnvironmentVariables, config).
  2. Runs validateSync(instance, { skipMissingProperties: false }).
  3. Returns the instance, so downstream code receives converted values.

Make coercion explicit. Use @Type(() => Number) on numeric fields instead of enableImplicitConversion, which converts every field using its reflected type and makes conversions easy to miss in review.

Booleans need extra care. Boolean('false') is true, so write a @Transform that maps only 'true' and 'false' to booleans. Any other value, including 'yes', 'TRUE' and '1', passes through unchanged and fails @IsBoolean(). Accepting a single format means a typo fails at boot instead of silently enabling a feature.

Zod: infer the type from the schema

Build a z.object schema and derive the type with type Env = z.infer<typeof envSchema>. Use z.coerce.number() for ports and timeouts. Avoid z.coerce.boolean(), because it has the same 'false' problem described above. Use z.enum(['true', 'false']).transform(v => v === 'true') instead. Call safeParse and return result.data.

Error output

Don't throw raw errors. A class-validator ValidationError carries the offending value, and some Zod issue messages can include the received input. A failing DATABASE_URL could therefore print credentials into boot logs.

Build the message yourself from the variable name and the rule that failed:

  • For class-validator, use property plus Object.keys(constraints).
  • For Zod, use issue.path plus issue.code.

Join the results into a single thrown Error.

import { plainToInstance, Transform, Type } from 'class-transformer';
import { IsBoolean, IsInt, IsNotEmpty, IsString, Max, Min, validateSync } from 'class-validator';

// One class supplies both the validation rules and the TypeScript type.
class EnvironmentVariables {
  // Explicit numeric coercion instead of enableImplicitConversion.
  @Type(() => Number)
  @IsInt()
  @Min(1)
  @Max(65535)
  PORT: number = 3000; // default applies when PORT is unset

  @IsString()
  @IsNotEmpty()
  DATABASE_URL!: string; // e.g. postgres://app:changeme@localhost:5432/app

  // Strict: only 'true' / 'false'. 'yes', 'TRUE', '1' pass through unchanged and fail @IsBoolean.
  @Transform(({ value }) => (value === 'true' ? true : value === 'false' ? false : value))
  @IsBoolean()
  FEATURE_EXPORT_ENABLED!: boolean;
}

export function validate(config: Record<string, unknown>): EnvironmentVariables {
  const env = plainToInstance(EnvironmentVariables, config);
  const errors = validateSync(env, { skipMissingProperties: false });

  if (errors.length > 0) {
    // Report variable names and failed rule names only.
    // Never include error.value: it may hold a secret such as DATABASE_URL.
    const summary = errors
      .map((e) => `  ${e.property}: failed ${Object.keys(e.constraints ?? {}).join(', ')}`)
      .join('\n');
    throw new Error(`Invalid environment configuration:\n${summary}`);
  }
  return env; // downstream code receives converted number/boolean values
}

// app.module.ts: ConfigModule.forRoot({ validate })

A class-validator validate function for ConfigModule.forRoot. It coerces numbers explicitly, accepts only 'true' or 'false' for booleans, and reports which variables failed without echoing their values.

How do you get typed config access with registerAs and ConfigService?

Group related settings into namespaces with registerAs. Each factory, such as database, http or auth, returns a plain object assembled from environment variables that have already passed the validation step. Validation guarantees the values are present and parseable. process.env still holds strings, though, so do the conversion inside the factory, for example Number(process.env.DB_PORT). That way each conversion happens once, in one place, instead of in every consumer.

registerAs attaches a KEY token to the factory. Inject it with @Inject(dbConfig.KEY) and type the parameter as ConfigType<typeof dbConfig>. The type comes from the factory's return value, so this.db.port is a number, there are no string keys to mistype, and renaming a field breaks the build rather than failing at runtime.

When you only need a few top-level variables, use ConfigService with generics. Declare ConfigService<EnvVars, true>. The second argument tells the compiler that validation ran, so values are not typed as possibly undefined. Then call get('PORT', { infer: true }), which returns the type declared for PORT in EnvVars and also restricts the key to known names.

Prefer namespaced injection for anything a module owns, such as connection settings or auth secrets. It narrows each class to the settings it actually uses, and tests can supply a plain object for that token. Keep ConfigService for cross-cutting values like PORT or NODE_ENV.

isGlobal: true makes ConfigService available everywhere, which hides which modules depend on configuration. Importing ConfigModule.forFeature(dbConfig) in each feature module keeps that dependency visible in the module graph.

import { Inject, Injectable, Module } from '@nestjs/common';
import { ConfigModule, ConfigService, ConfigType, registerAs } from '@nestjs/config';

// Values already passed validation; convert the strings once, here.
export const dbConfig = registerAs('database', () => ({
  host: process.env.DB_HOST as string,
  port: Number(process.env.DB_PORT),
  name: process.env.DB_NAME as string,
}));

// Shape of the top-level variables checked by the validation step.
interface EnvVars {
  PORT: number;
  NODE_ENV: 'development' | 'production' | 'test';
}

@Injectable()
export class DbService {
  constructor(
    // Typed from the factory's return value, so this.db.port is a number.
    @Inject(dbConfig.KEY) private readonly db: ConfigType<typeof dbConfig>,
    // `true` means validation ran, so get() does not add `| undefined`.
    private readonly config: ConfigService<EnvVars, true>,
  ) {}

  describe(): string {
    const port = this.config.get('PORT', { infer: true }); // number; key limited to EnvVars
    return `${this.db.host}:${this.db.port}/${this.db.name} (app on ${port})`;
  }
}

@Module({
  // Makes this module's config dependency explicit instead of relying on isGlobal.
  imports: [ConfigModule.forFeature(dbConfig)],
  providers: [DbService],
})
export class DbModule {}

A registerAs database namespace injected with ConfigType, alongside ConfigService<EnvVars, true> using get('PORT', { infer: true }), with the dependency declared through ConfigModule.forFeature.

Wiring typed config into forRootAsync for database, cache and HTTP clients

A synchronous call like CacheModule.register({ ttl: Number(process.env.CACHE_TTL) }) has a timing problem. The options object is built when the @Module() decorator is evaluated, which happens as soon as the file is imported. That is before ConfigModule has loaded .env files and before your validate function has run. The value you get is whatever happens to be in the process environment at import time. It is untyped and unvalidated, and if the variable is missing it may silently become NaN or undefined.

The fix is to move option construction into a factory that Nest calls during dependency resolution. Most configurable Nest modules expose forRootAsync or registerAsync for this. Each of these accepts three things:

  • imports: bring in ConfigModule.forFeature(dbConfig) so the namespaced provider is resolvable in this module's scope.
  • inject: list dbConfig.KEY, the token created by registerAs, rather than ConfigService.
  • useFactory: receive the resolved namespace typed as ConfigType<typeof dbConfig>, and map its fields to the module's options.

Injecting the namespace token instead of calling configService.get('database.host') removes the string paths entirely. If someone renames a field, the factory fails to compile instead of failing at runtime.

The same pattern covers the database connection, CacheModule.registerAsync for the cache store, and HttpModule.registerAsync for base URLs and timeouts on outbound clients.

To refactor an existing codebase, search for process.env outside your registerAs files. Each hit is either a module option that belongs in an async factory, or a service value that should come from an injected config namespace. Once those are gone, a test can override a single provider token to change configuration, without mutating the global environment.

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigType, registerAs } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { HttpModule } from '@nestjs/axios';
import { validate } from './env.validation'; // your schema validation function

// Only registerAs factories read process.env. They run after ConfigModule has loaded and validated the env.
export const dbConfig = registerAs('database', () => ({
  host: process.env.DB_HOST as string,
  port: parseInt(process.env.DB_PORT ?? '5432', 10),
  name: process.env.DB_NAME as string,
}));

export const billingApiConfig = registerAs('billingApi', () => ({
  baseUrl: process.env.BILLING_API_URL as string,
  timeoutMs: parseInt(process.env.BILLING_API_TIMEOUT_MS ?? '5000', 10),
}));

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, validate }),
    // Before: TypeOrmModule.forRoot({ host: process.env.DB_HOST, ... }) was evaluated at import time, before validation.
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule.forFeature(dbConfig)], // makes dbConfig.KEY resolvable here
      inject: [dbConfig.KEY],                       // the namespace token, not ConfigService
      useFactory: (db: ConfigType<typeof dbConfig>) => ({
        type: 'postgres',
        host: db.host, // a renamed field breaks compilation instead of failing at runtime
        port: db.port,
        database: db.name,
      }),
    }),
    HttpModule.registerAsync({
      imports: [ConfigModule.forFeature(billingApiConfig)],
      inject: [billingApiConfig.KEY],
      useFactory: (api: ConfigType<typeof billingApiConfig>) => ({
        baseURL: api.baseUrl,
        timeout: api.timeoutMs,
      }),
    }),
  ],
})
export class AppModule {}

Namespaced configs created with registerAs are injected by their KEY token into forRootAsync and registerAsync factories. The database and HTTP client options are built only after validation and never read process.env directly.

How do you test config validation and override config in unit tests?

Tests should never need to touch process.env at all. Every registerAs factory exposes a KEY property, which is the injection token for that namespace. In Test.createTestingModule, provide that token with useValue and a plain object, such as a database namespace with a fake host and port. You can also call overrideProvider(databaseConfig.KEY).useValue(...) on a module that already imports the real config. Services that inject the namespace with @Inject(databaseConfig.KEY) receive the test object directly. No .env file is read, no validation runs, and each test states exactly the configuration it depends on.

This matters because setting process.env per test case does not work reliably. ConfigModule runs validation and the registerAs factories once, when the module initializes. With cache: true, ConfigService.get also memoizes values after the first read. A test that changes process.env.DB_HOST after the testing module compiles will often still see the old value. Tests can then pass or fail depending on the order Jest runs them in.

Test the validate function on its own as a plain unit, separate from Nest. Pass it a known-bad object, for example a missing DATABASE_URL and a non-numeric PORT, alongside a valid-looking JWT_SECRET set to a sentinel string. Then make three assertions:

  • The function throws.
  • The message names both offending keys.
  • The message does not contain the sentinel.

The last assertion catches error formatting that dumps the whole input object. That kind of formatting would leak real secrets into CI logs and crash reports.

How can typed config validation save engineering time?

The time savings come from moving config mistakes to the point where they are cheapest to diagnose:

  • Shorter debugging. A boot error such as "DATABASE_URL: failed isNotEmpty" names the key and the rule. Without validation, the same mistake shows up as a connection timeout, a NaN port, or a feature that is silently enabled. An engineer then has to trace that symptom back to an environment variable.
  • Fewer runtime incidents from config drift. A missing or malformed variable stops the rollout at the first pod. Without validation it reaches users and is discovered later, often by someone other than the person who made the change.
  • Faster onboarding. The schema class or Zod object is an up-to-date list of every variable the service needs, with types and defaults. New contributors read it instead of reverse-engineering process.env calls across the codebase, or asking a teammate for a working .env.
  • Safer refactors. With ConfigType<typeof ...> and ConfigService<EnvVars, true>, renaming or retyping a setting produces compiler errors at every consumer. You don't find out through a failed request in staging.
  • Simpler tests. Overriding a namespace token with a plain object removes the per-test process.env setup and teardown. It also removes the order-dependent flakiness that comes with it.

To see how these add up, here is an illustrative estimate. Every input in it is assumed, not measured. Assume a team ships 40 deploys a month. Assume 1 in 20 of those deploys contains a config mistake, which gives 2 mistakes a month. Assume a mistake caught at boot by a named validation error takes 15 minutes to fix. Assume the same mistake found at runtime takes 3 engineer-hours, once you count investigation, rollback and redeploy. Under those assumed inputs, validation turns about 6 engineer-hours a month into about 30 minutes. Before you rely on a figure like this, substitute your own deploy frequency and incident history.

When should you avoid env validation, and what are the alternatives for secrets and runtime config?

Validation guards the boot path, and that is also its limit. ConfigModule resolves values once, when the module initializes. A typed DatabaseConfig is a snapshot. If you change the underlying variable while the process is running, the app never sees it. Feature flags, rate limits and kill switches often need to change in seconds, without a deploy. Put them behind a runtime config source that the app polls or subscribes to, and give that source its own validation at read time. If you force them through env validation, every flag flip becomes a restart, and a restart is the wrong blast radius for a flag change.

Treat .env as a local-development convenience. In production, set ignoreEnvFile: true, or point envFilePath at an environment-specific file you control. Then let the deployment platform or a secrets manager inject variables into the process. This keeps secrets out of images and repositories. It also means the schema validates what the platform actually supplied, not a stale file someone baked into the image.

Concern Env validation at boot Runtime config source
Changes take effect On restart Without restart
Typical values DB URLs, ports, credentials Flags, rate limits, thresholds
Failure mode Process refuses to start Fall back to the last known good value
Secret rotation Requires restart or re-read Can refresh in place

Relax the defaults deliberately and in narrow cases:

  • Global config: Drop isGlobal in libraries and plugins. There, explicit imports document which module depends on which settings.
  • Strict required variables: Make a variable optional only when it has a safe default. Optional-with-no-default just moves the crash to the first request.
  • Coercion: Disable implicit coercion for values where "false" becoming true would be dangerous. Parse those values explicitly instead.

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.