Learn NestJS Β· 9/14

Managing Configurations and Environments

10 min read

Course: NestJS

πŸ“œ Guide: Managing Configurations and Environments

Hey there! Welcome to the essential guide on managing configurations in your NestJS application. Let's be honest, juggling settings for development, testing, and production can feel like trying to herd cats. 🐈 If you've ever accidentally pushed a development database password to production, you know the special kind of panic that follows.

This guide will turn that chaos into calm, organized bliss. We'll learn how to handle application settings, secrets, and environment-specific variables like a pro.


1. The ConfigModule: Managing .env Files Safely πŸ›‘οΈ

The Problem: The Evils of Hardcoding

Imagine you're building an app. You need a database connection string, an API key for a payment gateway, and a port number. A beginner's first instinct might be to just slap them right into the code:

typescript
// src/app.service.ts
// 🚨 DANGER! DON'T DO THIS! 🚨
const DATABASE_URL = 'mongodb://user:supersecretpassword@dev-db:27017';
const API_KEY = 'pk_test_aBcDeFgHiJkLmNoPqRsTuVwXyZ';
const PORT = 3000;

This is a recipe for disaster!

  • Security Risk: Your "supersecretpassword" is now visible to anyone who can see your code. If you commit this to a public GitHub repository, bots will find your keys in minutes. Yikes.
  • Inflexible: What happens when you want to deploy to production? You have to manually change the DATABASE_URL to point to the production database. Forget to do it once, and you've got a major problem.
  • Collaboration Nightmare: Every developer on your team might need to use a different database string or port on their local machine, leading to constant changes and confusion.

The Solution: @nestjs/config and .env Files

The solution is to abstract our configuration away from the code. We store environment-specific variables in a special file, and our application reads from it. The industry-standard way to do this is with a .env file.

The @nestjs/config module is a fantastic wrapper around the popular dotenv library. It allows us to load variables from a .env file and access them throughout our application using a neat ConfigService.

Let's Get Practical!

Step 1: Installation πŸ› οΈ

First things first, let's install the necessary package.

bash
npm install --save @nestjs/config

Step 2: Create a .env file πŸ“„

In the root directory of your project (the same level as src and package.json), create a new file named .env.

bash
# .env

PORT=3001
DATABASE_URL="mongodb://user:mysecretpassword@localhost:27017/mydatabase"
API_KEY="pk_live_real_key_for_production"

✨ Fun Fact: .env files are designed to be simple key-value stores. It's a convention that has been adopted across the entire web development ecosystem, not just in Node.js!

🚨 IMPORTANT: Always, and I mean always, add your .env file to your .gitignore file. You never want to commit this file to version control.

bash
# .gitignore

# ... other entries
.env

Step 3: Load the ConfigModule πŸš€

Open your root AppModule (src/app.module.ts) and import ConfigModule. We'll use its .forRoot() method to load and parse our .env file.

typescript
// src/app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; // πŸ‘ˆ Import ConfigModule
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // πŸ‘ˆ Makes the ConfigService available everywhere
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

By setting isGlobal: true, we save ourselves the hassle of importing ConfigModule into every single module where we need to access our configuration. It’s like giving everyone in your application a library card to access the configuration library.

Step 4: Use the ConfigService πŸ‘¨β€πŸ”§

Now, let's use our newly configured service. We can inject ConfigService into any provider (like a service or controller) and use its .get() method to retrieve our variables.

typescript
// src/app.service.ts

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config'; // πŸ‘ˆ Import ConfigService

@Injectable()
export class AppService {
  constructor(private configService: ConfigService) {} // πŸ‘ˆ Inject it here

  getHello(): string {
    // Use the get() method to access environment variables
    const port = this.configService.get<number>('PORT');
    const dbUrl = this.configService.get<string>('DATABASE_URL');

    console.log(`Application is running on port: ${port}`);
    console.log(`Connecting to database at: ${dbUrl}`);

    return 'Hello World!';
  }
}

And that's it! You've successfully separated your configuration from your code. Now you can have different .env files for different environments without ever touching your source code. High five! πŸ™Œ


2. Validating Environment Variables on Startup βœ…

The Problem: Trust Issues with .env

So, we've moved our secrets to a .env file. Fantastic! But what happens if a new developer joins the team, pulls the code, and forgets to create their own .env file? Or what if they misspell DATABASE_URL as DB_URL?

