Configuration namespaces help organize settings into groups. This makes managing app settings easier and clearer.
0
0
Configuration namespaces in NestJS
Introduction
When your app has many settings that belong to different parts, like database and server.
When you want to avoid mixing unrelated configuration values.
When you want to load or override settings for specific parts without affecting others.
When you want to keep your configuration clean and easy to read.
When you want to share configuration logic across modules in a structured way.
Syntax
NestJS
import { registerAs } from '@nestjs/config'; export const databaseConfig = registerAs('database', () => ({ host: process.env.DB_HOST || 'localhost', port: parseInt(process.env.DB_PORT || '5432', 10), }));
registerAs creates a named configuration namespace.
The first argument is the namespace name as a string.
Examples
This creates a
server namespace with port and debug settings.NestJS
import { registerAs } from '@nestjs/config'; export const serverConfig = registerAs('server', () => ({ port: parseInt(process.env.SERVER_PORT || '3000', 10), debug: process.env.DEBUG === 'true', }));
This creates an
auth namespace for authentication settings.NestJS
import { registerAs } from '@nestjs/config'; export const authConfig = registerAs('auth', () => ({ jwtSecret: process.env.JWT_SECRET || 'defaultsecret', expiresIn: process.env.JWT_EXPIRES || '3600s', }));
Sample Program
This example shows how to create a database namespace, load it with ConfigModule, and use a factory provider to read and log the settings using ConfigService with the namespace prefix.
NestJS
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { registerAs } from '@nestjs/config'; const databaseConfig = registerAs('database', () => ({ host: process.env.DB_HOST || 'localhost', port: parseInt(process.env.DB_PORT || '5432', 10), })); @Module({ imports: [ ConfigModule.forRoot({ load: [databaseConfig], }), ], providers: [ { provide: 'DB_CONFIG_LOGGER', useFactory: (configService: ConfigService) => { const dbHost = configService.get('database.host'); const dbPort = configService.get('database.port'); console.log(`Database Host: ${dbHost}`); console.log(`Database Port: ${dbPort}`); return null; }, inject: [ConfigService], }, ], }) export class AppModule {}
OutputSuccess
Important Notes
Namespaces help avoid name clashes between different config parts.
You access values using dot notation like namespace.key.
Use environment variables inside namespaces for flexible settings.
Summary
Configuration namespaces group related settings together.
Use registerAs to create namespaces in NestJS.
Access namespaced settings with dot notation via ConfigService.