In NestJS's @nestjs/config, how do ConfigService.get and ConfigService.getOrThrow differ, and when does each return undefined or throw?
answer
- same arguments, different miss
- the default argument counts
- undefined, not empty
- fails at the call, not at boot
basics
~10 sConfigService.get returns the value, the default you passed, or undefined, and never throws. getOrThrow takes the same arguments but throws a TypeError when the result is still undefined, at the moment it is called.
solid answer
~40 sBoth methods take a key (dot notation reaches into nested custom configuration, as in `'database.host'`) and an optional default. `get()` looks the key up in loaded custom configuration, then in validated environment values, then in `process.env` (unless `skipProcessEnv` is set), then falls back to the default; a miss returns `undefined`. `getOrThrow()` calls the same lookup and throws `TypeError: Configuration key "SMTP_HOST" does not exist` if the result is `undefined`, and its return type excludes `undefined`. A default you pass still satisfies it, and an empty string is a value, not a miss. It fails when it is called, so a lazy read surfaces at request time; only a schema makes boot fail.
code
typescript · 20 linesimport { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class MailSettings {
readonly host: string;
readonly port: string;
constructor(private readonly config: ConfigService) {
// Runs at bootstrap: a missing SMTP_HOST stops the app here.
this.host = config.getOrThrow<string>('SMTP_HOST');
// Optional with a fallback; still a string unless a schema coerced it.
this.port = config.get<string>('SMTP_PORT', '587');
}
password(): string {
// Runs per call: a missing value throws on the first send, not at boot.
return this.config.getOrThrow<string>('SMTP_PASSWORD');
}
}go deeper
Recall that get returns undefined or your default on a miss, while getOrThrow throws a TypeError naming the key. Both accept dot paths such as 'mail.host'.
Explain the lookup order (custom configuration, validated values, process.env, default), why a type argument does not convert strings, and why an empty string passes getOrThrow.
Point out that getOrThrow fails where it is called, so a lazy read becomes a request-time outage; pair it with a boot-time schema and keep required reads in constructors.
Frame the team rule: a schema proves presence at boot, typed ConfigService generics carry that guarantee to call sites, and getOrThrow is reserved for values a schema cannot see.
## Two readers over one lookup `ConfigService` is the injectable that `@nestjs/config` registers when the root module calls `ConfigModule.forRoot()`. It has two read methods that share one lookup and differ only in what they do on a **miss**, meaning the lookup ended with `undefined`: - **`get(key, defaultValue?)`** returns whatever the lookup found, otherwise the default, otherwise `undefined`. It never throws. - **`getOrThrow(key, defaultValue?)`** runs the same lookup; if the result is still `undefined` it throws a `TypeError` with the message `Configuration key "KEY" does not exist`. Its TypeScript return type excludes `undefined`, so callers need no `!` or extra check. The key can be a dotted path such as `'mail.host'`, which walks into a nested custom configuration object. ## Where the lookup looks The order is fixed in the service's source: 1. **Custom configuration**: objects returned by the factories in `forRoot({ load: [...] })` or registered with `registerAs()` and `forFeature()`. 2. **Validated environment values**: the output of `validationSchema` or `validate`, if either is configured, including any coercion the schema did. 3. **`process.env`**, unless `forRoot()` set `skipProcessEnv: true`. With `cache: true`, values read from here are memoised. 4. **The default argument**, if you passed one. Two consequences matter in interviews. A factory in `load` that returns a `PORT` key shadows the `PORT` environment variable. And without a validation schema, a value from `process.env` is always a **string**: `get<number>('PORT')` returns `'3000'`, because the type argument is a compile-time hint, not a conversion. ## What counts as missing | Situation | `get('SMTP_HOST')` | `getOrThrow('SMTP_HOST')` | |---|---|---| | Set to `smtp.internal` | `'smtp.internal'` | `'smtp.internal'` | | Set to an empty string | `''` | `''`, no throw | | Unset, default `'localhost'` passed | `'localhost'` | `'localhost'`, no throw | | Unset, no default | `undefined` | throws `TypeError` | The check is strictly "is the result `undefined`". An empty string, `0` or `false` passes. If an empty secret must be rejected, that belongs in a validation schema, not in `getOrThrow`. ## When the failure happens `getOrThrow` is not a boot-time check. It throws **when the line runs**: - In a **constructor** of a singleton provider, that is during bootstrap, so a missing key stops the app from starting, one key at a time. - In a **method** that runs per request or per job, the first call fails, possibly hours after a deploy that looked healthy. - It reports **one key per throw**; a schema passed to `validationSchema` reports every invalid variable at once before any provider is built. That is why teams pair them: the schema guarantees presence at boot, and `getOrThrow` (or a typed `ConfigService`) gives code a non-optional type at the call site. ## Typing without runtime checks `ConfigService` takes two optional type arguments. `ConfigService<EnvVars>` together with `get('PORT', { infer: true })` infers the key's type from the `EnvVars` interface and rejects unknown keys at compile time. A second argument of `true`, as in `ConfigService<EnvVars, true>`, removes `undefined` from `get()`'s return type. Both are **assertions** for the compiler; neither checks anything at runtime. They are honest only when a schema has already proven the values exist. ## Choosing between them - Use **`get()` with a default** for genuinely optional settings, such as a timeout with a sensible fallback. - Use **`getOrThrow()`** where code cannot proceed without a value and you want the failure loud and named, ideally in a constructor so it fires at boot. - Use a **validation schema** for anything the service must refuse to start without, such as a database URL or a mail password. ## A worked example A mail sender needs `SMTP_HOST`, `SMTP_PORT` and `SMTP_PASSWORD`. The port has a sensible fallback, so `get('SMTP_PORT', '587')` is right, remembering the result is a string unless a schema coerced it. The host is needed to build the transport once, so `getOrThrow('SMTP_HOST')` in the constructor turns a missing host into a boot failure that names the key. If the password is read per send instead, reading it lazily with `getOrThrow` means a missing password is discovered only when the first message is sent, which is exactly the delay a boot-time schema exists to remove. Moving that read into the constructor, or declaring the password in the schema, brings the failure forward to deploy time, where a rollout can stop it.
- In NestJS, if a load factory returns PORT and the environment also sets PORT, which does ConfigService.get('PORT') return?The factory's value. `ConfigService.get()` checks custom configuration loaded through `load` or `registerAs()` first, then validated environment values, and only then `process.env`. So a configuration factory that happens to define a top-level key with the same name as an environment variable shadows that variable. Namespacing factories with `registerAs()` avoids accidental collisions.
- What does ConfigService<EnvVars, true> with { infer: true } add, and what does it not do?It is typing only. `infer: true` makes `get()` infer each key's type from the `EnvVars` interface and rejects keys the interface lacks; the second type argument `true` strips `undefined` from the return type. Nothing is checked at runtime, so the assertion is safe only when a validation schema has already guaranteed the values.
- getOrThrow throws even when a default value is passed.
- get<number>('PORT') converts the environment string into a number.
- getOrThrow validates every required key once at bootstrap.
- getOrThrow treats an empty string as a missing value.
- ConfigService.get throws when a key is missing.