Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 42 ยท Advanced Dependency Injection

Configuration and Environment

Learn NestJS configuration with ConfigModule and ConfigService: .env files, typed config namespaces with registerAs, and validating environment variables at startup.

Every application has settings that change between machines: the database URL, a port, an API key, a flag that turns a feature on. These must not be written into the source code. Following the well-known "twelve-factor" idea, they live in the environment (environment variables, often loaded from a .env file in development) and the code reads them at startup.

You could read process.env.DATABASE_URL anywhere, and many apps start that way. It works until a variable is missing in production and a request fails an hour after deploying, or until every value is a string and "false" turns out to be truthy. Nest's answer is the @nestjs/config package: it loads files, merges them with the real environment, groups values into typed namespaces, validates them before the app starts listening, and exposes everything through dependency injection. This lesson uses custom providers and modules; the framework code is read-only, and the runnable parts are plain-JavaScript stand-ins for the same ideas.

Installing and registering ConfigModule

The package is separate from Nest's core, so you install it with npm install @nestjs/config and import the module once in the root module:

TypeScript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.local', '.env'],
    }),
  ],
})
export class AppModule {}

forRoot() is a dynamic module method: it takes options and returns a configured module (the next lessons explain how to write your own). Two options matter immediately:

  • isGlobal: true registers ConfigService everywhere, so you do not have to import ConfigModule in each feature module. Configuration is one of the few things that justifies a global module.
  • envFilePath is one path or an array. By default the module reads .env in the working directory. When a variable appears in several files, the first file wins, and a variable that is already set in the real process environment is not overwritten by any file. That is the behavior you want: the production server's real environment beats whatever file happens to be lying around.

Never commit .env files that contain secrets. Commit a .env.example with fake values, and list the real files in .gitignore.

Where a setting comes from

Real environment Set by the host. Always wins.
.env files Loaded in order. First file wins.
Defaults in code Used only when nothing else is set.

Highest priority on the left.

1 / 2

Reading values with ConfigService

Once registered, inject ConfigService like any provider:

TypeScript
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class MailService {
  constructor(private readonly config: ConfigService) {}

  senderAddress(): string {
    return this.config.get<string>('MAIL_FROM', '[email protected]');
  }

  smtpHost(): string {
    return this.config.getOrThrow<string>('SMTP_HOST');
  }
}

get() returns undefined for an unknown key unless you give a default as the second argument. getOrThrow() throws if the key is missing, which is the right choice for settings with no sensible default. The generic <string> is only a type hint: nothing at runtime checks that the value really is a string, and everything that comes from a .env file starts out as a string. That is why validation matters, as you will see below.

Custom configuration files and namespaces

Flat keys such as DB_HOST, DB_PORT, DB_USER get unwieldy. The load option accepts functions that return structured objects, and registerAs() gives each one a namespace and a typed injection key:

TypeScript
import { registerAs } from '@nestjs/config';

export const databaseConfig = registerAs('database', () => ({
  host: process.env.DB_HOST ?? 'localhost',
  port: parseInt(process.env.DB_PORT ?? '5432', 10),
  name: process.env.DB_NAME ?? 'app',
}));
TypeScript
ConfigModule.forRoot({ isGlobal: true, load: [databaseConfig] });

Now you can read config.get('database.port') with dot notation, or inject the whole namespace with full type safety:

TypeScript
import { Inject, Injectable } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';

@Injectable()
export class DatabaseSettings {
  constructor(
    @Inject(databaseConfig.KEY)
    private readonly db: ConfigType<typeof databaseConfig>,
  ) {}

  url(): string {
    return `postgres://${this.db.host}:${this.db.port}/${this.db.name}`;
  }
}

databaseConfig.KEY is an injection token created by registerAs(), and ConfigType<typeof databaseConfig> derives the object's type from the factory, so this.db.port is a number and a typo like this.db.prot is a compile error. This is the same pattern as the Symbol tokens in the previous lesson, with the type work done for you. Notice that the conversion of DB_PORT to a number happens in one place, the factory, and not in every consumer.

Validating the environment at startup

