DEV Community

Tamim Ikbal
Tamim Ikbal

Posted on

1 1

How to Set Up Custom Configuration Files in NestJS

Hello my friends, I Hope you are all doing well. Today we will learn how to set up the custom config file in nestjs.

NestJS is a powerful JavaScript framework that provides all the essential functionalities needed for building scalable applications. However, it's not fully structured, you need to organize it yourself. While NestJS provides recommendations, it's up to us to implement a clean and maintainable configuration setup.

In this guide, we will set up a custom configuration file to keep our application settings structured and easy to manage. Let’s get started!

Let's say you have an env file with some different type of variable, for example:

APP_NAME=Laravel
APP_ENV=local
APP_TIMEZONE=UTC

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Enter fullscreen mode Exit fullscreen mode

Now, We can get and use them by process.env in our js code which is not ideal for production because of performance, security, and caching.

So, let’s create a config file for them but here also we shouldn't tie them into one file then we will break SRP and this will be harder to manage. So, let's do this step by step.

1. Creating our NestJS Project

To create a NestJs project, we need to run the following commands in our terminal.

npm i -g @nestjs/cli
nest new project-name
Enter fullscreen mode Exit fullscreen mode

2. Install Nestjs Config

npm i --save @nestjs/config
Enter fullscreen mode Exit fullscreen mode

3. Make the configuration file

Create the respective configuration files in the src/config folder. In this case, app.config.js and database.config.js.

4. Write the Config File

app.config.js

import * as process from 'node:process';
import { registerAs } from '@nestjs/config';

const config = () => ({
  name: process.env.APP_NAME || 'NestApp',
  env: process.env.APP_ENV || 'production',
  debug: process.env.APP_DEBUG === 'true',
  timezone: process.env.APP_TIMEZONE || 'UTC',
  locale: process.env.APP_LOCALE || 'en',
});

export default registerAs('app', config);
Enter fullscreen mode Exit fullscreen mode

database.config.js

import * as process from 'node:process';
import { registerAs } from '@nestjs/config';

const config = () => ({
  database: process.env.DB_CONNECTION || 'mysql',
  connection: {
    mysql: {
      type: 'mysql',
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT, 10) || 3306,
      username: process.env.DB_USERNAME || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || '',
      entities: ['./../Models/*.entity{.ts,.js}'],
      migrations: ['./../database/migrations/*{.ts,.js}'],
      synchronize: false,
      migrationsRun: false,
      logging: process.env.DB_LOGGING === 'true',
    },
  },
});

export default registerAs('database', config);
Enter fullscreen mode Exit fullscreen mode
Explanation

We define a configuration object and export it using nestjs registerAs(), which provides a namespace (prefix) for the configuration to avoid conflict between config key.

5. Import and Setup the ConfigModule

app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import appConfig from './config/app.config';
import databaseConfig from './config/database.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // Makes config accessible throughout the application
      load: [appConfig, databaseConfig],
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

6. Using Config Values in the Application

app.service.ts

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

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

  getHello(): string {
    console.log(this.config.get('app.name')); // Fetching APP_NAME from config
    return 'Hello World!';
  }
}
Enter fullscreen mode Exit fullscreen mode

That’s it! Now you have a powerful and organized configuration setup in NestJS. 🚀

Thanks for reading! 🙌

To Read more about Nest COnfig Please Visit: https://docs.nestjs.com/techniques/configuration

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more