The app will either crash in a weird, unhelpful way at runtime, or it'll fail silently, leaving you scratching your head wondering why it can't connect to the database. This is bad. We want our application to be loud and clear about its needs. It should shout, "Hey! You forgot to tell me the port number!" the moment it starts.

The Solution: Fail Fast with Validation

We can enforce a "contract" for our environment variables. We'll define a schema that says, "I absolutely need these variables, and they must be in this format." If the contract isn't met when the application starts, it will refuse to boot up and will tell you exactly why. This is a core principle of robust applications: fail fast.

For this, we'll use a powerful validation library called Joi.

Let's Get Practical!

Step 1: Install Joi πŸ“¦

bash
npm install --save joi

Step 2: Define a Validation Schema πŸ“

Now, let's tell ConfigModule how to validate our .env variables. We do this by adding a validationSchema to the forRoot() options.

typescript
// src/app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi'; // πŸ‘ˆ Import Joi
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: Joi.object({
        PORT: Joi.number().default(3000), // Default if not provided
        DATABASE_URL: Joi.string().required(), // Must be a string, and is required
        API_KEY: Joi.string().required(),
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Let's break down what Joi is doing:

  • Joi.object({...}): We're telling Joi to validate an object of key-value pairs (just like our .env file).
  • PORT: Joi.number().default(3000): We expect PORT to be a number. If it's not provided in the .env file, that's okay! We'll just use 3000 as a default.
  • DATABASE_URL: Joi.string().required(): We expect DATABASE_URL to be a string, and the .required() part means the application will throw an error on startup if this variable is missing.

Now, if you try to start the app without DATABASE_URL in your .env file, you'll get a beautiful, clear error message telling you exactly what's wrong. No more guesswork!


3. Custom Configuration Files and Namespaces πŸ—‚οΈ

The Problem: The "Junk Drawer" .env File

As your application grows, your .env file can become a dumping ground for everything: database credentials, email service keys, cache settings, feature flags... it gets messy, fast. It's like having one giant junk drawer for your entire house. Finding anything becomes a chore.

Wouldn't it be nice to group related settings? To have a "database" configuration object, an "email" configuration object, and so on?

The Solution: Typed and Namespaced Configurations

@nestjs/config allows us to move beyond the simple .env file and load configuration from dedicated TypeScript files. This gives us two huge benefits:

  1. Organization: We can group related variables into logical objects.
  2. Type Safety: We can use TypeScript to define the shape of our configuration objects, giving us amazing autocompletion and preventing typos.

Let's Get Practical!

Step 1: Create a Custom Configuration File πŸ“

Let's create a dedicated folder for our configuration files to keep things tidy.

Create a new folder src/config and inside it, a file named database.config.ts.

typescript
// src/config/database.config.ts

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

export default registerAs('database', () => ({
  url: process.env.DATABASE_URL,
  host: process.env.DATABASE_HOST,
  port: parseInt(process.env.DATABASE_PORT, 10) || 5432,
}));

The registerAs function is key here. It takes a token (the string 'database') and a function that returns our configuration object. This token will become our namespace.

Step 2: Load the Custom Configuration πŸ”Œ

Next, we need to tell ConfigModule to load this file. We do this using the load property in the forRoot() options.

typescript
// src/app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import databaseConfig from './config/database.config'; // πŸ‘ˆ Import our new config file

// ... other imports

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [databaseConfig], // πŸ‘ˆ Load the custom config
      // We can still keep Joi validation for the raw .env variables!
      // validationSchema: ...
    }),
  ],
  // ...
})
export class AppModule {}

Step 3: Access Namespaced Configuration 🎯

Now, we can access these grouped variables with a clean, dot-syntax.

typescript
// src/some.service.ts

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

@Injectable()
export class SomeService {
  constructor(private configService: ConfigService) {
    // Access the entire database object
    const dbConfig = this.configService.get('database');
    console.log(dbConfig.host, dbConfig.port);

    // Or access a specific property directly
    const dbHost = this.configService.get<string>('database.host');
    const dbPort = this.configService.get<number>('database.port');

    console.log(`Connecting to database host: ${dbHost} on port ${dbPort}`);
  }
}

Look at that! configService.get('database.host'). It's clean, readable, and way more organized. Your future self will thank you.


4. Dynamic Modules: A Gentle Introduction βš™οΈ

The Problem: The Chicken and Egg Situation

Okay, so we have our awesome, namespaced database configuration. Now we want to set up our database module (like TypeOrmModule). The TypeOrmModule needs the database configuration to connect.