A missing or malformed value should stop the app during boot, with a message naming the problem, not surface later as a strange runtime error. forRoot() has two ways to do this:

  • validationSchema: a Joi schema (the joi package). Joi can coerce types, apply defaults and report every error at once with validationOptions: { abortEarly: false }.
  • validate: your own function that receives the raw key-value object and returns the cleaned one. If it throws, startup fails. With class-validator you can describe the variables as a class and reuse the validation tools from Pipes and Validation.
TypeScript
import * as Joi from 'joi';

ConfigModule.forRoot({
  isGlobal: true,
  validationSchema: Joi.object({
    NODE_ENV: Joi.string().valid('development', 'test', 'production').default('development'),
    PORT: Joi.number().port().default(3000),
    DATABASE_URL: Joi.string().uri().required(),
  }),
  validationOptions: { abortEarly: false },
});

With this in place, forgetting DATABASE_URL makes the process exit at boot with an error that names the key. In a container orchestrator that means a bad deploy fails its health check immediately, and the previous version keeps serving traffic.

Practical advice

  • Keep secrets (keys, passwords) out of the repository and out of logs. Never print the whole configuration object.
  • Treat NODE_ENV as a coarse switch only. Prefer explicit settings (CACHE_TTL_SECONDS) over code that branches on the environment name.
  • Use cache: true in forRoot() if you read values in hot paths: reads from process.env are slower than reads from a cached object.
  • Read configuration through injection, not process.env, in services. Tests can then provide a fake ConfigService with a custom provider and never touch real variables.
  • For the HTTP port in main.ts, you can fetch the service from the application: app.get(ConfigService).get('PORT').

Stand-in: loading files and merging sources

The first stand-in reproduces the loading rules described above, with plain strings instead of files. It parses .env text (comments, quotes, blank lines), merges the files in order with "first file wins", and then lets the real environment override everything. It is a simplified parser: real dotenv also supports multi-line values and variable expansion.

JS Which value wins?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

PORT is 4000 because .env.local is listed first. In the second run the real environment replaces DB_HOST even though a file defined it. Every value is still a string, including DB_PORT, which is exactly why a namespace factory or a validation step has to convert them.

Stand-in: a schema check that fails fast

The second stand-in is a small schema validator in the spirit of Joi plus a namespace factory in the spirit of registerAs(). It coerces strings to numbers and booleans, applies defaults, collects all problems instead of stopping at the first one, and refuses to produce a config object if there are any. It is far smaller than Joi and only supports four rule types.

JS Validate before starting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first call returns real numbers and booleans and a ready-made database namespace. The second fails with four messages at once (three bad values and the missing DATABASE_URL), so one deployment attempt is enough to fix everything. That "collect all errors" behavior is what abortEarly: false gives you in Joi.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. ConfigModule.forRoot({ envFilePath: ['.env.local', '.env'] }) finds PORT in both files. Which value is used, assuming PORT is not set in the real environment?

    When several files define the same variable, the earliest file in the array takes precedence. A variable already present in the real process environment beats both files.
  2. 2. What is the main benefit of validating environment variables when the application starts?

    Failing fast turns a mysterious production problem into a clear startup error, and an orchestrator can then keep the previous version running.
  3. 3. Why is config.get<number>('PORT') not enough to make PORT a number?

    Generics are erased at runtime. Convert in a registerAs() factory or let a Joi schema coerce the value.
  4. 4. What does registerAs('database', ...) give you besides the database. prefix for keys?

    databaseConfig.KEY is a token you can pass to @Inject(), and ConfigType<typeof databaseConfig> gives the injected object a precise type.

Summary

  • Settings live in the environment, not in code; .env files are a development convenience and must not hold committed secrets.
  • ConfigModule.forRoot() loads files (first file wins, the real environment overrides files); isGlobal: true avoids importing it everywhere.
  • Read values through ConfigService (get, getOrThrow) or, better, through typed namespaces created with registerAs() and injected with ConfigType.
  • Values start as strings: convert and validate them in one place, with a Joi validationSchema or a validate function.
  • Fail fast: report every invalid setting at boot, before the app accepts traffic.
  • Inject configuration instead of reading process.env in services, so tests can swap it.

Next, learn how to build modules that accept options like forRoot() does, and how provider lifetimes work, in Dynamic Modules and Provider Scopes.