skip to content

In a NestJS app, MailModule imports ConfigModule.forFeature(mailConfig), yet another module's constructor reads configService.get('mail.host') and gets undefined; why?

level: seniorimportance: should knowfreq 30%

answer

  1. partial registration
  2. a separate merge step
  3. nobody depends on the loader
  4. hooks run after every instance

basics

~20 s

forFeature merges the namespace into ConfigService's shared configuration through a separate loader provider that nothing depends on, so Nest does not order it before other modules' constructors. Read it in onModuleInit, or inject mailConfig.KEY directly.

solid answer

~40 s

`ConfigModule.forFeature(mailConfig)` registers the namespace's factory as a provider, plus a separate loader provider that copies the factory's result into the configuration object `ConfigService` reads, under `mail`. Nest instantiates the providers of all modules concurrently during bootstrap, and nothing depends on that loader, so a constructor elsewhere can run before the merge; the docs call module initialization order indeterminate. `get()` then misses, and `getOrThrow()` would fail boot. Two fixes are safe: read the value in `onModuleInit()`, which Nest calls only after every singleton provider has been instantiated, or inject `@Inject(mailConfig.KEY) mail: ConfigType<typeof mailConfig>` in a module that imports `forFeature(mailConfig)`, which makes the factory a real dependency.

code

typescript · 27 lines
typescript
import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService, ConfigType } from '@nestjs/config';
import { mailConfig } from './mail.config.js';

@Injectable()
export class NotificationsService implements OnModuleInit {
  private smtpHost?: string;

  constructor(
    private readonly config: ConfigService,
    // Safe at construction: the factory is a real dependency.
    @Inject(mailConfig.KEY)
    private readonly mail: ConfigType<typeof mailConfig>,
  ) {
    // Unsafe here: the forFeature merge may not have run yet.
    // this.smtpHost = this.config.get('mail.host');
  }

  onModuleInit(): void {
    // Safe: every singleton provider exists before hooks run.
    this.smtpHost = this.config.get<string>('mail.host');
  }

  hosts(): [string | undefined, string | undefined] {
    return [this.smtpHost, this.mail.host];
  }
}

go deeper

for a junior

Recall that forFeature registers a configuration namespace for one feature module, and that a value it loads is reliably readable in onModuleInit or through an injected namespace token.

for a middle

Explain the three providers forFeature registers and why ConfigService.get depends on the loader's merge rather than on the factory itself.

for a senior

Diagnose it as an instantiation-order race: no dependency edge to the loader, concurrent module instantiation, a getOrThrow that fails boot only sometimes, and fixes that hold by construction.

for a principal

Set the convention that values needed at construction are injected by namespace token, and that cross-module reads through ConfigService happen in hooks or lazily, so the race cannot return.

