In a NestJS 12 app, what does ConfigModule.forRoot() do with a .env file, and how do other modules get ConfigService?
answer
- dotenv under the hood
- working directory by default
- shell or file: who wins?
- import it, or make it global
basics
~20 sConfigModule.forRoot() parses the .env file in the working directory, merges it with process.env (real environment variables win by default) and registers ConfigService. A feature module imports ConfigModule to inject it, unless forRoot set isGlobal: true.
solid answer
~40 s`ConfigModule.forRoot()` in the root module parses `.env` from the current working directory with dotenv (or the files listed in `envFilePath`), merges those pairs with `process.env`, and registers `ConfigService`, whose `get()` reads the merged result. When a key is set in both places, the real environment variable wins; `override: true` makes the file win instead. With an array in `envFilePath`, the first file that defines a key wins. `ConfigService` is an ordinary provider, so a feature module adds `ConfigModule` to its `imports` before injecting it, unless `forRoot({ isGlobal: true })` registered the module globally. `ignoreEnvFile: true` skips the file and uses only the runtime environment.
code
typescript · 28 linesimport { Injectable, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Injectable()
export class MailService {
constructor(private readonly config: ConfigService) {}
smtpHost(): string | undefined {
return this.config.get<string>('SMTP_HOST');
}
}
@Module({
providers: [MailService],
exports: [MailService],
})
export class MailModule {}
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: ['.env.development.local', '.env.development'],
}),
MailModule,
],
})
export class AppModule {}go deeper
Recall that forRoot() goes in the root module, loads .env from the working directory and registers ConfigService. Know that a feature module needs ConfigModule in its imports unless isGlobal is true.
Explain the merge: runtime variables beat the file unless override is true, the first envFilePath entry wins, and file values are copied into process.env for keys not already set.
Show you know what bites in production: a stray .env baked into an image, ignoreEnvFile for platform-injected config, and values that must exist before Nest even boots.
Talk about the house rule: one global forRoot in the root module, whether .env files are allowed outside local development, and how that keeps every service's configuration path predictable.
## What `ConfigModule.forRoot()` does at startup `@nestjs/config` is NestJS's configuration package. Its entry point is `ConfigModule.forRoot()`, a static method that returns a **dynamic module** (a module whose providers are computed from the options you pass). You call it once, in the imports of the root module, usually `AppModule`. While Nest builds the module graph, `forRoot()` runs these steps: 1. **Read the env file.** It parses `.env` in the process's current working directory with the dotenv parser, or the file or files named in `envFilePath`. A path that does not exist is skipped, not reported as an error. 2. **Merge with the runtime environment.** The parsed key/value pairs are merged with `process.env`, the variables the process was started with (a shell export, a container's environment, a platform's settings). 3. **Copy file values back.** Values from the file are written into `process.env` for keys it does not already hold, so code that reads `process.env` directly after this point sees them too. 4. **Register `ConfigService`.** The returned module provides `ConfigService`, an injectable whose `get()` method reads the merged values, plus any custom configuration objects you loaded through the `load` option. ## Which value wins The package follows dotenv's conflict rule: the runtime environment beats the file unless you opt out. | Situation | What `ConfigService.get('KEY')` returns | |---|---| | Key only in `.env` | The file's value | | Key only in the runtime environment | The runtime value | | Key in both | The runtime value | | Key in both, `override: true` | The file's value | | Key in two files of an `envFilePath` array | The value from the first file listed | So `envFilePath: ['.env.development.local', '.env.development']` lets a developer's local file shadow the shared one, and a variable exported in the shell still beats both. These are this package's rules for one boot; how a team should layer configuration sources in general is a framework-neutral question. ## Getting `ConfigService` into a feature module `ConfigService` is an ordinary Nest provider, so Nest's **module encapsulation** applies: a module can inject only its own providers and the ones exported by modules it imports. There are two ways in: - **Import the module.** Add the plain `ConfigModule` class (not another `forRoot()` call) to the feature module's `imports`, then inject `ConfigService` through the constructor. - **Make it global.** Pass `isGlobal: true` to `forRoot()` once; the returned dynamic module is registered as global, and every module can inject `ConfigService` without importing anything. - **Neither.** Bootstrap fails with Nest's dependency-resolution error ("Nest can't resolve dependencies of the ..."), naming `ConfigService` as the argument it could not find in that module. Calling `forRoot()` again in each feature module is the wrong fix: it re-runs the loading and validation steps for no benefit. ## Options that change loading - **`envFilePath`**: a string or an array of paths, replacing the default `.env` in the working directory. - **`ignoreEnvFile: true`**: read no file at all; only the runtime environment (and custom configuration) is used. Useful when a platform injects every variable and a stray `.env` in the image must never be read. - **`override: true`**: let file values beat runtime variables, and write all of them into `process.env`. - **`expandVariables: true`**: resolve `${OTHER_VAR}` references inside the file (through dotenv-expand). - **`cache: true`**: memoise values `ConfigService` reads from `process.env`, because reading `process.env` is comparatively slow. - **`isGlobal: true`**: register the module globally, as above. ## What it does not cover - **Values needed before Nest boots.** If something must be known before the root module is even processed (for example options passed straight to `NestFactory.createMicroservice()`), the docs point to the Nest CLI's `--env-file` flag, which hands the file to Node's own loader rather than to this package. - **Types.** Every value that comes from a file or the environment is a **string**. `ConfigService.get<number>('PORT')` only changes the TypeScript type; a validation schema or a configuration factory is what actually converts it. - **Code that runs at import time.** A module decision that reads `process.env` while modules are still being assembled can await the `ConfigModule.envVariablesLoaded` promise, which resolves once `forRoot()` has loaded the variables. ## A worked example A service keeps its database and mail settings in `.env.development` on a laptop, while production injects the same names as real environment variables and ships no file at all. - Locally, `forRoot({ envFilePath: ['.env.development.local', '.env.development'] })` loads the shared file, and a developer's personal `.env.development.local` overrides single keys because it is listed first. - In production the listed files do not exist, so they are skipped and every value comes from the runtime environment; setting `ignoreEnvFile: true` there makes that explicit. - A developer who exports `DATABASE_URL` in a terminal for one debugging session overrides both files without editing them, because the runtime value wins. - Every module that needs these values injects `ConfigService`, because `forRoot()` was called once with `isGlobal: true`.
- In NestJS, what does ignoreEnvFile: true change, and when would you set it?`ConfigModule.forRoot({ ignoreEnvFile: true })` reads no `.env` file at all, so `ConfigService` sees only the runtime environment plus any custom configuration you loaded. It fits deployments where the platform injects every variable and a `.env` accidentally copied into the image must never be read. A `validationSchema` still runs, against the runtime variables.
- Why can code read a .env-only value from process.env after ConfigModule.forRoot() has run?`forRoot()` writes the file's values into `process.env` for keys the process does not already have (every key when `override: true`). Code that reads `process.env` directly after the module has loaded therefore sees them. Code that runs earlier, such as a module chosen at import time, can await `ConfigModule.envVariablesLoaded` first.
- Values in .env always override variables exported in the shell.
- ConfigService can be injected anywhere without importing ConfigModule or setting isGlobal.
- With several envFilePath entries, the last file listed wins.
- Each feature module should call ConfigModule.forRoot() again to read config.
- ConfigService.get<number>() converts the env string into a number.