In NestJS's @nestjs/config, what does registerAs() create, and how do you inject a namespace with ConfigType instead of ConfigService.get?
answer
- a factory with a name
- the KEY property
- ConfigType of typeof factory
- asProvider for forRootAsync
basics
~10 sregisterAs('mail', factory) tags a configuration factory with a namespace and an injection token, factory.KEY. Load it, then inject the whole object with @Inject(mailConfig.KEY) typed as ConfigType<typeof mailConfig>, or read one value as 'mail.host'.
solid answer
~30 s`registerAs('mail', () => ({ host: process.env.SMTP_HOST }))` returns the factory with two additions: a `KEY` property, the provider token for that namespace, and an `asProvider()` method. You load it through `ConfigModule.forRoot({ load: [mailConfig] })` or `ConfigModule.forFeature(mailConfig)`. Code can then call `configService.get('mail.host')`, or inject the whole object with `@Inject(mailConfig.KEY) private mail: ConfigType<typeof mailConfig>`, where `ConfigType` is the factory's return type. `mailConfig.asProvider()` turns the namespace into an options provider for another module's `forRootAsync()`. The factory reads `process.env` itself, so `validationSchema` does not validate or coerce what it returns.
code
typescript · 25 linesimport { Inject, Injectable, Module } from '@nestjs/common';
import { ConfigModule, ConfigType, registerAs } from '@nestjs/config';
export const mailConfig = registerAs('mail', () => ({
host: process.env.SMTP_HOST ?? 'localhost',
port: parseInt(process.env.SMTP_PORT ?? '587', 10),
}));
@Injectable()
export class MailService {
constructor(
@Inject(mailConfig.KEY)
private readonly mail: ConfigType<typeof mailConfig>,
) {}
endpoint(): string {
return `${this.mail.host}:${this.mail.port}`;
}
}
@Module({
imports: [ConfigModule.forFeature(mailConfig)],
providers: [MailService],
})
export class MailModule {}go deeper
Recall that registerAs gives a configuration factory a name, that it must be loaded through forRoot's load or forFeature, and that 'mail.host' reads one value from it.
Explain KEY as the injection token, ConfigType as the factory's return type, and what asProvider returns for another module's forRootAsync.
Show that schemas do not reach namespace factories, so conversion and checks live in the factory, and that token injection gives an ordering guarantee a ConfigService.get call does not.
Weigh typed namespaces injected by token against string keys read through ConfigService across a codebase: refactor safety and test overrides against one more file per area.
## What a namespace is In `@nestjs/config`, a **custom configuration factory** is a function that returns a configuration object. You build it from `process.env` (already merged with the `.env` file by the time it runs), and you decide the shape, defaults and conversions. `registerAs()` gives such a factory a **namespace**, a name under which its object lives: ```typescript import { registerAs } from '@nestjs/config'; export default registerAs('mail', () => ({ host: process.env.SMTP_HOST, port: parseInt(process.env.SMTP_PORT ?? '587', 10), })); ``` `registerAs(token, factory)` returns the same factory, with two non-enumerable additions: - **`KEY`**: the **injection token** for this namespace. It is a generated string built from the name, not the bare string `'mail'`, so always reference it as `mailConfig.KEY`. - **`asProvider()`**: a helper that turns the namespace into a provider definition for another module (below). ## Loading it A namespace does nothing until a module loads it: 1. **Globally**, through `ConfigModule.forRoot({ load: [mailConfig] })` in the root module. The token is exported by the module `forRoot()` returns, so with `isGlobal: true` it can be injected anywhere. 2. **Per feature**, through `ConfigModule.forFeature(mailConfig)` in the module that needs it, called **partial registration**. The token is exported to that importing module. Either way, Nest calls the factory during dependency injection and also merges its object into `ConfigService`'s configuration under the namespace name. ## Two ways to read it | | `configService.get('mail.host')` | `@Inject(mailConfig.KEY) mail: ConfigType<typeof mailConfig>` | |---|---|---| | What you get | One value by dotted path | The whole object the factory returned | | Typing | Whatever type argument you write | Inferred from the factory's return type | | Typo in the key | Silent `undefined` | Compile error on `mail.hots` | | Dependency | On `ConfigService` | Directly on the namespace's provider | **`ConfigType<typeof mailConfig>`** is a type helper: it takes the factory's type and yields what the factory returns, unwrapping a promise for an async factory. It is purely compile-time; it does not convert or check values. Injecting the token has a second benefit: your class depends on the namespace's own provider, so dependency injection must build the factory's object before it builds your class. ## Feeding another module: `asProvider()` Many Nest integration modules accept an async options provider through a `forRootAsync()` method. `asProvider()` returns exactly that shape for a namespace: ```typescript { imports: [ConfigModule.forFeature(mailConfig)], useFactory: (config) => config, inject: [mailConfig.KEY], } ``` So passing `mailConfig.asProvider()` to such a module's `forRootAsync()` hands the namespace object over as that module's options, without boilerplate. (How to write a module with a `forRootAsync()` of your own is a separate topic.) ## Pitfalls - **Validation does not reach it.** `validationSchema` and `validate` check the environment variables. A namespace factory reads `process.env` afterwards, where values are still strings, so `port` above is whatever the factory makes of it. Convert and check inside the factory, and throw there if a value is unacceptable; a throw stops the app from booting. - **The wrong token.** `@Inject('mail')` is not the namespace's token; Nest fails to resolve it. Use `mailConfig.KEY`. - **Visibility.** Injecting `mailConfig.KEY` works only where the token is visible: in a module that imports `ConfigModule.forFeature(mailConfig)`, or anywhere when `forRoot()` loaded it with `isGlobal: true`. - **Namespace versus top-level keys.** A plain factory in `load` merges its keys at the top level, where they can shadow environment variables of the same name; a namespaced factory keeps them under its name. ## Choosing between `forRoot` loading and `forFeature` - **Load in `forRoot()`** when several modules share a namespace, such as database settings read by a repository layer and a health check. One registration, visible everywhere with `isGlobal: true`. - **Use `forFeature()`** when exactly one feature owns the settings, such as mail settings used only by the mail module. The module declares its own configuration next to its code, and the root module stays short. - **Inject the token** in either case wherever a value is needed at construction time. Reading a `forFeature()` namespace through `ConfigService` in another module's constructor is the classic way to get `undefined`, because the merge into `ConfigService`'s shared object is not ordered before that constructor.
- In NestJS, if validationSchema does not cover namespace factories, how do you validate a namespace's values?Inside the factory. A `registerAs()` factory runs during dependency injection with the merged `process.env`, so it can parse, apply defaults and `throw` when a value is out of range; a throw there stops the application from bootstrapping. Alternatively, let the schema validate the raw variables and have the factory only reshape values the schema already proved present.
- Why might you prefer injecting mailConfig.KEY over calling ConfigService.get('mail.host') in a constructor?Injecting the token gives a typed object, so a misspelt property is a compile error instead of a silent `undefined`. It also makes your class depend on the namespace's own provider, so Nest builds the factory's object before your constructor runs. `ConfigService.get()` reads a shared object that a separate step fills in, and dependency injection does not order that step before your constructor.
- The injection token of registerAs('mail') is the plain string 'mail'.
- validationSchema also validates and coerces registerAs factories.
- ConfigType converts the namespace's values to their declared types at runtime.
- A namespace can only be read through ConfigService.get, never injected.
- asProvider() creates a new global ConfigModule for the namespace.