## The symptom `ConfigModule.forFeature()` is **partial registration** in `@nestjs/config`: instead of loading every configuration factory in the root module, a feature module loads only its own namespace, for example `ConfigModule.forFeature(mailConfig)` in `MailModule`, where `mailConfig` was created with `registerAs('mail', ...)`. Elsewhere, a provider calls `configService.get('mail.host')` in its constructor and receives `undefined`, even though `SMTP_HOST` is set. Moving the same call into a method, or into `onModuleInit()`, returns the right value. Adding or reordering an unrelated import can change the outcome. ## What `forFeature()` registers Reading the package's source, `forFeature(mailConfig)` returns a dynamic module with three providers: 1. **The namespace's factory provider**, under the token `mailConfig.KEY`. Its value is the object the factory returns. 2. **A `ConfigService` provider** that depends on that factory provider and returns the shared `ConfigService` instance. 3. **A loader provider** that takes the factory's object and writes it into the shared configuration object that every `ConfigService` read goes through, under the key `mail`. The third provider is the one that makes `'mail.host'` resolvable, and **nothing injects it**. Nest builds it because it is registered in that module, not because anyone asked for it. ## Why the constructor loses the race - During bootstrap Nest instantiates the providers of **all modules concurrently**, resolving each provider's own dependencies first. - Your provider depends on `ConfigService`, not on the loader. Dependency injection therefore guarantees nothing about whether the loader has already run when your constructor executes. - The documentation states it at this strength: `forFeature()` runs during module initialization, the order of module initialization is indeterminate, and a value loaded this way by another module may not be available in a constructor yet. When the merge has not happened, `get('mail.host')` misses in the configuration object and falls through to `process.env`, which has no `mail.host` key, so it returns `undefined` or your default. With `getOrThrow('mail.host')` the same miss throws a `TypeError` during bootstrap, a failure that can appear or disappear as module imports change. ## Fixes that hold by construction | Fix | Why it is safe | |---|---| | Read in `onModuleInit()` | Nest calls lifecycle hooks only after the singleton providers of every module have been instantiated, so every loader has run | | Inject `@Inject(mailConfig.KEY)` typed `ConfigType<typeof mailConfig>` | Your class now depends on the factory's provider, so injection builds it first; no shared object is involved | | Read lazily in a method | By the time a request or job calls it, bootstrap has finished | Token injection needs the token to be visible: import `ConfigModule.forFeature(mailConfig)` in the consuming module too, or load the namespace through `forRoot({ load: [mailConfig], isGlobal: true })`. It is the most robust option, because it does not depend on the merge at all and it gives a typed object. ## What does not fix it - **Import order.** Listing `MailModule` first in `AppModule.imports` does not create a dependency edge, so it is not a guarantee, even if it happens to work today. - **`@Global()`.** Making a module global changes which providers are visible, not when the loader runs. - **`forwardRef()`.** It resolves circular dependencies between providers; there is no cycle here. - **`cache: true`.** It memoises reads from `process.env`, which is not where namespaced values live. ## Finding it in a codebase - Search for `ConfigModule.forFeature(` and note each namespace name it registers. - Search for reads of those names through `ConfigService` (`get('mail.` and `getOrThrow('mail.`) and check whether any sits in a constructor or a property initialiser outside the registering module. - Replace each such read with an injected `ConfigType` of the namespace, or move it into `onModuleInit()`. - Prefer `getOrThrow` for the remaining reads, so a regression fails loudly at boot instead of passing `undefined` into a client. ## How to explain it in an interview A strong answer names the mechanism (a separate merge step that nothing depends on), cites the documented guarantee (`onModuleInit()` is safe), and prefers injecting the namespace token where the value is needed at construction. It also notes that hook ordering changes in NestJS 12, where hooks run by hierarchy level, do not affect this: all instantiation still finishes before the first hook runs.

  • Why is onModuleInit() safe when the constructor is not?
    Nest instantiates the singleton providers of every module during bootstrap and only then calls `onModuleInit()` hooks. By the time any hook runs, each `forFeature()` loader has already merged its namespace. NestJS 12 changed the order in which hooks are called, by hierarchy level, but not the rule that instantiation finishes first.
  • What happens if the constructor uses getOrThrow('mail.host') instead of get()?
    The missed merge becomes a `TypeError` with `Configuration key "mail.host" does not exist`, thrown while Nest is constructing providers, so bootstrap fails. Because the outcome depends on instantiation order that Nest does not promise, the failure can appear or disappear when module imports change, which makes it confusing to debug.

A shared whiteboard a colleague fills in at some point during the morning: glance at it at 9:00 sharp and it may be blank. Read it after the morning stand-up, when everyone has finished, or ask the colleague directly for the figure, and you always get it.

  • forFeature values are request-scoped, so constructors cannot see them.
  • Marking the consuming module @Global() makes the value available in its constructor.
  • ConfigModule.forFeature replaces the root configuration, wiping forRoot values.
  • Importing MailModule first in AppModule reliably fixes the ordering.
  • forFeature runs its factory lazily on the first ConfigService.get call.