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=
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
2. Install Nestjs Config
npm i --save @nestjs/config
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);
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);
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 {}
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!';
}
}
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
Top comments (0)