But wait... how can we give TypeOrmModule the configuration from ConfigService if ConfigService isn't available until after all the modules are initialized? It's a classic chicken-and-egg problem.

The Solution: forRootAsync

This is where the concept of Dynamic Modules comes into play. You've already used one: ConfigModule.forRoot({...}) is a static method that makes the module dynamic! It allows you to pass in options.

Many NestJS modules that require configuration provide an asynchronous version of this method, usually called forRootAsync. This method allows a module to wait for other modules (like our ConfigModule) to be ready before it configures itself.

It's like telling NestJS: "Hey, before you set up the TypeOrmModule, you need to import ConfigModule first. Then, use this little factory function to inject the ConfigService and get the database details. Then you can finish setting up the TypeOrmModule."

Let's Get Practical!

Here is a common, real-world example of using TypeOrmModule.forRootAsync to solve this exact problem.

typescript
// In a feature module, e.g., src/users/users.module.ts
// Or in your AppModule if the connection is global

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule], // πŸ‘ˆ 1. Make ConfigModule available
      inject: [ConfigService],  // πŸ‘ˆ 2. Inject the ConfigService
      useFactory: async (configService: ConfigService) => ({ // πŸ‘ˆ 3. Use the factory
        type: 'postgres',
        host: configService.get<string>('database.host'),
        port: configService.get<number>('database.port'),
        username: configService.get<string>('database.user'),
        password: configService.get<string>('database.password'),
        database: configService.get<string>('database.name'),
        entities: [/* ... your entities ... */],
        synchronize: true, // Be careful with this in production!
      }),
    }),
    // ... other imports for this module
  ],
  // ... controllers and providers
})
export class UsersModule {}

This pattern is incredibly powerful and is used all over the NestJS ecosystem. By understanding useFactory and inject, you can connect any configurable module to your centralized ConfigService, keeping your application clean, robust, and easy to manage.


Further Reading πŸ“š

Challenge

Challenge: Dynamic Module Configuration with Validation

Your task is to implement a robust, namespaced configuration for a mock DatabaseModule using NestJS's configuration patterns. You will need to define a custom configuration, validate environment variables, and use the forRootAsync pattern to inject the configuration into a dynamic module.

Requirements:

  1. Create a Namespaced Configuration: In the conceptual file database.config.ts, use the registerAs function to create a configuration namespace named 'database'. This configuration should read DB_HOST, DB_PORT, and DB_NAME from process.env.

  2. Implement a Dynamic Module: In database.module.ts, implement the DatabaseModule as a dynamic module. It must have a static method forRootAsync that uses the standard pattern (useFactory, inject, imports) to provide a mock connection object based on the configuration it receives.

  3. Configure the Root Module (AppModule):

    • Set up the ConfigModule to be global (isGlobal: true).
    • Load your custom databaseConfig using the load property.
    • Implement a validationSchema using Joi to enforce the following rules on startup:
      • DB_HOST: must be a required string.
      • DB_PORT: must be a number and default to 5432 if not provided.
      • DB_NAME: must be a required string.
  4. Connect Everything: In the AppModule, import and configure your DatabaseModule using its forRootAsync method. The factory function should inject ConfigService to retrieve the 'database' configuration and provide it to the DatabaseModule.

Expected result

Your final implementation should correctly configure a NestJS application with a type-safe, validated, and dynamic configuration for a database module.

database.config.ts

This file should export a default function call to registerAs. The first argument must be the string 'database'. The second argument should be a factory function that returns an object mapping environment variables (DB_HOST, DB_PORT, DB_NAME) to configuration properties (host, port, name). The port should be parsed to an integer.

database.module.ts

The DatabaseModule must have a static forRootAsync method that returns a DynamicModule. This method should use the useFactory pattern to create a provider for the DATABASE_CONNECTION token. The factory will inject ConfigService, get the 'database' configuration, and provide a value, for example, a connection string like postgresql://${host}:${port}/${name}.

app.module.ts

Within the AppModule's imports array:

  1. ConfigModule.forRoot should be configured with isGlobal: true, load: [databaseConfig], and a validationSchema property. The schema, created with Joi.object(), must define DB_HOST as a required string, DB_PORT as a number with a default of 5432, and DB_NAME as a required string.
  2. DatabaseModule.forRootAsync() should be correctly called and configured, with its imports including ConfigModule, inject including ConfigService, and a useFactory that correctly retrieves the 'database' namespace configuration.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.