Configuration namespaces help organize settings into groups. This makes managing app settings easier and clearer.
Configuration namespaces in 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.
server namespace with port and debug settings.import { registerAs } from '@nestjs/config'; export const serverConfig = registerAs('server', () => ({ port: parseInt(process.env.SERVER_PORT || '3000', 10), debug: process.env.DEBUG === 'true', }));
auth namespace for authentication settings.import { registerAs } from '@nestjs/config'; export const authConfig = registerAs('auth', () => ({ jwtSecret: process.env.JWT_SECRET || 'defaultsecret', expiresIn: process.env.JWT_EXPIRES || '3600s', }));
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.
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 {}
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.
Configuration namespaces group related settings together.
Use registerAs to create namespaces in NestJS.
Access namespaced settings with dot notation via ConfigService.
Practice
registerAs in NestJS configuration?Solution
Step 1: Understand the role of
registerAsregisterAsis used to define a configuration namespace, grouping related settings under one name.Step 2: Differentiate from other NestJS features
It is not used for middleware, modules, or database connections, which are handled differently.
Final Answer:
To create a named namespace grouping related configuration settings -> Option DQuick Check:
registerAs creates config namespaces = A [OK]
- Confusing registerAs with module registration
- Thinking registerAs sets up middleware
- Assuming registerAs creates database connections
registerAs?Solution
Step 1: Check correct export and function syntax
The correct pattern is to export a constant assigned toregisterAswith a name and a function returning an object.Step 2: Identify syntax errors in options
export default registerAs('database', () => ({ host: 'localhost' })); uses default export but misses const assignment. registerAs('database', { host: 'localhost' }); passes object directly, not a function. registerAs('database', () => { host: 'localhost' }); misses returning an object (no parentheses).Final Answer:
export const database = registerAs('database', () => ({ host: 'localhost' })); -> Option AQuick Check:
Correct syntax = A [OK]
- Passing object directly instead of function
- Missing export const declaration
- Not returning an object from the function
export const appConfig = registerAs('app', () => ({ port: 3000, env: 'dev' }));What will
configService.get('app.port') return?Solution
Step 1: Understand dot notation access in ConfigService
UsingconfigService.get('app.port')accesses the 'port' key inside the 'app' namespace.Step 2: Check the registered config values
The 'app' namespace returns an object withport: 3000, so the call returns 3000.Final Answer:
3000 -> Option AQuick Check:
configService.get('namespace.key') returns value = B [OK]
- Expecting the string 'app.port' as output
- Assuming undefined if namespace not accessed properly
- Thinking it throws an error for valid keys
export const apiConfig = registerAs('api', () => ({ url: 'https://api.example.com' }));
// Later in service
const url = configService.get('api.url');What is the likely cause if
url is undefined?Solution
Step 1: Check registration of namespace
If the 'api' namespace is not imported or registered in the ConfigModule, its keys won't be available.Step 2: Verify key existence and usage
The key 'url' exists in the namespace, and dot notation is supported, so these are not issues.Step 3: Consider injection issues
While injection problems can cause errors, they usually throw exceptions, not silently return undefined.Final Answer:
The namespace 'api' was not imported or registered in ConfigModule -> Option BQuick Check:
Missing namespace registration = D [OK]
- Assuming dot notation is unsupported
- Thinking missing key causes error instead of undefined
- Ignoring namespace registration step
export const dbConfig = registerAs('database', () => ({ host: 'localhost', port: 5432 }));
export const authConfig = registerAs('auth', () => ({ jwtSecret: 'secret' }));How can you access the JWT secret inside a service using
ConfigService and ensure type safety?Solution
Step 1: Use dot notation with namespace and key
To access the JWT secret, use'auth.jwtSecret'to specify the namespace and key.Step 2: Apply type safety with generic parameter
Pass<string>togetto ensure the returned value is typed as string.Step 3: Eliminate incorrect options
const secret = configService.get('jwtSecret'); misses namespace, A uses wrong type, D uses wrong namespace.Final Answer:
const secret = configService.get<string>('auth.jwtSecret'); -> Option CQuick Check:
Use namespace.key with type param = C [OK]
- Omitting namespace in key string
- Using wrong type parameter
- Accessing key from wrong namespace
Ready to prove it?
Pass the test and this pattern moves unknown
