In NestJS 12, how does ConfigModule.forRoot's validationSchema stop the app booting on a missing secret, and what does ConfigService then return?
answer
- any Standard Schema
- checked before providers exist
- every failing variable listed
- schema output, not raw strings
basics
~20 sIn NestJS 12, forRoot checks the merged .env and process variables against a Standard Schema before any provider is built, throwing 'Config validation error' with every bad variable. ConfigService then returns the schema's coerced output.
solid answer
~40 sIn NestJS 12, `ConfigModule.forRoot({ validationSchema })` accepts any Standard Schema, for example a Zod object, and validates the `.env` values merged with `process.env` while Nest is still assembling modules, before any provider is constructed. A variable declared without a default is required, so a missing secret makes bootstrap throw `Config validation error:` followed by one `PATH: message` line per failing variable. By default, unknown variables such as `PATH` do not fail it. Once it passes, `ConfigService.get()` returns the schema's output, so `z.coerce.number()` yields a number and defaults apply, while `process.env` keeps strings. Library-specific options go under `validationOptions.libraryOptions`; Joi still works from Joi 18.
code
typescript · 18 linesimport { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { z } from 'zod';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [`.env.${process.env.NODE_ENV ?? 'development'}`, '.env'],
validationSchema: z.object({
DATABASE_URL: z.string(),
SMTP_PASSWORD: z.string(),
SMTP_PORT: z.coerce.number().default(587),
}),
}),
],
})
export class AppModule {}go deeper
Recall that a schema passed to validationSchema makes the app refuse to start when a required variable is missing, and that a variable without a default is required.
Explain what is validated (the merged file and process variables), the 'Config validation error' message, and that ConfigService returns coerced values while process.env keeps strings.
Cover the NestJS 12 upgrade: Joi 18 or later, settings under validationOptions.libraryOptions, and that factories in load are outside the schema's reach and need their own checks.
Argue for one boot-time schema per service as the contract for its environment, and decide whether teams move Joi schemas to a Standard Schema library or keep Joi 18.
## Why fail at boot A service that starts without its database URL or mail password looks healthy until the first request touches the missing value. `@nestjs/config` can refuse to start instead: you give `ConfigModule.forRoot()` a schema, and if the environment does not satisfy it, bootstrap throws before the app ever listens. ## How `validationSchema` works in NestJS 12 In NestJS 12 the `validationSchema` option takes any **Standard Schema**, a small shared interface that several validation libraries implement, so the package no longer depends on one library. A Zod object is the docs' example. During `forRoot()`: 1. **Collect.** The `.env` file values are merged with `process.env` (runtime variables win unless `override: true`). The schema sees this whole merged object, so it also catches a variable the deployment platform forgot to set. 2. **Validate.** The package calls the schema's standard `validate` entry point. This happens while Nest is still resolving the module graph, before any provider is constructed. 3. **Fail or keep.** On failure it throws an `Error` whose message starts with `Config validation error:` and lists each issue as `PATH: message`, one per line. On success it stores the schema's **output** for `ConfigService`. 4. **Write back.** Validated values are copied into `process.env` as strings, only for keys `process.env` does not already hold (all keys with `override: true`). A variable declared **without a default** is required; one with a default is filled in when absent. ## What `ConfigService` returns afterwards | Variable in the environment | Schema entry | `ConfigService.get()` | `process.env` | |---|---|---|---| | `SMTP_PORT=2525` | coerced number, default 587 | `2525` (number) | `'2525'` | | `SMTP_PORT` unset | coerced number, default 587 | `587` (number) | `'587'` | | `SMTP_PASSWORD` unset | required string | boot fails | boot fails | | `FEATURE_FLAG=on` | not declared | `'on'` | `'on'` | Two details here surprise people: - **Coercion reaches `ConfigService`, not `process.env`.** Environment variables are strings, which is why the docs use `z.coerce.number()`. Code reading `process.env.SMTP_PORT` still gets a string. - **Undeclared variables survive.** A Zod object strips keys it does not declare, but the package merges the undeclared variables back so they stay readable. By default unknown variables, such as `PATH` and `HOME`, do not fail validation. ## Options and alternatives - **`validationOptions`** is typed against the Standard Schema options; anything specific to your library goes under **`validationOptions.libraryOptions`**. - **`validatePredefined: false`** validates only the values from the `.env` file, not variables already in the process environment. - **`validate`** is the alternative: a **synchronous** function that receives the merged object, returns the validated object (which becomes what `ConfigService` serves) and throws to stop bootstrap. It is how a class-based validator is wired in. If both are set, `validate` is the one used. - **Scope.** Neither option checks custom configuration factories passed to `load` or registered with `registerAs()`; those validate themselves. ## Upgrading from NestJS 11 In NestJS 11, `validationSchema` was Joi-specific and Joi's settings (`allowUnknown`, `abortEarly`) sat directly under `validationOptions`. In NestJS 12: - A Joi schema still works, but only from **Joi 18**, the release that implements Standard Schema. - Joi's settings move to `validationOptions.libraryOptions`. For Joi schemas the package keeps its historical defaults, `allowUnknown: true` and `abortEarly: false`, and merges yours on top. - The docs now recommend a Standard Schema library such as Zod for new projects. `nest upgrade` applies this `validationOptions` move for you as part of the mechanical migration. ## Reading a failure When bootstrap stops with `Config validation error:`, each line names one variable and the schema library's complaint about it. The usual causes: - **The file was never read.** `envFilePath` is resolved against the process's working directory, so starting the app from another directory skips the file silently and every file-only variable looks missing. - **A typo in a name.** The schema demands `SMTP_PASSWORD` while the platform sets `SMTP_PASS`; the extra variable passes as unknown, and the declared one fails. - **Wrong type.** A value that cannot be coerced, such as `SMTP_PORT=smtp`, fails with the library's type message. One gap to know: a schema that only demands a string accepts an empty one, so a secret set to nothing passes. If empty must fail, say so in the schema.
- In NestJS 12, do the schema's coerced values also reach process.env?Only as strings. After validating, `forRoot()` writes string, number and boolean values into `process.env` as strings, and only for keys `process.env` does not already hold (all keys with `override: true`). So `process.env.SMTP_PORT` stays `'2525'` while `ConfigService.get('SMTP_PORT')` returns `2525`. Read configuration through `ConfigService` to get the schema's output.
- When would you use the validate option instead of validationSchema?When your validator is not a Standard Schema, for example a class with class-validator decorators. `validate` is a synchronous function that receives the merged variables, returns the validated object, which `ConfigService` then serves, and throws to stop bootstrap. If both options are set, `@nestjs/config` uses `validate`.
- Does validationSchema check values produced by load factories or registerAs namespaces?No. The docs state that it applies only to environment variables. A custom configuration factory reads `process.env` itself and returns whatever it builds, so range checks and conversions for those objects belong inside the factory, which can throw to stop bootstrap.
- In NestJS 12, validationSchema accepts only Joi schemas.
- A missing required variable is reported the first time ConfigService.get reads it.
- Unrelated variables such as PATH make the schema validation fail by default.
- After validation, process.env holds the coerced numbers too.
- Joi options still go directly under validationOptions in NestJS 12.
- validationSchema also validates the objects returned by load factories.
Assumes NestJS 12: @nestjs/config's validationSchema takes any Standard Schema and library options moved under validationOptions.libraryOptions; in NestJS 11 it was Joi-specific.